Home | History | Annotate | Download | only in setup
      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 // This file defines the methods useful for uninstalling Chrome.
      6 
      7 #include "chrome/installer/setup/uninstall.h"
      8 
      9 #include <windows.h>
     10 
     11 #include <vector>
     12 
     13 #include "base/file_util.h"
     14 #include "base/files/file_enumerator.h"
     15 #include "base/path_service.h"
     16 #include "base/process/kill.h"
     17 #include "base/strings/string16.h"
     18 #include "base/strings/string_number_conversions.h"
     19 #include "base/strings/string_util.h"
     20 #include "base/strings/utf_string_conversions.h"
     21 #include "base/win/registry.h"
     22 #include "base/win/scoped_handle.h"
     23 #include "base/win/shortcut.h"
     24 #include "base/win/windows_version.h"
     25 #include "chrome/common/chrome_constants.h"
     26 #include "chrome/common/chrome_paths_internal.h"
     27 #include "chrome/common/chrome_result_codes.h"
     28 #include "chrome/installer/launcher_support/chrome_launcher_support.h"
     29 #include "chrome/installer/setup/install.h"
     30 #include "chrome/installer/setup/install_worker.h"
     31 #include "chrome/installer/setup/setup_constants.h"
     32 #include "chrome/installer/setup/setup_util.h"
     33 #include "chrome/installer/util/auto_launch_util.h"
     34 #include "chrome/installer/util/browser_distribution.h"
     35 #include "chrome/installer/util/channel_info.h"
     36 #include "chrome/installer/util/delete_after_reboot_helper.h"
     37 #include "chrome/installer/util/google_update_constants.h"
     38 #include "chrome/installer/util/google_update_settings.h"
     39 #include "chrome/installer/util/helper.h"
     40 #include "chrome/installer/util/install_util.h"
     41 #include "chrome/installer/util/installation_state.h"
     42 #include "chrome/installer/util/installer_state.h"
     43 #include "chrome/installer/util/logging_installer.h"
     44 #include "chrome/installer/util/self_cleaning_temp_dir.h"
     45 #include "chrome/installer/util/shell_util.h"
     46 #include "chrome/installer/util/util_constants.h"
     47 #include "content/public/common/result_codes.h"
     48 #include "extensions/common/constants.h"
     49 #include "rlz/lib/rlz_lib.h"
     50 
     51 // Build-time generated include file.
     52 #include "registered_dlls.h"  // NOLINT
     53 
     54 using base::win::RegKey;
     55 using installer::InstallStatus;
     56 using installer::MasterPreferences;
     57 
     58 namespace {
     59 
     60 // Avoid leaving behind a Temp dir.  If one exists, ask SelfCleaningTempDir to
     61 // clean it up for us.  This may involve scheduling it for deletion after
     62 // reboot.  Don't report that a reboot is required in this case, however.
     63 // TODO(erikwright): Shouldn't this still lead to
     64 // ScheduleParentAndGrandparentForDeletion?
     65 void DeleteInstallTempDir(const base::FilePath& target_path) {
     66   base::FilePath temp_path(target_path.DirName().Append(
     67       installer::kInstallTempDir));
     68   if (base::DirectoryExists(temp_path)) {
     69     installer::SelfCleaningTempDir temp_dir;
     70     if (!temp_dir.Initialize(target_path.DirName(),
     71                              installer::kInstallTempDir) ||
     72         !temp_dir.Delete()) {
     73       LOG(ERROR) << "Failed to delete temp dir " << temp_path.value();
     74     }
     75   }
     76 }
     77 
     78 // Iterates over the list of distribution types in |dist_types|, and
     79 // adds to |update_list| the work item to update the corresponding "ap"
     80 // registry value specified in |channel_info|.
     81 void AddChannelValueUpdateWorkItems(
     82     const installer::InstallationState& original_state,
     83     const installer::InstallerState& installer_state,
     84     const installer::ChannelInfo& channel_info,
     85     const std::vector<BrowserDistribution::Type>& dist_types,
     86     WorkItemList* update_list) {
     87   const bool system_level = installer_state.system_install();
     88   const HKEY reg_root = installer_state.root_key();
     89   for (size_t i = 0; i < dist_types.size(); ++i) {
     90     BrowserDistribution::Type dist_type = dist_types[i];
     91     const installer::ProductState* product_state =
     92         original_state.GetProductState(system_level, dist_type);
     93     // Only modify other products if they're installed and multi.
     94     if (product_state != NULL &&
     95         product_state->is_multi_install() &&
     96         !product_state->channel().Equals(channel_info)) {
     97       BrowserDistribution* other_dist =
     98           BrowserDistribution::GetSpecificDistribution(dist_type);
     99       update_list->AddSetRegValueWorkItem(reg_root, other_dist->GetStateKey(),
    100           google_update::kRegApField, channel_info.value(), true);
    101     } else {
    102       LOG_IF(ERROR,
    103              product_state != NULL && product_state->is_multi_install())
    104           << "Channel value for "
    105           << BrowserDistribution::GetSpecificDistribution(
    106                  dist_type)->GetDisplayName()
    107           << " is somehow already set to the desired new value of "
    108           << channel_info.value();
    109     }
    110   }
    111 }
    112 
    113 // Makes appropriate changes to the Google Update "ap" value in the registry.
    114 // Specifically, removes the flags associated with this product ("-chrome" or
    115 // "-chromeframe") from the "ap" values for all other installed products and for
    116 // the multi-installer package.
    117 void ProcessGoogleUpdateItems(
    118     const installer::InstallationState& original_state,
    119     const installer::InstallerState& installer_state,
    120     const installer::Product& product) {
    121   DCHECK(installer_state.is_multi_install());
    122   const bool system_level = installer_state.system_install();
    123   BrowserDistribution* distribution = product.distribution();
    124   const installer::ProductState* product_state =
    125       original_state.GetProductState(system_level, distribution->GetType());
    126   DCHECK(product_state != NULL);
    127   installer::ChannelInfo channel_info;
    128 
    129   // Remove product's flags from the channel value.
    130   channel_info.set_value(product_state->channel().value());
    131   const bool modified = product.SetChannelFlags(false, &channel_info);
    132 
    133   // Apply the new channel value to all other products and to the multi package.
    134   if (modified) {
    135     scoped_ptr<WorkItemList>
    136         update_list(WorkItem::CreateNoRollbackWorkItemList());
    137     std::vector<BrowserDistribution::Type> dist_types;
    138     for (size_t i = 0; i < BrowserDistribution::NUM_TYPES; ++i) {
    139       BrowserDistribution::Type other_dist_type =
    140           static_cast<BrowserDistribution::Type>(i);
    141       if (distribution->GetType() != other_dist_type)
    142         dist_types.push_back(other_dist_type);
    143     }
    144     AddChannelValueUpdateWorkItems(original_state, installer_state,
    145                                    channel_info, dist_types,
    146                                    update_list.get());
    147     bool success = update_list->Do();
    148     LOG_IF(ERROR, !success) << "Failed updating channel values.";
    149   }
    150 }
    151 
    152 void ProcessOnOsUpgradeWorkItems(
    153     const installer::InstallerState& installer_state,
    154     const installer::Product& product) {
    155   scoped_ptr<WorkItemList> work_item_list(
    156       WorkItem::CreateNoRollbackWorkItemList());
    157   AddOsUpgradeWorkItems(installer_state, base::FilePath(), Version(), product,
    158                         work_item_list.get());
    159   if (!work_item_list->Do())
    160     LOG(ERROR) << "Failed to remove on-os-upgrade command.";
    161 }
    162 
    163 void ProcessIELowRightsPolicyWorkItems(
    164     const installer::InstallerState& installer_state) {
    165   scoped_ptr<WorkItemList> work_items(WorkItem::CreateNoRollbackWorkItemList());
    166   AddDeleteOldIELowRightsPolicyWorkItems(installer_state, work_items.get());
    167   work_items->Do();
    168   installer::RefreshElevationPolicy();
    169 }
    170 
    171 void ClearRlzProductState() {
    172   const rlz_lib::AccessPoint points[] = {rlz_lib::CHROME_OMNIBOX,
    173                                          rlz_lib::CHROME_HOME_PAGE,
    174                                          rlz_lib::NO_ACCESS_POINT};
    175 
    176   rlz_lib::ClearProductState(rlz_lib::CHROME, points);
    177 
    178   // If chrome has been reactivated, clear all events for this brand as well.
    179   string16 reactivation_brand_wide;
    180   if (GoogleUpdateSettings::GetReactivationBrand(&reactivation_brand_wide)) {
    181     std::string reactivation_brand(WideToASCII(reactivation_brand_wide));
    182     rlz_lib::SupplementaryBranding branding(reactivation_brand.c_str());
    183     rlz_lib::ClearProductState(rlz_lib::CHROME, points);
    184   }
    185 }
    186 
    187 // Decides whether setup.exe and the installer archive should be removed based
    188 // on the original and installer states:
    189 // * non-multi product being uninstalled: remove both
    190 // * any multi product left besides App Host: keep both
    191 // * only App Host left: keep setup.exe
    192 void CheckShouldRemoveSetupAndArchive(
    193     const installer::InstallationState& original_state,
    194     const installer::InstallerState& installer_state,
    195     bool* remove_setup,
    196     bool* remove_archive) {
    197   *remove_setup = true;
    198   *remove_archive = true;
    199 
    200   // If any multi-install product is left (other than App Host) we must leave
    201   // the installer and archive. For the App Host, we only leave the installer.
    202   if (!installer_state.is_multi_install()) {
    203     VLOG(1) << "Removing all installer files for a non-multi installation.";
    204   } else {
    205     // Loop through all known products...
    206     for (size_t i = 0; i < BrowserDistribution::NUM_TYPES; ++i) {
    207       BrowserDistribution::Type dist_type =
    208           static_cast<BrowserDistribution::Type>(i);
    209       const installer::ProductState* product_state =
    210           original_state.GetProductState(
    211               installer_state.system_install(), dist_type);
    212       // If the product is installed, in multi mode, and is not part of the
    213       // active uninstallation...
    214       if (product_state && product_state->is_multi_install() &&
    215           !installer_state.FindProduct(dist_type)) {
    216         // setup.exe will not be removed as there is a remaining multi-install
    217         // product.
    218         *remove_setup = false;
    219         // As a special case, we can still remove the actual archive if the
    220         // only remaining product is the App Host.
    221         if (dist_type != BrowserDistribution::CHROME_APP_HOST) {
    222           VLOG(1) << "Keeping all installer files due to a remaining "
    223                   << "multi-install product.";
    224           *remove_archive = false;
    225           return;
    226         }
    227         VLOG(1) << "Keeping setup.exe due to a remaining "
    228                 << "app-host installation.";
    229       }
    230     }
    231     VLOG(1) << "Removing the installer archive.";
    232     if (remove_setup)
    233       VLOG(1) << "Removing setup.exe.";
    234   }
    235 }
    236 
    237 // Removes all files from the installer directory, leaving setup.exe iff
    238 // |remove_setup| is false.
    239 // Returns false in case of an error.
    240 bool RemoveInstallerFiles(const base::FilePath& installer_directory,
    241                           bool remove_setup) {
    242   base::FileEnumerator file_enumerator(
    243       installer_directory,
    244       false,
    245       base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES);
    246   bool success = true;
    247 
    248   base::FilePath setup_exe_base_name(installer::kSetupExe);
    249 
    250   while (true) {
    251     base::FilePath to_delete(file_enumerator.Next());
    252     if (to_delete.empty())
    253       break;
    254     if (!remove_setup && to_delete.BaseName() == setup_exe_base_name)
    255       continue;
    256 
    257     VLOG(1) << "Deleting installer path " << to_delete.value();
    258     if (!base::DeleteFile(to_delete, true)) {
    259       LOG(ERROR) << "Failed to delete path: " << to_delete.value();
    260       success = false;
    261     }
    262   }
    263 
    264   return success;
    265 }
    266 
    267 }  // namespace
    268 
    269 namespace installer {
    270 
    271 // Kills all Chrome processes, immediately.
    272 void CloseAllChromeProcesses() {
    273   base::CleanupProcesses(installer::kChromeExe, base::TimeDelta(),
    274                          content::RESULT_CODE_HUNG, NULL);
    275   base::CleanupProcesses(installer::kNaClExe, base::TimeDelta(),
    276                          content::RESULT_CODE_HUNG, NULL);
    277 }
    278 
    279 // Attempts to close the Chrome Frame helper process by sending WM_CLOSE
    280 // messages to its window, or just killing it if that doesn't work.
    281 void CloseChromeFrameHelperProcess() {
    282   HWND window = FindWindow(installer::kChromeFrameHelperWndClass, NULL);
    283   if (!::IsWindow(window))
    284     return;
    285 
    286   const DWORD kWaitMs = 3000;
    287 
    288   DWORD pid = 0;
    289   ::GetWindowThreadProcessId(window, &pid);
    290   DCHECK_NE(pid, 0U);
    291   base::win::ScopedHandle process(::OpenProcess(SYNCHRONIZE, FALSE, pid));
    292   PLOG_IF(INFO, !process) << "Failed to open process: " << pid;
    293 
    294   bool kill = true;
    295   if (SendMessageTimeout(window, WM_CLOSE, 0, 0, SMTO_BLOCK, kWaitMs, NULL) &&
    296       process) {
    297     VLOG(1) << "Waiting for " << installer::kChromeFrameHelperExe;
    298     DWORD wait = ::WaitForSingleObject(process, kWaitMs);
    299     if (wait != WAIT_OBJECT_0) {
    300       LOG(WARNING) << "Wait for " << installer::kChromeFrameHelperExe
    301                    << " to exit failed or timed out.";
    302     } else {
    303       kill = false;
    304       VLOG(1) << installer::kChromeFrameHelperExe << " exited normally.";
    305     }
    306   }
    307 
    308   if (kill) {
    309     VLOG(1) << installer::kChromeFrameHelperExe << " hung.  Killing.";
    310     base::CleanupProcesses(installer::kChromeFrameHelperExe, base::TimeDelta(),
    311                            content::RESULT_CODE_HUNG, NULL);
    312   }
    313 }
    314 
    315 // Updates shortcuts to |old_target_exe| that have non-empty args, making them
    316 // target |new_target_exe| instead. The non-empty args requirement is a
    317 // heuristic to determine whether a shortcut is "user-generated". This routine
    318 // can only be called for user-level installs.
    319 void RetargetUserShortcutsWithArgs(const InstallerState& installer_state,
    320                                    const Product& product,
    321                                    const base::FilePath& old_target_exe,
    322                                    const base::FilePath& new_target_exe) {
    323   if (installer_state.system_install()) {
    324     NOTREACHED();
    325     return;
    326   }
    327   BrowserDistribution* dist = product.distribution();
    328   ShellUtil::ShellChange install_level = ShellUtil::CURRENT_USER;
    329   ShellUtil::ShortcutProperties updated_properties(install_level);
    330   updated_properties.set_target(new_target_exe);
    331 
    332   // Retarget all shortcuts that point to |old_target_exe| from all
    333   // ShellUtil::ShortcutLocations.
    334   VLOG(1) << "Retargeting shortcuts.";
    335   for (int location = ShellUtil::SHORTCUT_LOCATION_FIRST;
    336       location < ShellUtil::NUM_SHORTCUT_LOCATIONS; ++location) {
    337     if (!ShellUtil::UpdateShortcutsWithArgs(
    338             static_cast<ShellUtil::ShortcutLocation>(location), dist,
    339             install_level, old_target_exe, updated_properties)) {
    340       LOG(WARNING) << "Failed to retarget shortcuts in ShortcutLocation: "
    341                    << location;
    342     }
    343   }
    344 }
    345 
    346 // Deletes shortcuts at |install_level| from Start menu, Desktop,
    347 // Quick Launch, taskbar, and secondary tiles on the Start Screen (Win8+).
    348 // Only shortcuts pointing to |target_exe| will be removed.
    349 void DeleteShortcuts(const InstallerState& installer_state,
    350                      const Product& product,
    351                      const base::FilePath& target_exe) {
    352   BrowserDistribution* dist = product.distribution();
    353 
    354   // The per-user shortcut for this user, if present on a system-level install,
    355   // has already been deleted in chrome_browser_main_win.cc::DoUninstallTasks().
    356   ShellUtil::ShellChange install_level = installer_state.system_install() ?
    357       ShellUtil::SYSTEM_LEVEL : ShellUtil::CURRENT_USER;
    358 
    359   // Delete and unpin all shortcuts that point to |target_exe| from all
    360   // ShellUtil::ShortcutLocations.
    361   VLOG(1) << "Deleting shortcuts.";
    362   for (int location = ShellUtil::SHORTCUT_LOCATION_FIRST;
    363       location < ShellUtil::NUM_SHORTCUT_LOCATIONS; ++location) {
    364     if (!ShellUtil::RemoveShortcuts(
    365             static_cast<ShellUtil::ShortcutLocation>(location), dist,
    366             install_level, target_exe)) {
    367       LOG(WARNING) << "Failed to delete shortcuts in ShortcutLocation:"
    368                    << location;
    369     }
    370   }
    371 }
    372 
    373 bool ScheduleParentAndGrandparentForDeletion(const base::FilePath& path) {
    374   base::FilePath parent_dir = path.DirName();
    375   bool ret = ScheduleFileSystemEntityForDeletion(parent_dir);
    376   if (!ret) {
    377     LOG(ERROR) << "Failed to schedule parent dir for deletion: "
    378                << parent_dir.value();
    379   } else {
    380     base::FilePath grandparent_dir(parent_dir.DirName());
    381     ret = ScheduleFileSystemEntityForDeletion(grandparent_dir);
    382     if (!ret) {
    383       LOG(ERROR) << "Failed to schedule grandparent dir for deletion: "
    384                  << grandparent_dir.value();
    385     }
    386   }
    387   return ret;
    388 }
    389 
    390 // Deletes the given directory if it is empty. Returns DELETE_SUCCEEDED if the
    391 // directory is deleted, DELETE_NOT_EMPTY if it is not empty, and DELETE_FAILED
    392 // otherwise.
    393 DeleteResult DeleteEmptyDir(const base::FilePath& path) {
    394   if (!base::IsDirectoryEmpty(path))
    395     return DELETE_NOT_EMPTY;
    396 
    397   if (base::DeleteFile(path, true))
    398     return DELETE_SUCCEEDED;
    399 
    400   LOG(ERROR) << "Failed to delete folder: " << path.value();
    401   return DELETE_FAILED;
    402 }
    403 
    404 void GetLocalStateFolders(const Product& product,
    405                           std::vector<base::FilePath>* paths) {
    406   // Obtain the location of the user profile data.
    407   product.GetUserDataPaths(paths);
    408   LOG_IF(ERROR, paths->empty())
    409       << "Could not retrieve user's profile directory.";
    410 }
    411 
    412 // Creates a copy of the local state file and returns a path to the copy.
    413 base::FilePath BackupLocalStateFile(
    414     const std::vector<base::FilePath>& local_state_folders) {
    415   base::FilePath backup;
    416 
    417   // Copy the first local state file that is found.
    418   for (size_t i = 0; i < local_state_folders.size(); ++i) {
    419     const base::FilePath& local_state_folder = local_state_folders[i];
    420     base::FilePath state_file(
    421         local_state_folder.Append(chrome::kLocalStateFilename));
    422     if (!base::PathExists(state_file))
    423       continue;
    424     if (!base::CreateTemporaryFile(&backup))
    425       LOG(ERROR) << "Failed to create temporary file for Local State.";
    426     else
    427       base::CopyFile(state_file, backup);
    428     break;
    429   }
    430   return backup;
    431 }
    432 
    433 // Deletes all user data directories for a product.
    434 DeleteResult DeleteLocalState(
    435     const std::vector<base::FilePath>& local_state_folders,
    436     bool schedule_on_failure) {
    437   if (local_state_folders.empty())
    438     return DELETE_SUCCEEDED;
    439 
    440   DeleteResult result = DELETE_SUCCEEDED;
    441   for (size_t i = 0; i < local_state_folders.size(); ++i) {
    442     const base::FilePath& user_local_state = local_state_folders[i];
    443     VLOG(1) << "Deleting user profile " << user_local_state.value();
    444     if (!base::DeleteFile(user_local_state, true)) {
    445       LOG(ERROR) << "Failed to delete user profile dir: "
    446                  << user_local_state.value();
    447       if (schedule_on_failure) {
    448         ScheduleDirectoryForDeletion(user_local_state);
    449         result = DELETE_REQUIRES_REBOOT;
    450       } else {
    451         result = DELETE_FAILED;
    452       }
    453     }
    454   }
    455 
    456   if (result == DELETE_REQUIRES_REBOOT) {
    457     ScheduleParentAndGrandparentForDeletion(local_state_folders[0]);
    458   } else {
    459     const base::FilePath user_data_dir(local_state_folders[0].DirName());
    460     if (!user_data_dir.empty() &&
    461         DeleteEmptyDir(user_data_dir) == DELETE_SUCCEEDED) {
    462       const base::FilePath product_dir(user_data_dir.DirName());
    463       if (!product_dir.empty())
    464         DeleteEmptyDir(product_dir);
    465     }
    466   }
    467 
    468   return result;
    469 }
    470 
    471 // Moves setup to a temporary file, outside of the install folder. Also attempts
    472 // to change the current directory to the TMP directory. On Windows, each
    473 // process has a handle to its CWD. If setup.exe's CWD happens to be within the
    474 // install directory, deletion will fail as a result of the open handle.
    475 bool MoveSetupOutOfInstallFolder(const InstallerState& installer_state,
    476                                  const base::FilePath& setup_exe) {
    477   bool ret = false;
    478   base::FilePath tmp_dir;
    479   base::FilePath temp_file;
    480   if (!PathService::Get(base::DIR_TEMP, &tmp_dir)) {
    481     NOTREACHED();
    482   } else if (!base::CreateTemporaryFileInDir(tmp_dir, &temp_file)) {
    483     LOG(ERROR) << "Failed to create temporary file for setup.exe.";
    484   } else {
    485     VLOG(1) << "Changing current directory to: " << tmp_dir.value();
    486     if (!file_util::SetCurrentDirectory(tmp_dir))
    487       PLOG(ERROR) << "Failed to change the current directory.";
    488 
    489     VLOG(1) << "Attempting to move setup to: " << temp_file.value();
    490     ret = base::Move(setup_exe, temp_file);
    491     PLOG_IF(ERROR, !ret) << "Failed to move setup to " << temp_file.value();
    492 
    493     // We cannot delete the file right away, but try to delete it some other
    494     // way. Either with the help of a different process or the system.
    495     if (ret && !base::DeleteFileAfterReboot(temp_file)) {
    496       static const uint32 kDeleteAfterMs = 10 * 1000;
    497       installer::DeleteFileFromTempProcess(temp_file, kDeleteAfterMs);
    498     }
    499   }
    500   return ret;
    501 }
    502 
    503 DeleteResult DeleteChromeDirectoriesIfEmpty(
    504     const base::FilePath& application_directory) {
    505   DeleteResult result(DeleteEmptyDir(application_directory));
    506   if (result == DELETE_SUCCEEDED) {
    507     // Now check and delete if the parent directories are empty
    508     // For example Google\Chrome or Chromium
    509     const base::FilePath product_directory(application_directory.DirName());
    510     if (!product_directory.empty()) {
    511         result = DeleteEmptyDir(product_directory);
    512         if (result == DELETE_SUCCEEDED) {
    513           const base::FilePath vendor_directory(product_directory.DirName());
    514           if (!vendor_directory.empty())
    515             result = DeleteEmptyDir(vendor_directory);
    516         }
    517     }
    518   }
    519   if (result == DELETE_NOT_EMPTY)
    520     result = DELETE_SUCCEEDED;
    521   return result;
    522 }
    523 
    524 DeleteResult DeleteAppHostFilesAndFolders(const InstallerState& installer_state,
    525                                           const Version& installed_version) {
    526   const base::FilePath& target_path = installer_state.target_path();
    527   if (target_path.empty()) {
    528     LOG(ERROR) << "DeleteAppHostFilesAndFolders: no installation destination "
    529                << "path.";
    530     return DELETE_FAILED;  // Nothing else we can do to uninstall, so we return.
    531   }
    532 
    533   DeleteInstallTempDir(target_path);
    534 
    535   DeleteResult result = DELETE_SUCCEEDED;
    536 
    537   base::FilePath app_host_exe(target_path.Append(installer::kChromeAppHostExe));
    538   if (!base::DeleteFile(app_host_exe, false)) {
    539     result = DELETE_FAILED;
    540     LOG(ERROR) << "Failed to delete path: " << app_host_exe.value();
    541   }
    542 
    543   return result;
    544 }
    545 
    546 DeleteResult DeleteChromeFilesAndFolders(const InstallerState& installer_state,
    547                                          const base::FilePath& setup_exe) {
    548   const base::FilePath& target_path = installer_state.target_path();
    549   if (target_path.empty()) {
    550     LOG(ERROR) << "DeleteChromeFilesAndFolders: no installation destination "
    551                << "path.";
    552     return DELETE_FAILED;  // Nothing else we can do to uninstall, so we return.
    553   }
    554 
    555   DeleteInstallTempDir(target_path);
    556 
    557   DeleteResult result = DELETE_SUCCEEDED;
    558 
    559   base::FilePath installer_directory;
    560   if (target_path.IsParent(setup_exe))
    561     installer_directory = setup_exe.DirName();
    562 
    563   // Enumerate all the files in target_path recursively (breadth-first).
    564   // We delete a file or folder unless it is a parent/child of the installer
    565   // directory. For parents of the installer directory, we will later recurse
    566   // and delete all the children (that are not also parents/children of the
    567   // installer directory).
    568   base::FileEnumerator file_enumerator(target_path, true,
    569       base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES);
    570   while (true) {
    571     base::FilePath to_delete(file_enumerator.Next());
    572     if (to_delete.empty())
    573       break;
    574     if (to_delete.BaseName().value() == installer::kChromeAppHostExe)
    575       continue;
    576     if (!installer_directory.empty() &&
    577         (to_delete == installer_directory ||
    578          installer_directory.IsParent(to_delete) ||
    579          to_delete.IsParent(installer_directory))) {
    580       continue;
    581     }
    582 
    583     VLOG(1) << "Deleting install path " << to_delete.value();
    584     if (!base::DeleteFile(to_delete, true)) {
    585       LOG(ERROR) << "Failed to delete path (1st try): " << to_delete.value();
    586       if (installer_state.FindProduct(BrowserDistribution::CHROME_FRAME)) {
    587         // We don't try killing Chrome processes for Chrome Frame builds since
    588         // that is unlikely to help. Instead, schedule files for deletion and
    589         // return a value that will trigger a reboot prompt.
    590         base::FileEnumerator::FileInfo find_info = file_enumerator.GetInfo();
    591         if (find_info.IsDirectory())
    592           ScheduleDirectoryForDeletion(to_delete);
    593         else
    594           ScheduleFileSystemEntityForDeletion(to_delete);
    595         result = DELETE_REQUIRES_REBOOT;
    596       } else {
    597         // Try closing any running Chrome processes and deleting files once
    598         // again.
    599         CloseAllChromeProcesses();
    600         if (!base::DeleteFile(to_delete, true)) {
    601           LOG(ERROR) << "Failed to delete path (2nd try): "
    602                      << to_delete.value();
    603           result = DELETE_FAILED;
    604           break;
    605         }
    606       }
    607     }
    608   }
    609 
    610   return result;
    611 }
    612 
    613 // This method checks if Chrome is currently running or if the user has
    614 // cancelled the uninstall operation by clicking Cancel on the confirmation
    615 // box that Chrome pops up.
    616 InstallStatus IsChromeActiveOrUserCancelled(
    617     const InstallerState& installer_state,
    618     const Product& product) {
    619   int32 exit_code = content::RESULT_CODE_NORMAL_EXIT;
    620   CommandLine options(CommandLine::NO_PROGRAM);
    621   options.AppendSwitch(installer::switches::kUninstall);
    622 
    623   // Here we want to save user from frustration (in case of Chrome crashes)
    624   // and continue with the uninstallation as long as chrome.exe process exit
    625   // code is NOT one of the following:
    626   // - UNINSTALL_CHROME_ALIVE - chrome.exe is currently running
    627   // - UNINSTALL_USER_CANCEL - User cancelled uninstallation
    628   // - HUNG - chrome.exe was killed by HuntForZombieProcesses() (until we can
    629   //          give this method some brains and not kill chrome.exe launched
    630   //          by us, we will not uninstall if we get this return code).
    631   VLOG(1) << "Launching Chrome to do uninstall tasks.";
    632   if (product.LaunchChromeAndWait(installer_state.target_path(), options,
    633                                   &exit_code)) {
    634     VLOG(1) << "chrome.exe launched for uninstall confirmation returned: "
    635             << exit_code;
    636     if ((exit_code == chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE) ||
    637         (exit_code == chrome::RESULT_CODE_UNINSTALL_USER_CANCEL) ||
    638         (exit_code == content::RESULT_CODE_HUNG))
    639       return installer::UNINSTALL_CANCELLED;
    640 
    641     if (exit_code == chrome::RESULT_CODE_UNINSTALL_DELETE_PROFILE)
    642       return installer::UNINSTALL_DELETE_PROFILE;
    643   } else {
    644     PLOG(ERROR) << "Failed to launch chrome.exe for uninstall confirmation.";
    645   }
    646 
    647   return installer::UNINSTALL_CONFIRMED;
    648 }
    649 
    650 bool ShouldDeleteProfile(const InstallerState& installer_state,
    651                          const CommandLine& cmd_line, InstallStatus status,
    652                          const Product& product) {
    653   bool should_delete = false;
    654 
    655   // Chrome Frame uninstallations always want to delete the profile (we have no
    656   // UI to prompt otherwise and the profile stores no useful data anyway)
    657   // unless they are managed by MSI. MSI uninstalls will explicitly include
    658   // the --delete-profile flag to distinguish them from MSI upgrades.
    659   if (product.is_chrome_frame() && !installer_state.is_msi()) {
    660     should_delete = true;
    661   } else {
    662     should_delete =
    663         status == installer::UNINSTALL_DELETE_PROFILE ||
    664         cmd_line.HasSwitch(installer::switches::kDeleteProfile);
    665   }
    666 
    667   return should_delete;
    668 }
    669 
    670 // Removes XP-era filetype registration making Chrome the default browser.
    671 // MSDN (see http://msdn.microsoft.com/library/windows/desktop/cc144148.aspx)
    672 // tells us not to do this, but certain applications break following
    673 // uninstallation if we don't.
    674 void RemoveFiletypeRegistration(const InstallerState& installer_state,
    675                                 HKEY root,
    676                                 const string16& browser_entry_suffix) {
    677   string16 classes_path(ShellUtil::kRegClasses);
    678   classes_path.push_back(base::FilePath::kSeparators[0]);
    679 
    680   BrowserDistribution* distribution = BrowserDistribution::GetDistribution();
    681   const string16 prog_id(
    682       distribution->GetBrowserProgIdPrefix() + browser_entry_suffix);
    683 
    684   // Delete each filetype association if it references this Chrome.  Take care
    685   // not to delete the association if it references a system-level install of
    686   // Chrome (only a risk if the suffix is empty).  Don't delete the whole key
    687   // since other apps may have stored data there.
    688   std::vector<const wchar_t*> cleared_assocs;
    689   if (installer_state.system_install() ||
    690       !browser_entry_suffix.empty() ||
    691       !base::win::RegKey(HKEY_LOCAL_MACHINE, (classes_path + prog_id).c_str(),
    692                          KEY_QUERY_VALUE).Valid()) {
    693     InstallUtil::ValueEquals prog_id_pred(prog_id);
    694     for (const wchar_t* const* filetype =
    695          &ShellUtil::kPotentialFileAssociations[0]; *filetype != NULL;
    696          ++filetype) {
    697       if (InstallUtil::DeleteRegistryValueIf(
    698               root, (classes_path + *filetype).c_str(), NULL,
    699               prog_id_pred) == InstallUtil::DELETED) {
    700         cleared_assocs.push_back(*filetype);
    701       }
    702     }
    703   }
    704 
    705   // For all filetype associations in HKLM that have just been removed, attempt
    706   // to restore some reasonable value.  We have no definitive way of knowing
    707   // what handlers are the most appropriate, so we use a fixed mapping based on
    708   // the default values for a fresh install of Windows.
    709   if (root == HKEY_LOCAL_MACHINE) {
    710     string16 assoc;
    711     base::win::RegKey key;
    712 
    713     for (size_t i = 0; i < cleared_assocs.size(); ++i) {
    714       const wchar_t* replacement_prog_id = NULL;
    715       assoc.assign(cleared_assocs[i]);
    716 
    717       // Inelegant, but simpler than a pure data-driven approach.
    718       if (assoc == L".htm" || assoc == L".html")
    719         replacement_prog_id = L"htmlfile";
    720       else if (assoc == L".xht" || assoc == L".xhtml")
    721         replacement_prog_id = L"xhtmlfile";
    722 
    723       if (!replacement_prog_id) {
    724         LOG(WARNING) << "No known replacement ProgID for " << assoc
    725                      << " files.";
    726       } else if (key.Open(HKEY_LOCAL_MACHINE,
    727                           (classes_path + replacement_prog_id).c_str(),
    728                           KEY_QUERY_VALUE) == ERROR_SUCCESS &&
    729                  (key.Open(HKEY_LOCAL_MACHINE, (classes_path + assoc).c_str(),
    730                            KEY_SET_VALUE) != ERROR_SUCCESS ||
    731                   key.WriteValue(NULL, replacement_prog_id) != ERROR_SUCCESS)) {
    732         // The replacement ProgID is registered on the computer but the attempt
    733         // to set it for the filetype failed.
    734         LOG(ERROR) << "Failed to restore system-level filetype association "
    735                    << assoc << " = " << replacement_prog_id;
    736       }
    737     }
    738   }
    739 }
    740 
    741 bool DeleteChromeRegistrationKeys(const InstallerState& installer_state,
    742                                   BrowserDistribution* dist,
    743                                   HKEY root,
    744                                   const string16& browser_entry_suffix,
    745                                   InstallStatus* exit_code) {
    746   DCHECK(exit_code);
    747   if (dist->GetDefaultBrowserControlPolicy() ==
    748       BrowserDistribution::DEFAULT_BROWSER_UNSUPPORTED) {
    749     // We should have never set those keys.
    750     return true;
    751   }
    752 
    753   base::FilePath chrome_exe(installer_state.target_path().Append(kChromeExe));
    754 
    755   // Delete Software\Classes\ChromeHTML.
    756   const string16 prog_id(
    757       dist->GetBrowserProgIdPrefix() + browser_entry_suffix);
    758   string16 reg_prog_id(ShellUtil::kRegClasses);
    759   reg_prog_id.push_back(base::FilePath::kSeparators[0]);
    760   reg_prog_id.append(prog_id);
    761   InstallUtil::DeleteRegistryKey(root, reg_prog_id);
    762 
    763   // Delete Software\Classes\Chrome.
    764   string16 reg_app_id(ShellUtil::kRegClasses);
    765   reg_app_id.push_back(base::FilePath::kSeparators[0]);
    766   // Append the requested suffix manually here (as ShellUtil::GetBrowserModelId
    767   // would otherwise try to figure out the currently installed suffix).
    768   reg_app_id.append(dist->GetBaseAppId() + browser_entry_suffix);
    769   InstallUtil::DeleteRegistryKey(root, reg_app_id);
    770 
    771   // Delete all Start Menu Internet registrations that refer to this Chrome.
    772   {
    773     using base::win::RegistryKeyIterator;
    774     InstallUtil::ProgramCompare open_command_pred(chrome_exe);
    775     string16 client_name;
    776     string16 client_key;
    777     string16 open_key;
    778     for (RegistryKeyIterator iter(root, ShellUtil::kRegStartMenuInternet);
    779          iter.Valid(); ++iter) {
    780       client_name.assign(iter.Name());
    781       client_key.assign(ShellUtil::kRegStartMenuInternet)
    782           .append(1, L'\\')
    783           .append(client_name);
    784       open_key.assign(client_key).append(ShellUtil::kRegShellOpen);
    785       if (InstallUtil::DeleteRegistryKeyIf(root, client_key, open_key, NULL,
    786               open_command_pred) != InstallUtil::NOT_FOUND) {
    787         // Delete the default value of SOFTWARE\Clients\StartMenuInternet if it
    788         // references this Chrome (i.e., if it was made the default browser).
    789         InstallUtil::DeleteRegistryValueIf(
    790             root, ShellUtil::kRegStartMenuInternet, NULL,
    791             InstallUtil::ValueEquals(client_name));
    792         // Also delete the value for the default user if we're operating in
    793         // HKLM.
    794         if (root == HKEY_LOCAL_MACHINE) {
    795           InstallUtil::DeleteRegistryValueIf(
    796               HKEY_USERS,
    797               string16(L".DEFAULT\\").append(
    798                   ShellUtil::kRegStartMenuInternet).c_str(),
    799               NULL, InstallUtil::ValueEquals(client_name));
    800         }
    801       }
    802     }
    803   }
    804 
    805   // Delete Software\RegisteredApplications\Chromium
    806   InstallUtil::DeleteRegistryValue(
    807       root, ShellUtil::kRegRegisteredApplications,
    808       dist->GetBaseAppName() + browser_entry_suffix);
    809 
    810   // Delete the App Paths and Applications keys that let Explorer find Chrome:
    811   // http://msdn.microsoft.com/en-us/library/windows/desktop/ee872121
    812   string16 app_key(ShellUtil::kRegClasses);
    813   app_key.push_back(base::FilePath::kSeparators[0]);
    814   app_key.append(L"Applications");
    815   app_key.push_back(base::FilePath::kSeparators[0]);
    816   app_key.append(installer::kChromeExe);
    817   InstallUtil::DeleteRegistryKey(root, app_key);
    818 
    819   string16 app_path_key(ShellUtil::kAppPathsRegistryKey);
    820   app_path_key.push_back(base::FilePath::kSeparators[0]);
    821   app_path_key.append(installer::kChromeExe);
    822   InstallUtil::DeleteRegistryKey(root, app_path_key);
    823 
    824   // Cleanup OpenWithList and OpenWithProgids:
    825   // http://msdn.microsoft.com/en-us/library/bb166549
    826   string16 file_assoc_key;
    827   string16 open_with_list_key;
    828   string16 open_with_progids_key;
    829   for (int i = 0; ShellUtil::kPotentialFileAssociations[i] != NULL; ++i) {
    830     file_assoc_key.assign(ShellUtil::kRegClasses);
    831     file_assoc_key.push_back(base::FilePath::kSeparators[0]);
    832     file_assoc_key.append(ShellUtil::kPotentialFileAssociations[i]);
    833     file_assoc_key.push_back(base::FilePath::kSeparators[0]);
    834 
    835     open_with_list_key.assign(file_assoc_key);
    836     open_with_list_key.append(L"OpenWithList");
    837     open_with_list_key.push_back(base::FilePath::kSeparators[0]);
    838     open_with_list_key.append(installer::kChromeExe);
    839     InstallUtil::DeleteRegistryKey(root, open_with_list_key);
    840 
    841     open_with_progids_key.assign(file_assoc_key);
    842     open_with_progids_key.append(ShellUtil::kRegOpenWithProgids);
    843     InstallUtil::DeleteRegistryValue(root, open_with_progids_key, prog_id);
    844   }
    845 
    846   // Cleanup in case Chrome had been made the default browser.
    847 
    848   // Delete the default value of SOFTWARE\Clients\StartMenuInternet if it
    849   // references this Chrome.  Do this explicitly here for the case where HKCU is
    850   // being processed; the iteration above will have no hits since registration
    851   // lives in HKLM.
    852   InstallUtil::DeleteRegistryValueIf(
    853       root, ShellUtil::kRegStartMenuInternet, NULL,
    854       InstallUtil::ValueEquals(dist->GetBaseAppName() + browser_entry_suffix));
    855 
    856   // Delete each protocol association if it references this Chrome.
    857   InstallUtil::ProgramCompare open_command_pred(chrome_exe);
    858   string16 parent_key(ShellUtil::kRegClasses);
    859   parent_key.push_back(base::FilePath::kSeparators[0]);
    860   const string16::size_type base_length = parent_key.size();
    861   string16 child_key;
    862   for (const wchar_t* const* proto =
    863            &ShellUtil::kPotentialProtocolAssociations[0];
    864        *proto != NULL;
    865        ++proto) {
    866     parent_key.resize(base_length);
    867     parent_key.append(*proto);
    868     child_key.assign(parent_key).append(ShellUtil::kRegShellOpen);
    869     InstallUtil::DeleteRegistryKeyIf(root, parent_key, child_key, NULL,
    870                                      open_command_pred);
    871   }
    872 
    873   RemoveFiletypeRegistration(installer_state, root, browser_entry_suffix);
    874 
    875   *exit_code = installer::UNINSTALL_SUCCESSFUL;
    876   return true;
    877 }
    878 
    879 void RemoveChromeLegacyRegistryKeys(BrowserDistribution* dist,
    880                                     const string16& chrome_exe) {
    881   // We used to register Chrome to handle crx files, but this turned out
    882   // to be not worth the hassle. Remove these old registry entries if
    883   // they exist. See: http://codereview.chromium.org/210007
    884 
    885 #if defined(GOOGLE_CHROME_BUILD)
    886 const wchar_t kChromeExtProgId[] = L"ChromeExt";
    887 #else
    888 const wchar_t kChromeExtProgId[] = L"ChromiumExt";
    889 #endif
    890 
    891   HKEY roots[] = { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER };
    892   for (size_t i = 0; i < arraysize(roots); ++i) {
    893     string16 suffix;
    894     if (roots[i] == HKEY_LOCAL_MACHINE)
    895       suffix = ShellUtil::GetCurrentInstallationSuffix(dist, chrome_exe);
    896 
    897     // Delete Software\Classes\ChromeExt,
    898     string16 ext_prog_id(ShellUtil::kRegClasses);
    899     ext_prog_id.push_back(base::FilePath::kSeparators[0]);
    900     ext_prog_id.append(kChromeExtProgId);
    901     ext_prog_id.append(suffix);
    902     InstallUtil::DeleteRegistryKey(roots[i], ext_prog_id);
    903 
    904     // Delete Software\Classes\.crx,
    905     string16 ext_association(ShellUtil::kRegClasses);
    906     ext_association.append(L"\\");
    907     ext_association.append(extensions::kExtensionFileExtension);
    908     InstallUtil::DeleteRegistryKey(roots[i], ext_association);
    909   }
    910 }
    911 
    912 // Builds and executes a work item list to remove DelegateExecute verb handler
    913 // work items for |product|.  This will be a noop for products whose
    914 // corresponding BrowserDistribution implementations do not publish a CLSID via
    915 // GetCommandExecuteImplClsid.
    916 bool ProcessDelegateExecuteWorkItems(const InstallerState& installer_state,
    917                                      const Product& product) {
    918   scoped_ptr<WorkItemList> item_list(WorkItem::CreateNoRollbackWorkItemList());
    919   AddDelegateExecuteWorkItems(installer_state, base::FilePath(), Version(),
    920                               product, item_list.get());
    921   return item_list->Do();
    922 }
    923 
    924 // Removes Active Setup entries from the registry. This cannot be done through
    925 // a work items list as usual because of different paths based on conditionals,
    926 // but otherwise respects the no rollback/best effort uninstall mentality.
    927 // This will only apply for system-level installs of Chrome/Chromium and will be
    928 // a no-op for all other types of installs.
    929 void UninstallActiveSetupEntries(const InstallerState& installer_state,
    930                                  const Product& product) {
    931   VLOG(1) << "Uninstalling registry entries for ActiveSetup.";
    932   BrowserDistribution* distribution = product.distribution();
    933 
    934   if (!product.is_chrome() || !installer_state.system_install()) {
    935     const char* install_level =
    936         installer_state.system_install() ? "system" : "user";
    937     VLOG(1) << "No Active Setup processing to do for " << install_level
    938             << "-level " << distribution->GetDisplayName();
    939     return;
    940   }
    941 
    942   const string16 active_setup_path(
    943       InstallUtil::GetActiveSetupPath(distribution));
    944   InstallUtil::DeleteRegistryKey(HKEY_LOCAL_MACHINE, active_setup_path);
    945 
    946   // Windows leaves keys behind in HKCU\\Software\\(Wow6432Node\\)?Microsoft\\
    947   //     Active Setup\\Installed Components\\{guid}
    948   // for every user that logged in since system-level Chrome was installed.
    949   // This is a problem because Windows compares the value of the Version subkey
    950   // in there with the value of the Version subkey in the matching HKLM entries
    951   // before running Chrome's Active Setup so if Chrome was to be reinstalled
    952   // with a lesser version (e.g. switching back to a more stable channel), the
    953   // affected users would not have Chrome's Active Setup called until Chrome
    954   // eventually updated passed that user's registered Version.
    955   //
    956   // It is however very hard to delete those values as the registry hives for
    957   // other users are not loaded by default under HKEY_USERS (unless a user is
    958   // logged on or has a process impersonating him).
    959   //
    960   // Following our best effort uninstall practices, try to delete the value in
    961   // all users hives. If a given user's hive is not loaded, try to load it to
    962   // proceed with the deletion (failure to do so is ignored).
    963 
    964   static const wchar_t kProfileList[] =
    965       L"Software\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\";
    966 
    967   // Windows automatically adds Wow6432Node when creating/deleting the HKLM key,
    968   // but doesn't seem to do so when manually deleting the user-level keys it
    969   // created.
    970   string16 alternate_active_setup_path(active_setup_path);
    971   alternate_active_setup_path.insert(arraysize("Software\\") - 1,
    972                                      L"Wow6432Node\\");
    973 
    974   // These two privileges are required by RegLoadKey() and RegUnloadKey() below.
    975   ScopedTokenPrivilege se_restore_name_privilege(SE_RESTORE_NAME);
    976   ScopedTokenPrivilege se_backup_name_privilege(SE_BACKUP_NAME);
    977   if (!se_restore_name_privilege.is_enabled() ||
    978       !se_backup_name_privilege.is_enabled()) {
    979     // This is not a critical failure as those privileges aren't required to
    980     // clean hives that are already loaded, but attempts to LoadRegKey() below
    981     // will fail.
    982     LOG(WARNING) << "Failed to enable privileges required to load registry "
    983                     "hives.";
    984   }
    985 
    986   for (base::win::RegistryKeyIterator it(HKEY_LOCAL_MACHINE, kProfileList);
    987        it.Valid(); ++it) {
    988     const wchar_t* profile_sid = it.Name();
    989 
    990     // First check if this user's registry hive needs to be loaded in
    991     // HKEY_USERS.
    992     base::win::RegKey user_reg_root_probe(
    993         HKEY_USERS, profile_sid, KEY_READ);
    994     bool loaded_hive = false;
    995     if (!user_reg_root_probe.Valid()) {
    996       VLOG(1) << "Attempting to load registry hive for " << profile_sid;
    997 
    998       string16 reg_profile_info_path(kProfileList);
    999       reg_profile_info_path.append(profile_sid);
   1000       base::win::RegKey reg_profile_info_key(
   1001           HKEY_LOCAL_MACHINE, reg_profile_info_path.c_str(), KEY_READ);
   1002 
   1003       string16 profile_path;
   1004       LONG result = reg_profile_info_key.ReadValue(L"ProfileImagePath",
   1005                                                    &profile_path);
   1006       if (result != ERROR_SUCCESS) {
   1007         LOG(ERROR) << "Error reading ProfileImagePath: " << result;
   1008         continue;
   1009       }
   1010       base::FilePath registry_hive_file(profile_path);
   1011       registry_hive_file = registry_hive_file.AppendASCII("NTUSER.DAT");
   1012 
   1013       result = RegLoadKey(HKEY_USERS, profile_sid,
   1014                           registry_hive_file.value().c_str());
   1015       if (result != ERROR_SUCCESS) {
   1016         LOG(ERROR) << "Error loading registry hive: " << result;
   1017         continue;
   1018       }
   1019 
   1020       VLOG(1) << "Loaded registry hive for " << profile_sid;
   1021       loaded_hive = true;
   1022     }
   1023 
   1024     base::win::RegKey user_reg_root(
   1025         HKEY_USERS, profile_sid, KEY_ALL_ACCESS);
   1026 
   1027     LONG result = user_reg_root.DeleteKey(active_setup_path.c_str());
   1028     if (result != ERROR_SUCCESS) {
   1029       result = user_reg_root.DeleteKey(alternate_active_setup_path.c_str());
   1030       if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) {
   1031         LOG(ERROR) << "Failed to delete key at " << active_setup_path
   1032                    << " and at " << alternate_active_setup_path
   1033                    << ", result: " << result;
   1034       }
   1035     }
   1036 
   1037     if (loaded_hive) {
   1038       user_reg_root.Close();
   1039       if (RegUnLoadKey(HKEY_USERS, profile_sid) == ERROR_SUCCESS)
   1040         VLOG(1) << "Unloaded registry hive for " << profile_sid;
   1041       else
   1042         LOG(ERROR) << "Error unloading registry hive for " << profile_sid;
   1043     }
   1044   }
   1045 }
   1046 
   1047 InstallStatus UninstallProduct(const InstallationState& original_state,
   1048                                const InstallerState& installer_state,
   1049                                const base::FilePath& setup_path,
   1050                                const Product& product,
   1051                                bool remove_all,
   1052                                bool force_uninstall,
   1053                                const CommandLine& cmd_line) {
   1054   InstallStatus status = installer::UNINSTALL_CONFIRMED;
   1055   BrowserDistribution* browser_dist = product.distribution();
   1056   const string16 chrome_exe(
   1057       installer_state.target_path().Append(installer::kChromeExe).value());
   1058 
   1059   bool is_chrome = product.is_chrome();
   1060 
   1061   VLOG(1) << "UninstallProduct: " << browser_dist->GetDisplayName();
   1062 
   1063   if (force_uninstall) {
   1064     // Since --force-uninstall command line option is used, we are going to
   1065     // do silent uninstall. Try to close all running Chrome instances.
   1066     // NOTE: We don't do this for Chrome Frame.
   1067     if (is_chrome)
   1068       CloseAllChromeProcesses();
   1069   } else if (is_chrome) {
   1070     // no --force-uninstall so lets show some UI dialog boxes.
   1071     status = IsChromeActiveOrUserCancelled(installer_state, product);
   1072     if (status != installer::UNINSTALL_CONFIRMED &&
   1073         status != installer::UNINSTALL_DELETE_PROFILE)
   1074       return status;
   1075 
   1076     const string16 suffix(ShellUtil::GetCurrentInstallationSuffix(browser_dist,
   1077                                                                   chrome_exe));
   1078 
   1079     // Check if we need admin rights to cleanup HKLM (the conditions for
   1080     // requiring a cleanup are the same as the conditions to do the actual
   1081     // cleanup where DeleteChromeRegistrationKeys() is invoked for
   1082     // HKEY_LOCAL_MACHINE below). If we do, try to launch another uninstaller
   1083     // (silent) in elevated mode to do HKLM cleanup.
   1084     // And continue uninstalling in the current process also to do HKCU cleanup.
   1085     if (remove_all &&
   1086         ShellUtil::QuickIsChromeRegisteredInHKLM(
   1087             browser_dist, chrome_exe, suffix) &&
   1088         !::IsUserAnAdmin() &&
   1089         base::win::GetVersion() >= base::win::VERSION_VISTA &&
   1090         !cmd_line.HasSwitch(installer::switches::kRunAsAdmin)) {
   1091       CommandLine new_cmd(CommandLine::NO_PROGRAM);
   1092       new_cmd.AppendArguments(cmd_line, true);
   1093       // Append --run-as-admin flag to let the new instance of setup.exe know
   1094       // that we already tried to launch ourselves as admin.
   1095       new_cmd.AppendSwitch(installer::switches::kRunAsAdmin);
   1096       // Append --remove-chrome-registration to remove registry keys only.
   1097       new_cmd.AppendSwitch(installer::switches::kRemoveChromeRegistration);
   1098       if (!suffix.empty()) {
   1099         new_cmd.AppendSwitchNative(
   1100             installer::switches::kRegisterChromeBrowserSuffix, suffix);
   1101       }
   1102       DWORD exit_code = installer::UNKNOWN_STATUS;
   1103       InstallUtil::ExecuteExeAsAdmin(new_cmd, &exit_code);
   1104     }
   1105   }
   1106 
   1107   if (is_chrome) {
   1108     // Chrome is not in use so lets uninstall Chrome by deleting various files
   1109     // and registry entries. Here we will just make best effort and keep going
   1110     // in case of errors.
   1111     ClearRlzProductState();
   1112     // Delete the key that delegate_execute might make.
   1113     if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
   1114       InstallUtil::DeleteRegistryKey(HKEY_CURRENT_USER,
   1115                                      chrome::kMetroRegistryPath);
   1116     }
   1117 
   1118     auto_launch_util::DisableAllAutoStartFeatures(
   1119         ASCIIToUTF16(chrome::kInitialProfile));
   1120 
   1121     // If user-level chrome is self-destructing as a result of encountering a
   1122     // system-level chrome, retarget owned non-default shortcuts (app shortcuts,
   1123     // profile shortcuts, etc.) to the system-level chrome.
   1124     if (cmd_line.HasSwitch(installer::switches::kSelfDestruct) &&
   1125         !installer_state.system_install()) {
   1126       const base::FilePath system_chrome_path(
   1127           GetChromeInstallPath(true, browser_dist).
   1128               Append(installer::kChromeExe));
   1129       VLOG(1) << "Retargeting user-generated Chrome shortcuts.";
   1130       if (base::PathExists(system_chrome_path)) {
   1131         RetargetUserShortcutsWithArgs(installer_state, product,
   1132                                       base::FilePath(chrome_exe),
   1133                                       system_chrome_path);
   1134       } else {
   1135         LOG(ERROR) << "Retarget failed: system-level Chrome not found.";
   1136       }
   1137     }
   1138 
   1139     DeleteShortcuts(installer_state, product, base::FilePath(chrome_exe));
   1140   }
   1141 
   1142   // Delete the registry keys (Uninstall key and Version key).
   1143   HKEY reg_root = installer_state.root_key();
   1144 
   1145   // Note that we must retrieve the distribution-specific data before deleting
   1146   // product.GetVersionKey().
   1147   string16 distribution_data(browser_dist->GetDistributionData(reg_root));
   1148 
   1149   // Remove Control Panel uninstall link.
   1150   if (product.ShouldCreateUninstallEntry()) {
   1151     InstallUtil::DeleteRegistryKey(reg_root,
   1152                                    browser_dist->GetUninstallRegPath());
   1153   }
   1154 
   1155   // Remove Omaha product key.
   1156   InstallUtil::DeleteRegistryKey(reg_root, browser_dist->GetVersionKey());
   1157 
   1158   // Also try to delete the MSI value in the ClientState key (it might not be
   1159   // there). This is due to a Google Update behaviour where an uninstall and a
   1160   // rapid reinstall might result in stale values from the old ClientState key
   1161   // being picked up on reinstall.
   1162   product.SetMsiMarker(installer_state.system_install(), false);
   1163 
   1164   InstallStatus ret = installer::UNKNOWN_STATUS;
   1165 
   1166   if (is_chrome) {
   1167     const string16 suffix(ShellUtil::GetCurrentInstallationSuffix(browser_dist,
   1168                                                                   chrome_exe));
   1169 
   1170     // Remove all Chrome registration keys.
   1171     // Registration data is put in HKCU for both system level and user level
   1172     // installs.
   1173     DeleteChromeRegistrationKeys(installer_state, browser_dist,
   1174                                  HKEY_CURRENT_USER, suffix, &ret);
   1175 
   1176     // If the user's Chrome is registered with a suffix: it is possible that old
   1177     // unsuffixed registrations were left in HKCU (e.g. if this install was
   1178     // previously installed with no suffix in HKCU (old suffix rules if the user
   1179     // is not an admin (or declined UAC at first run)) and later had to be
   1180     // suffixed when fully registered in HKLM (e.g. when later making Chrome
   1181     // default through the UI)).
   1182     // Remove remaining HKCU entries with no suffix if any.
   1183     if (!suffix.empty()) {
   1184       DeleteChromeRegistrationKeys(installer_state, browser_dist,
   1185                                    HKEY_CURRENT_USER, string16(), &ret);
   1186 
   1187       // For similar reasons it is possible in very few installs (from
   1188       // 21.0.1180.0 and fixed shortly after) to be installed with the new-style
   1189       // suffix, but have some old-style suffix registrations left behind.
   1190       string16 old_style_suffix;
   1191       if (ShellUtil::GetOldUserSpecificRegistrySuffix(&old_style_suffix) &&
   1192           suffix != old_style_suffix) {
   1193         DeleteChromeRegistrationKeys(installer_state, browser_dist,
   1194                                      HKEY_CURRENT_USER, old_style_suffix, &ret);
   1195       }
   1196     }
   1197 
   1198     // Chrome is registered in HKLM for all system-level installs and for
   1199     // user-level installs for which Chrome has been made the default browser.
   1200     // Always remove the HKLM registration for system-level installs.  For
   1201     // user-level installs, only remove it if both: 1) this uninstall isn't a
   1202     // self destruct following the installation of a system-level Chrome
   1203     // (because the system-level Chrome owns the HKLM registration now), and 2)
   1204     // this user has made Chrome their default browser (i.e. has shell
   1205     // integration entries registered with |suffix| (note: |suffix| will be the
   1206     // empty string if required as it is obtained by
   1207     // GetCurrentInstallationSuffix() above)).
   1208     // TODO(gab): This can still leave parts of a suffixed install behind. To be
   1209     // able to remove them we would need to be able to remove only suffixed
   1210     // entries (as it is now some of the registry entries (e.g. App Paths) are
   1211     // unsuffixed; thus removing suffixed installs is prohibited in HKLM if
   1212     // !|remove_all| for now).
   1213     if (installer_state.system_install() ||
   1214         (remove_all &&
   1215          ShellUtil::QuickIsChromeRegisteredInHKLM(
   1216              browser_dist, chrome_exe, suffix))) {
   1217       DeleteChromeRegistrationKeys(installer_state, browser_dist,
   1218                                    HKEY_LOCAL_MACHINE, suffix, &ret);
   1219     }
   1220 
   1221     ProcessDelegateExecuteWorkItems(installer_state, product);
   1222 
   1223     ProcessOnOsUpgradeWorkItems(installer_state, product);
   1224 
   1225     UninstallActiveSetupEntries(installer_state, product);
   1226 
   1227     // Notify the shell that associations have changed since Chrome was likely
   1228     // unregistered.
   1229     SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
   1230 
   1231     // TODO(huangs): Implement actual migration code and remove the hack below.
   1232     // Remove the "shadow" App Launcher registry keys.
   1233     if (installer_state.is_multi_install()) {
   1234       // If we're not uninstalling the legacy App Launcher, and if it was
   1235       // not installed in the first place, then delete the "shadow" keys.
   1236       chrome_launcher_support::InstallationState level_to_check =
   1237           installer_state.system_install() ?
   1238               chrome_launcher_support::INSTALLED_AT_SYSTEM_LEVEL :
   1239               chrome_launcher_support::INSTALLED_AT_USER_LEVEL;
   1240       bool has_legacy_app_launcher = level_to_check ==
   1241           chrome_launcher_support::GetAppLauncherInstallationState();
   1242       if (!has_legacy_app_launcher) {
   1243         BrowserDistribution* shadow_app_launcher_dist =
   1244             BrowserDistribution::GetSpecificDistribution(
   1245                 BrowserDistribution::CHROME_APP_HOST);
   1246         InstallUtil::DeleteRegistryKey(reg_root,
   1247             shadow_app_launcher_dist->GetVersionKey());
   1248       }
   1249     }
   1250   }
   1251 
   1252   if (installer_state.is_multi_install())
   1253     ProcessGoogleUpdateItems(original_state, installer_state, product);
   1254 
   1255   // Get the state of the installed product (if any)
   1256   const ProductState* product_state =
   1257       original_state.GetProductState(installer_state.system_install(),
   1258                                      browser_dist->GetType());
   1259 
   1260   // Delete shared registry keys as well (these require admin rights) if
   1261   // remove_all option is specified.
   1262   if (remove_all) {
   1263     if (!InstallUtil::IsChromeSxSProcess() && is_chrome) {
   1264       // Delete media player registry key that exists only in HKLM.
   1265       // We don't delete this key in SxS uninstall or Chrome Frame uninstall
   1266       // as we never set the key for those products.
   1267       string16 reg_path(installer::kMediaPlayerRegPath);
   1268       reg_path.push_back(base::FilePath::kSeparators[0]);
   1269       reg_path.append(installer::kChromeExe);
   1270       InstallUtil::DeleteRegistryKey(HKEY_LOCAL_MACHINE, reg_path);
   1271     }
   1272 
   1273     // Unregister any dll servers that we may have registered for this
   1274     // product.
   1275     if (product_state != NULL) {
   1276       std::vector<base::FilePath> com_dll_list;
   1277       product.AddComDllList(&com_dll_list);
   1278       base::FilePath dll_folder = installer_state.target_path().AppendASCII(
   1279           product_state->version().GetString());
   1280 
   1281       scoped_ptr<WorkItemList> unreg_work_item_list(
   1282           WorkItem::CreateWorkItemList());
   1283 
   1284       AddRegisterComDllWorkItems(dll_folder,
   1285                                  com_dll_list,
   1286                                  installer_state.system_install(),
   1287                                  false,  // Unregister
   1288                                  true,   // May fail
   1289                                  unreg_work_item_list.get());
   1290       unreg_work_item_list->Do();
   1291     }
   1292 
   1293     if (product.is_chrome_frame())
   1294       ProcessIELowRightsPolicyWorkItems(installer_state);
   1295   }
   1296 
   1297   // Close any Chrome Frame helper processes that may be running.
   1298   if (product.is_chrome_frame()) {
   1299     VLOG(1) << "Closing the Chrome Frame helper process";
   1300     CloseChromeFrameHelperProcess();
   1301   }
   1302 
   1303   if (product_state == NULL)
   1304     return installer::UNINSTALL_SUCCESSFUL;
   1305 
   1306   // Finally delete all the files from Chrome folder after moving setup.exe
   1307   // and the user's Local State to a temp location.
   1308   bool delete_profile = ShouldDeleteProfile(installer_state, cmd_line, status,
   1309                                             product);
   1310   ret = installer::UNINSTALL_SUCCESSFUL;
   1311 
   1312   // When deleting files, we must make sure that we're either a "single"
   1313   // (aka non-multi) installation or we are the Chrome Binaries.
   1314 
   1315   std::vector<base::FilePath> local_state_folders;
   1316   GetLocalStateFolders(product, &local_state_folders);
   1317   base::FilePath backup_state_file(BackupLocalStateFile(local_state_folders));
   1318 
   1319   if (product.is_chrome_app_host()) {
   1320     DeleteAppHostFilesAndFolders(installer_state, product_state->version());
   1321   } else if (!installer_state.is_multi_install() ||
   1322              product.is_chrome_binaries()) {
   1323     base::FilePath setup_exe(base::MakeAbsoluteFilePath(cmd_line.GetProgram()));
   1324     DeleteResult delete_result = DeleteChromeFilesAndFolders(
   1325         installer_state, setup_exe);
   1326     if (delete_result == DELETE_FAILED) {
   1327       ret = installer::UNINSTALL_FAILED;
   1328     } else if (delete_result == DELETE_REQUIRES_REBOOT) {
   1329       ret = installer::UNINSTALL_REQUIRES_REBOOT;
   1330     }
   1331   }
   1332 
   1333   if (delete_profile)
   1334     DeleteLocalState(local_state_folders, product.is_chrome_frame());
   1335 
   1336   if (!force_uninstall) {
   1337     VLOG(1) << "Uninstallation complete. Launching post-uninstall operations.";
   1338     browser_dist->DoPostUninstallOperations(product_state->version(),
   1339         backup_state_file, distribution_data);
   1340   }
   1341 
   1342   // Try and delete the preserved local state once the post-install
   1343   // operations are complete.
   1344   if (!backup_state_file.empty())
   1345     base::DeleteFile(backup_state_file, false);
   1346 
   1347   return ret;
   1348 }
   1349 
   1350 void CleanUpInstallationDirectoryAfterUninstall(
   1351     const InstallationState& original_state,
   1352     const InstallerState& installer_state,
   1353     const CommandLine& cmd_line,
   1354     InstallStatus* uninstall_status) {
   1355   if (*uninstall_status != UNINSTALL_SUCCESSFUL &&
   1356       *uninstall_status != UNINSTALL_REQUIRES_REBOOT) {
   1357     return;
   1358   }
   1359   const base::FilePath target_path(installer_state.target_path());
   1360   if (target_path.empty()) {
   1361     LOG(ERROR) << "No installation destination path.";
   1362     *uninstall_status = UNINSTALL_FAILED;
   1363     return;
   1364   }
   1365   base::FilePath setup_exe(base::MakeAbsoluteFilePath(cmd_line.GetProgram()));
   1366   if (!target_path.IsParent(setup_exe)) {
   1367     VLOG(1) << "setup.exe is not in target path. Skipping installer cleanup.";
   1368     return;
   1369   }
   1370   base::FilePath install_directory(setup_exe.DirName());
   1371 
   1372   bool remove_setup = true;
   1373   bool remove_archive = true;
   1374   CheckShouldRemoveSetupAndArchive(original_state, installer_state,
   1375                                    &remove_setup, &remove_archive);
   1376   if (!remove_archive)
   1377     return;
   1378 
   1379   if (remove_setup) {
   1380     // In order to be able to remove the folder in which we're running, we
   1381     // need to move setup.exe out of the install folder.
   1382     // TODO(tommi): What if the temp folder is on a different volume?
   1383     MoveSetupOutOfInstallFolder(installer_state, setup_exe);
   1384   }
   1385 
   1386   // Remove files from "...\<product>\Application\<version>\Installer"
   1387   if (!RemoveInstallerFiles(install_directory, remove_setup)) {
   1388     *uninstall_status = UNINSTALL_FAILED;
   1389     return;
   1390   }
   1391 
   1392   if (!remove_setup)
   1393     return;
   1394 
   1395   // Try to remove the empty directory hierarchy.
   1396 
   1397   // Delete "...\<product>\Application\<version>\Installer"
   1398   if (DeleteEmptyDir(install_directory) != DELETE_SUCCEEDED) {
   1399     *uninstall_status = UNINSTALL_FAILED;
   1400     return;
   1401   }
   1402 
   1403   // Delete "...\<product>\Application\<version>"
   1404   DeleteResult delete_result = DeleteEmptyDir(install_directory.DirName());
   1405   if (delete_result == DELETE_FAILED ||
   1406       (delete_result == DELETE_NOT_EMPTY &&
   1407        *uninstall_status != UNINSTALL_REQUIRES_REBOOT)) {
   1408     *uninstall_status = UNINSTALL_FAILED;
   1409     return;
   1410   }
   1411 
   1412   if (*uninstall_status == UNINSTALL_REQUIRES_REBOOT) {
   1413     // Delete the Application directory at reboot if empty.
   1414     ScheduleFileSystemEntityForDeletion(target_path);
   1415 
   1416     // If we need a reboot to continue, schedule the parent directories for
   1417     // deletion unconditionally. If they are not empty, the session manager
   1418     // will not delete them on reboot.
   1419     ScheduleParentAndGrandparentForDeletion(target_path);
   1420   } else if (DeleteChromeDirectoriesIfEmpty(target_path) == DELETE_FAILED) {
   1421     *uninstall_status = UNINSTALL_FAILED;
   1422   }
   1423 }
   1424 
   1425 }  // namespace installer
   1426