Backed out 5 changesets (bug 1732435) for causing bustages at nsXREDirProvider.cpp. CLOSED TREE
authorButkovits Atila <abutkovits@mozilla.com>
Wed, 08 Dec 2021 20:10:57 +0200
changeset 601421 740fad344989d083fad880469a0555ac68010d34
parent 601420 db0701b309ad98a20a6d7ac95e38e0ac94e83116
child 601422 dba7b7c19b2f20632f19a49e0d436ebfdcc63681
push id39047
push userabutkovits@mozilla.com
push dateWed, 08 Dec 2021 21:43:06 +0000
treeherdermozilla-central@740fad344989 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
bugs1732435
milestone97.0a1
backs outdb0701b309ad98a20a6d7ac95e38e0ac94e83116
22a583f191e26714955112023f158e2b887b16c6
b37ed631436f29ffaa4360c3afca4de324fe50d7
8a734e8a313b9017e06421efeb3a7c34396dcfbc
9cb78a88ffdee4eeb97b1677329baf7b9a0b1a60
first release with
nightly linux32
740fad344989 / 97.0a1 / 20211208214306 / files
nightly linux64
740fad344989 / 97.0a1 / 20211208214306 / files
nightly mac
740fad344989 / 97.0a1 / 20211208214306 / files
nightly win32
740fad344989 / 97.0a1 / 20211208214306 / files
nightly win64
740fad344989 / 97.0a1 / 20211208214306 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Backed out 5 changesets (bug 1732435) for causing bustages at nsXREDirProvider.cpp. CLOSED TREE Backed out changeset db0701b309ad (bug 1732435) Backed out changeset 22a583f191e2 (bug 1732435) Backed out changeset b37ed631436f (bug 1732435) Backed out changeset 8a734e8a313b (bug 1732435) Backed out changeset 9cb78a88ffde (bug 1732435)
browser/installer/windows/nsis/installer.nsi
browser/installer/windows/nsis/uninstaller.nsi
toolkit/components/maintenanceservice/workmonitor.cpp
toolkit/mozapps/installer/windows/nsis/common.nsh
toolkit/mozapps/update/BackgroundUpdate.jsm
toolkit/mozapps/update/UpdateService.jsm
toolkit/mozapps/update/UpdateServiceStub.jsm
toolkit/mozapps/update/common/commonupdatedir.cpp
toolkit/mozapps/update/common/commonupdatedir.h
toolkit/mozapps/update/nsIUpdateService.idl
toolkit/mozapps/update/tests/TestAUSHelper.cpp
toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js
toolkit/mozapps/update/tests/unit_aus_update/updateDirectoryMigrate.js
toolkit/xre/MultiInstanceLock.cpp
toolkit/xre/nsUpdateDriver.cpp
toolkit/xre/nsXREDirProvider.cpp
--- a/browser/installer/windows/nsis/installer.nsi
+++ b/browser/installer/windows/nsis/installer.nsi
@@ -405,16 +405,22 @@ Section "-Application" APP_IDX
     ${EndIf}
   ${EndIf}
 
   ; Default for creating Desktop shortcut (1 = create, 0 = don't create)
   ${If} $AddDesktopSC == ""
     StrCpy $AddDesktopSC "1"
   ${EndIf}
 
+  ${CreateUpdateDir} "Mozilla"
+  ${If} ${Errors}
+    Pop $0
+    ${LogMsg} "** ERROR Failed to create update directory: $0"
+  ${EndIf}
+
   ${LogHeader} "Adding Registry Entries"
   SetShellVarContext current  ; Set SHCTX to HKCU
   ${RegCleanMain} "Software\Mozilla"
   ${RegCleanUninstall}
   ${UpdateProtocolHandlers}
 
   ClearErrors
   WriteRegStr HKLM "Software\Mozilla" "${BrandShortName}InstallerTest" "Write Test"
--- a/browser/installer/windows/nsis/uninstaller.nsi
+++ b/browser/installer/windows/nsis/uninstaller.nsi
@@ -322,27 +322,26 @@ Function un.LaunchRefreshHelpPage
   Pop $1
   Pop $0
 FunctionEnd
 
 Function un.OpenRefreshHelpURL
   ExecShell "open" "${URLProfileRefreshHelp}"
 FunctionEnd
 
-; Returns the common directory (typically
-; "C:\ProgramData\Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38") on the stack.
+; Returns the common directory (typically "C:\ProgramData\Mozilla") on the stack.
 Function un.GetCommonDirectory
   Push $0   ; Save $0
 
   ; This gets C:\ProgramData or the equivalent.
   ${GetCommonAppDataFolder} $0
 
   ; Add our subdirectory, this is hardcoded as grandparent of the update directory in
   ; several other places.
-  StrCpy $0 "$0\Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38"
+  StrCpy $0 "$0\Mozilla"
 
   Exch $0   ; Restore original $0 and put our $0 on the stack.
 FunctionEnd
 
 Function un.SendUninstallPing
   ${If} $AppUserModelID == ""
     Return
   ${EndIf}
--- a/toolkit/components/maintenanceservice/workmonitor.cpp
+++ b/toolkit/components/maintenanceservice/workmonitor.cpp
@@ -796,16 +796,35 @@ BOOL ExecuteServiceCommand(int argc, LPW
       result = ProcessSoftwareUpdateCommand(argc - 3, argv + 3);
       DeleteSecureUpdater(secureUpdaterPath);
     }
 
     // We might not reach here if the service install succeeded
     // because the service self updates itself and the service
     // installer will stop the service.
     LOG(("Service command %ls complete.", argv[2]));
+  } else if (!lstrcmpi(argv[2], L"fix-update-directory-perms")) {
+    bool gotInstallDir = true;
+    mozilla::UniquePtr<wchar_t[]> updateDir;
+    if (argc <= 3) {
+      LOG_WARN(("Didn't get an install dir for fix-update-directory-perms"));
+      gotInstallDir = false;
+    }
+    HRESULT permResult =
+        GetCommonUpdateDirectory(gotInstallDir ? argv[3] : nullptr,
+                                 SetPermissionsOf::AllFilesAndDirs, updateDir);
+    if (FAILED(permResult)) {
+      LOG_WARN(
+          ("Unable to set the permissions on the update directory "
+           "('%S'): %d",
+           updateDir.get(), permResult));
+      result = FALSE;
+    } else {
+      result = TRUE;
+    }
   } else {
     LOG_WARN(("Service command not recognized: %ls.", argv[2]));
     // result is already set to FALSE
   }
 
   LOG(("service command %ls complete with result: %ls.", argv[1],
        (result ? L"Success" : L"Failure")));
   return result;
--- a/toolkit/mozapps/installer/windows/nsis/common.nsh
+++ b/toolkit/mozapps/installer/windows/nsis/common.nsh
@@ -3562,21 +3562,21 @@
           ; Concatenate the local AppData path ($R9) to the relative profile path and
           ; the relative path to $INSTDIR from $PROGRAMFILES
           StrCpy $R2 "$R9\$R7$R2"
           ${${_MOZFUNC_UN}GetLongPath} "$R2" $R2
 
           ${If} $R2 != ""
             ; Backup the old update directory logs and delete the directory
             ${If} ${FileExists} "$R2\updates\last-update.log"
-              Rename "$R2\updates\last-update.log" "$TEMP\moz-update-old-1-last-update.log"
+              Rename "$R2\updates\last-update.log" "$TEMP\moz-update-oldest-last-update.log"
             ${EndIf}
 
             ${If} ${FileExists} "$R2\updates\backup-update.log"
-              Rename "$R2\updates\backup-update.log" "$TEMP\moz-update-old-1-backup-update.log"
+              Rename "$R2\updates\backup-update.log" "$TEMP\moz-update-oldest-backup-update.log"
             ${EndIf}
 
             ${If} ${FileExists} "$R2\updates"
                 RmDir /r "$R2"
             ${EndIf}
           ${EndIf}
         ${EndIf}
 
@@ -3587,61 +3587,35 @@
         ${EndIf}
 
         ; If the taskbar ID hash exists then delete the new update directory
         ; Backup its logs before deleting it.
         ${If} $R1 != ""
           StrCpy $R0 "$R9\$R8\$R1"
 
           ${If} ${FileExists} "$R0\updates\last-update.log"
-            Rename "$R0\updates\last-update.log" "$TEMP\moz-update-old-2-last-update.log"
+            Rename "$R0\updates\last-update.log" "$TEMP\moz-update-older-last-update.log"
           ${EndIf}
 
           ${If} ${FileExists} "$R0\updates\backup-update.log"
-            Rename "$R0\updates\backup-update.log" "$TEMP\moz-update-old-2-backup-update.log"
+            Rename "$R0\updates\backup-update.log" "$TEMP\moz-update-older-backup-update.log"
           ${EndIf}
 
           ; Remove the old updates directory, located in the user's Windows profile directory
           ${If} ${FileExists} "$R0\updates"
             RmDir /r "$R0"
           ${EndIf}
 
+          ; Get the new updates directory so we can remove that too
+          ; The new update directory is in the Program Data directory
+          ; (currently C:\ProgramData).
           ${GetCommonAppDataFolder} $R0
           StrCpy $R0 "$R0\$R8\$R1"
 
           ${If} ${FileExists} "$R0\updates\last-update.log"
-            Rename "$R0\updates\last-update.log" "$TEMP\moz-update-old-3-last-update.log"
-          ${EndIf}
-
-          ${If} ${FileExists} "$R0\updates\backup-update.log"
-            Rename "$R0\updates\backup-update.log" "$TEMP\moz-update-old-3-backup-update.log"
-          ${EndIf}
-
-          ; Even though this is an old update directory, completely clear it out
-          ; on uninstall only, not on installation. If this is an installation,
-          ; it may be a paveover install and there may be un-migrated settings
-          ; in the update directory that we don't want to lose.
-          ; On install though, we should still remove pending updates and update
-          ; metadata since migrating that data could potentially confuse Firefox
-          ; into thinking that it failed to apply an update.
-          !if "${_MOZFUNC_UN}" == "un."
-            ${If} ${FileExists} "$R0"
-              RmDir /r "$R0"
-            ${EndIf}
-          !else
-            ${If} ${FileExists} "$R0\updates"
-              RmDir /r "$R0\updates"
-            ${EndIf}
-            Delete "$R0\active-update.xml"
-          !endif
-
-          ${GetCommonAppDataFolder} $R0
-          StrCpy $R0 "$R0\Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38\updates\$R1"
-
-          ${If} ${FileExists} "$R0\updates\last-update.log"
             Rename "$R0\updates\last-update.log" "$TEMP\moz-update-newest-last-update.log"
           ${EndIf}
 
           ${If} ${FileExists} "$R0\updates\backup-update.log"
             Rename "$R0\updates\backup-update.log" "$TEMP\moz-update-newest-backup-update.log"
           ${EndIf}
 
           ; The update directory is shared across all users of this
@@ -3728,16 +3702,94 @@
 
     !undef _MOZFUNC_UN
     !define _MOZFUNC_UN
     !verbose pop
   !endif
 !macroend
 
 /**
+ * Create the update directory and sets the permissions correctly
+ *
+ * @param   ROOT_DIR_NAME
+ *          The name of the update directory to be created in the common
+ *          application directory. For example, if ROOT_DIR_NAME is "Mozilla",
+ *          the created directory will be "C:\ProgramData\Mozilla".
+ *
+ * $R0 = Used for checking errors
+ * $R1 = The common application directory path
+ * $R9 = An error message to be returned on the stack
+ */
+!macro CreateUpdateDir ROOT_DIR_NAME
+  Push $R9
+  Push $R0
+  Push $R1
+
+  ; The update directory is in the Program Data directory
+  ; (currently C:\ProgramData).
+  ${GetCommonAppDataFolder} $R1
+  StrCpy $R1 "$R1\${ROOT_DIR_NAME}"
+
+  ClearErrors
+  ${IfNot} ${FileExists} "$R1"
+    CreateDirectory "$R1"
+    ${If} ${Errors}
+      StrCpy $R9 "Unable to create directory: $R1"
+      GoTo end
+    ${EndIf}
+  ${EndIf}
+
+  ; Grant Full Access to the Builtin User group
+  AccessControl::SetOnFile "$R1" "(BU)" "FullAccess"
+  Pop $R0
+  ${If} $R0 == error
+    Pop $R9  ; Get AccessControl's Error Message
+    SetErrors
+    GoTo end
+  ${EndIf}
+
+  ; Grant Full Access to the Builtin Administrator group
+  AccessControl::SetOnFile "$R1" "(BA)" "FullAccess"
+  Pop $R0
+  ${If} $R0 == error
+    Pop $R9  ; Get AccessControl's Error Message
+    SetErrors
+    GoTo end
+  ${EndIf}
+
+  ; Grant Full Access to the SYSTEM user
+  AccessControl::SetOnFile "$R1" "(SY)" "FullAccess"
+  Pop $R0
+  ${If} $R0 == error
+    Pop $R9  ; Get AccessControl's Error Message
+    SetErrors
+    GoTo end
+  ${EndIf}
+
+  ; Remove inherited permissions
+  AccessControl::DisableFileInheritance "$R1"
+  Pop $R0
+  ${If} $R0 == error
+    Pop $R9  ; Get AccessControl's Error Message
+    SetErrors
+    GoTo end
+  ${EndIf}
+
+end:
+  Pop $R1
+  Pop $R0
+  ${If} ${Errors}
+    Exch $R9
+  ${Else}
+    Pop $R9
+  ${EndIf}
+!macroend
+!define CreateUpdateDir "!insertmacro CreateUpdateDir"
+
+/**
  * Deletes shortcuts and Start Menu directories under Programs as specified by
  * the shortcuts log ini file and on Windows 7 unpins TaskBar and Start Menu
  * shortcuts. The shortcuts will not be deleted if the shortcut target isn't for
  * this install location which is determined by the shortcut having a target of
  * $INSTDIR\${FileMainEXE}. The context (All Users or Current User) of the
  * $DESKTOP and $SMPROGRAMS constants depends on the
  * SetShellVarContext setting and must be set by the caller of this macro. There
  * is no All Users context for $QUICKLAUNCH but this will not cause a problem
--- a/toolkit/mozapps/update/BackgroundUpdate.jsm
+++ b/toolkit/mozapps/update/BackgroundUpdate.jsm
@@ -50,17 +50,17 @@ XPCOMUtils.defineLazyServiceGetter(
 
 Cu.importGlobalProperties(["Glean"]);
 
 // We may want to change the definition of the task over time. When we do this,
 // we need to remove and re-register the task. We will make sure this happens
 // by storing the installed version number of the task to a pref and comparing
 // that version number to the current version. If they aren't equal, we know
 // that we have to re-register the task.
-const TASK_DEF_CURRENT_VERSION = 3;
+const TASK_DEF_CURRENT_VERSION = 2;
 const TASK_INSTALLED_VERSION_PREF =
   "app.update.background.lastInstalledTaskVersion";
 
 var BackgroundUpdate = {
   _initialized: false,
 
   get taskId() {
     let taskId = "backgroundupdate";
@@ -503,51 +503,16 @@ var BackgroundUpdate = {
             `${taskInstalledVersion} to ${TASK_DEF_CURRENT_VERSION}. ` +
             `Removing task so the new version can be registered`
         );
         try {
           await TaskScheduler.deleteTask(this.taskId);
         } catch (e) {
           log.error(`${SLUG}: Error removing old task: ${e}`);
         }
-        try {
-          // When the update directory was moved, we migrated the old contents
-          // to the new location. This can potentially happen in a background
-          // task. However, we also need to re-register the background task
-          // with the task scheduler in order to update the MOZ_LOG_FILE value
-          // to point to the new location. If the task runs before Firefox has
-          // a chance to re-register the task, the log file may be recreated in
-          // the old location. In practice, this would be unusual, because
-          // MOZ_LOG_FILE will not create the parent directories necessary to
-          // put a log file in the specified location. But just to be safe,
-          // we'll do some cleanup when we re-register the task to make sure
-          // that no log file is hanging around in the old location.
-          let oldUpdateDir = FileUtils.getDir("OldUpdRootD", [], false);
-          let oldLog = oldUpdateDir.clone();
-          oldLog.append("backgroundupdate.moz_log");
-
-          if (oldLog.exists()) {
-            oldLog.remove(false);
-            // We may have created some directories in order to put this log
-            // file in this location. Clean them up if they are empty.
-            // (If we pass false for the recurse parameter, directories with
-            // contents will not be removed)
-            //
-            // Potentially removes "C:\ProgramData\Mozilla\updates\<hash>"
-            oldUpdateDir.remove(false);
-            // Potentially removes "C:\ProgramData\Mozilla\updates"
-            oldUpdateDir.parent.remove(false);
-            // Potentially removes "C:\ProgramData\Mozilla"
-            oldUpdateDir.parent.parent.remove(false);
-          }
-        } catch (ex) {
-          log.warn(
-            `${SLUG}: Ignoring error encountered attempting to remove stale log file: ${ex}`
-          );
-        }
       }
 
       log.info(
         `${SLUG}: background update was previously disabled for reasons: '${previousReasons}'`
       );
 
       await this._registerBackgroundUpdateTask(this.taskId);
       log.info(
--- a/toolkit/mozapps/update/UpdateService.jsm
+++ b/toolkit/mozapps/update/UpdateService.jsm
@@ -296,17 +296,24 @@ const ONLY_INSTANCE_CHECK_DEFAULT_POLL_I
 // Wait this long after detecting that another instance is running (having been
 // polling that entire time) before giving up and applying the update anyway.
 const ONLY_INSTANCE_CHECK_DEFAULT_TIMEOUT_MS = 6 * 60 * 60 * 1000; // 6 hours
 
 // The other instance check timeout can be overridden via a pref, but we limit
 // that value to this so that the pref can't effectively disable the feature.
 const ONLY_INSTANCE_CHECK_MAX_TIMEOUT_MS = 2 * 24 * 60 * 60 * 1000; // 2 days
 
+// Object to keep track of the current phase of the update and whether there
+// has been a write failure for the phase so only one telemetry ping is made
+// for the phase.
+var gUpdateFileWriteInfo = { phase: null, failure: false };
 var gUpdateMutexHandle = null;
+// The permissions of the update directory should be fixed no more than once per
+// session
+var gUpdateDirPermissionFixAttempted = false;
 // This is the file stream used for the log file.
 var gLogfileOutputStream;
 // This value will be set to true if it appears that BITS is being used by
 // another user to download updates. We don't really want two users using BITS
 // at once. Computers with many users (ex: a school computer), should not end
 // up with dozens of BITS jobs.
 var gBITSInUseByAnotherUser = false;
 // Tracks whether an update is currently being staged. This is slightly more
@@ -733,16 +740,20 @@ function getCanApplyUpdates() {
     LOG("getCanApplyUpdates - testing write access " + updateTestFile.path);
     testWriteAccess(updateTestFile, false);
   } catch (e) {
     LOG(
       "getCanApplyUpdates - unable to apply updates without write " +
         "access to the update directory. Exception: " +
         e
     );
+    // Attempt to fix the update directory permissions. If successful the next
+    // time this function is called the write access check to the update
+    // directory will succeed.
+    fixUpdateDirectoryPermissions();
     return false;
   }
 
   if (AppConstants.platform == "macosx") {
     LOG(
       "getCanApplyUpdates - bypass the write since elevation can be used " +
         "on Mac OS X"
     );
@@ -1155,17 +1166,20 @@ function readBinaryTransparencyResult(di
  *          The patch directory where the update.status file should be
  *          written.
  * @param   state
  *          The state value to write.
  */
 function writeStatusFile(dir, state) {
   let statusFile = dir.clone();
   statusFile.append(FILE_UPDATE_STATUS);
-  writeStringToFile(statusFile, state);
+  let success = writeStringToFile(statusFile, state);
+  if (!success) {
+    handleCriticalWriteFailure(statusFile.path);
+  }
 }
 
 /**
  * Writes the update's application version to a file in the patch directory. If
  * the update doesn't provide application version information via the
  * appVersion attribute the string "null" will be written to the file.
  * This value is compared during startup (in nsUpdateDriver.cpp) to determine if
  * the update should be applied. Note that this won't provide protection from
@@ -1176,17 +1190,20 @@ function writeStatusFile(dir, state) {
  *          written.
  * @param   version
  *          The version value to write. Will be the string "null" when the
  *          update doesn't provide the appVersion attribute in the update xml.
  */
 function writeVersionFile(dir, version) {
   let versionFile = dir.clone();
   versionFile.append(FILE_UPDATE_VERSION);
-  writeStringToFile(versionFile, version);
+  let success = writeStringToFile(versionFile, version);
+  if (!success) {
+    handleCriticalWriteFailure(versionFile.path);
+  }
 }
 
 /**
  * Determines if the service should be used to attempt an update
  * or not.
  *
  * @return  true if the service should be used for updates.
  */
@@ -1790,16 +1807,132 @@ function pingStateAndStatusCodes(aUpdate
       suffix,
       parseInt(binaryTransparencyResult)
     );
   }
   AUSTLMY.pingStateCode(suffix, stateCode);
 }
 
 /**
+ * Asynchronously fixes the update directory permissions. This is currently only
+ * available on Windows.
+ *
+ * @return true if the permission-fixing process was started, and false if the
+ *         permission-fixing process was not started or the platform is not
+ *         supported.
+ */
+function fixUpdateDirectoryPermissions() {
+  if (AppConstants.platform != "win") {
+    LOG(
+      "There is currently no implementation for fixing update directory " +
+        "permissions on this platform"
+    );
+    return false;
+  }
+
+  if (!gUpdateDirPermissionFixAttempted) {
+    // Never try to fix permissions more than one time during a session.
+    gUpdateDirPermissionFixAttempted = true;
+
+    LOG("Attempting to fix update directory permissions");
+    try {
+      Cc["@mozilla.org/updates/update-processor;1"]
+        .createInstance(Ci.nsIUpdateProcessor)
+        .fixUpdateDirectoryPerms(shouldUseService());
+    } catch (e) {
+      LOG(
+        "Attempt to fix update directory permissions failed. Exception: " + e
+      );
+      return false;
+    }
+    return true;
+  }
+  return false;
+}
+
+/**
+ * This function should be called whenever we fail to write to a file required
+ * for update to function. This function will, if possible, attempt to fix the
+ * file permissions. If the file permissions cannot be fixed, the user will be
+ * prompted to reinstall.
+ *
+ * All functionality happens asynchronously.
+ *
+ * Returns false if the permission-fixing process cannot be started. Since this
+ * is asynchronous, a true return value does not mean that the permissions were
+ * actually fixed.
+ *
+ * @param path A string representing the path that could not be written. This
+ *             value will only be used for logging purposes.
+ */
+function handleCriticalWriteFailure(path) {
+  LOG(
+    "handleCriticalWriteFailure - Unable to write to critical update file: " +
+      path
+  );
+  if (!gUpdateFileWriteInfo.failure) {
+    gUpdateFileWriteInfo.failure = true;
+    let patchType = AUSTLMY.PATCH_UNKNOWN;
+    let update = UM.readyUpdate || UM.downloadingUpdate;
+    if (update) {
+      let patch = update.selectedPatch;
+      if (patch.type == "complete") {
+        patchType = AUSTLMY.PATCH_COMPLETE;
+      } else if (patch.type == "partial") {
+        patchType = AUSTLMY.PATCH_PARTIAL;
+      }
+    }
+
+    if (gUpdateFileWriteInfo.phase == "check") {
+      let updateServiceInstance = UpdateServiceFactory.createInstance();
+      let pingSuffix = updateServiceInstance._pingSuffix;
+      if (!pingSuffix) {
+        // If pingSuffix isn't defined then this this is a manual check which
+        // isn't recorded at this time.
+        AUSTLMY.pingCheckCode(pingSuffix, AUSTLMY.CHK_ERR_WRITE_FAILURE);
+      }
+    } else if (gUpdateFileWriteInfo.phase == "download") {
+      AUSTLMY.pingDownloadCode(patchType, AUSTLMY.DWNLD_ERR_WRITE_FAILURE);
+    } else if (gUpdateFileWriteInfo.phase == "stage") {
+      let suffix = patchType + "_" + AUSTLMY.STAGE;
+      AUSTLMY.pingStateCode(suffix, AUSTLMY.STATE_WRITE_FAILURE);
+    } else if (gUpdateFileWriteInfo.phase == "startup") {
+      let suffix = patchType + "_" + AUSTLMY.STARTUP;
+      AUSTLMY.pingStateCode(suffix, AUSTLMY.STATE_WRITE_FAILURE);
+    } else {
+      // Temporary failure code to see if there are failures without an update
+      // phase.
+      AUSTLMY.pingDownloadCode(
+        patchType,
+        AUSTLMY.DWNLD_UNKNOWN_PHASE_ERR_WRITE_FAILURE
+      );
+    }
+  }
+
+  return fixUpdateDirectoryPermissions();
+}
+
+/**
+ * This is a convenience function for calling the above function depending on a
+ * boolean success value.
+ *
+ * @param wroteSuccessfully A boolean representing whether or not the write was
+ *                          successful. When this is true, this function does
+ *                          nothing.
+ * @param path A string representing the path to the file that the operation
+ *             attempted to write to. This value is only used for logging
+ *             purposes.
+ */
+function handleCriticalWriteResult(wroteSuccessfully, path) {
+  if (!wroteSuccessfully) {
+    handleCriticalWriteFailure(path);
+  }
+}
+
+/**
  * This returns true if the passed update is the same version or older than the
  * version and build ID values passed. Otherwise it returns false.
  */
 function updateIsAtLeastAsOldAs(update, version, buildID) {
   if (!update || !update.appVersion || !update.buildID) {
     return false;
   }
   let versionComparison = Services.vc.compare(update.appVersion, version);
@@ -2603,16 +2736,17 @@ UpdateService.prototype = {
       // This function is a point when we can potentially enter the update
       // system, even with update disabled. Make sure that we do not continue
       // because update code can have side effects that are visible to the user
       // and give the impression that updates are enabled. For example, if we
       // can't write to the update directory, we might complain to the user that
       // update is broken and they should reinstall.
       return;
     }
+    gUpdateFileWriteInfo = { phase: "startup", failure: false };
     if (!this.canCheckForUpdates) {
       LOG(
         "UpdateService:_postUpdateProcessing - unable to check for " +
           "updates... returning early"
       );
       return;
     }
     let status = readStatusFile(getReadyUpdateDir());
@@ -4100,16 +4234,17 @@ UpdateManager.prototype = {
     try {
       fileStream.init(file, mode, FileUtils.PERMS_FILE, 0);
     } catch (e) {
       LOG(
         "UpdateManager:_loadXMLFileIntoArray - error initializing file " +
           "stream. Exception: " +
           e
       );
+      fixUpdateDirectoryPermissions();
       return updates;
     }
     try {
       var parser = new DOMParser();
       var doc = parser.parseFromStream(
         fileStream,
         "UTF-8",
         fileStream.available(),
@@ -4335,25 +4470,32 @@ UpdateManager.prototype = {
     if (this._downloadingUpdate) {
       updates.push(this._downloadingUpdate);
     }
 
     // The active update stored in the active-update.xml file will change during
     // the lifetime of an active update and the file should always be updated
     // when saveUpdates is called.
     let promises = [];
-    promises[0] = this._writeUpdatesToXMLFile(updates, FILE_ACTIVE_UPDATE_XML);
+    promises[0] = this._writeUpdatesToXMLFile(
+      updates,
+      FILE_ACTIVE_UPDATE_XML
+    ).then(wroteSuccessfully =>
+      handleCriticalWriteResult(wroteSuccessfully, FILE_ACTIVE_UPDATE_XML)
+    );
     // The update history stored in the updates.xml file should only need to be
     // updated when an active update has been added to it in which case
     // |_updatesDirty| will be true.
     if (this._updatesDirty) {
       this._updatesDirty = false;
       promises[1] = this._writeUpdatesToXMLFile(
         this._getUpdates(),
         FILE_UPDATES_XML
+      ).then(wroteSuccessfully =>
+        handleCriticalWriteResult(wroteSuccessfully, FILE_UPDATES_XML)
       );
     }
     return Promise.all(promises);
   },
 
   /**
    * See nsIUpdateService.idl
    */
@@ -4578,16 +4720,17 @@ Checker.prototype = {
     return url;
   },
 
   /**
    * See nsIUpdateService.idl
    */
   checkForUpdates: function UC_checkForUpdates(listener, force) {
     LOG("Checker: checkForUpdates, force: " + force);
+    gUpdateFileWriteInfo = { phase: "check", failure: false };
     if (!listener) {
       throw Components.Exception("", Cr.NS_ERROR_NULL_POINTER);
     }
 
     let UpdateServiceInstance = UpdateServiceFactory.createInstance();
     // |force| can override |canCheckForUpdates| since |force| indicates a
     // manual update check. But nothing should override enterprise policies.
     if (UpdateServiceInstance.disabledByPolicy) {
@@ -5230,16 +5373,17 @@ Downloader.prototype = {
 
   /**
    * Download and stage the given update.
    * @param   update
    *          A nsIUpdate object to download a patch for. Cannot be null.
    */
   downloadUpdate: function Downloader_downloadUpdate(update) {
     LOG("UpdateService:_downloadUpdate");
+    gUpdateFileWriteInfo = { phase: "download", failure: false };
     if (!update) {
       AUSTLMY.pingDownloadCode(undefined, AUSTLMY.DWNLD_ERR_NO_UPDATE);
       throw Components.Exception("", Cr.NS_ERROR_NULL_POINTER);
     }
 
     var updateDir = getDownloadingUpdateDir();
 
     this._update = update;
@@ -5731,16 +5875,17 @@ Downloader.prototype = {
     // Prevent the preference from setting a value greater than 10000.
     retryTimeout = Math.min(retryTimeout, 10000);
     var maxFail = Services.prefs.getIntPref(
       PREF_APP_UPDATE_SOCKET_MAXERRORS,
       DEFAULT_SOCKET_MAX_ERRORS
     );
     // Prevent the preference from setting a value greater than 20.
     maxFail = Math.min(maxFail, 20);
+    let permissionFixingInProgress = false;
     LOG(
       "Downloader:onStopRequest - status: " +
         status +
         ", " +
         "current fail: " +
         this.updateService._consecutiveSocketErrors +
         ", " +
         "max fail: " +
@@ -5796,16 +5941,22 @@ Downloader.prototype = {
           const mfCode = "move_failed";
           let message = getStatusTextFromCode(mfCode, mfCode);
           this._update.statusText = message;
 
           nonDownloadFailure = true;
           deleteActiveUpdate = true;
 
           cleanUpDownloadingUpdateDir();
+
+          let failedWrite = readyDir.clone();
+          failedWrite.append(FILE_UPDATE_MAR);
+          permissionFixingInProgress = handleCriticalWriteFailure(
+            failedWrite.path
+          );
         }
       } else {
         LOG("Downloader:onStopRequest - download verification failed");
         state = STATE_DOWNLOAD_FAILED;
         status = Cr.NS_ERROR_CORRUPTED_CONTENT;
 
         // Yes, this code is a string.
         const vfCode = "verification_failed";
@@ -5857,16 +6008,21 @@ Downloader.prototype = {
       shouldRetrySoon = true;
       deleteActiveUpdate = false;
     } else if (status != Cr.NS_BINDING_ABORTED && status != Cr.NS_ERROR_ABORT) {
       if (
         status == Cr.NS_ERROR_FILE_ACCESS_DENIED ||
         status == Cr.NS_ERROR_FILE_READ_ONLY
       ) {
         LOG("Downloader:onStopRequest - permission error");
+        // This will either fix the permissions, or asynchronously show the
+        // reinstall prompt if it cannot fix them.
+        let patchFile = getDownloadingUpdateDir();
+        patchFile.append(FILE_UPDATE_MAR);
+        permissionFixingInProgress = handleCriticalWriteFailure(patchFile.path);
         nonDownloadFailure = true;
       } else {
         LOG("Downloader:onStopRequest - non-verification failure");
       }
 
       let dwnldCode = AUSTLMY.DWNLD_ERR_BINDING_ABORTED;
       if (status == Cr.NS_ERROR_ABORT) {
         dwnldCode = AUSTLMY.DWNLD_ERR_ABORT;
@@ -5993,17 +6149,17 @@ Downloader.prototype = {
           if (!success) {
             cleanupDownloadingUpdate();
           } else {
             allFailed = false;
           }
         }
       }
 
-      if (allFailed) {
+      if (allFailed && !permissionFixingInProgress) {
         let downloadAttempts = Services.prefs.getIntPref(
           PREF_APP_UPDATE_DOWNLOAD_ATTEMPTS,
           0
         );
         downloadAttempts++;
         Services.prefs.setIntPref(
           PREF_APP_UPDATE_DOWNLOAD_ATTEMPTS,
           downloadAttempts
@@ -6070,16 +6226,17 @@ Downloader.prototype = {
       state == STATE_PENDING_SERVICE ||
       state == STATE_PENDING_ELEVATE
     ) {
       if (getCanStageUpdates()) {
         LOG(
           "Downloader:onStopRequest - attempting to stage update: " +
             this._update.name
         );
+        gUpdateFileWriteInfo = { phase: "stage", failure: false };
         // Stage the update
         try {
           Cc["@mozilla.org/updates/update-processor;1"]
             .createInstance(Ci.nsIUpdateProcessor)
             .processUpdate();
           gStagingInProgress = true;
         } catch (e) {
           // Fail gracefully in case the application does not support the update
--- a/toolkit/mozapps/update/UpdateServiceStub.jsm
+++ b/toolkit/mozapps/update/UpdateServiceStub.jsm
@@ -11,27 +11,31 @@ const { FileUtils } = ChromeUtils.import
 );
 const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
 const { AppConstants } = ChromeUtils.import(
   "resource://gre/modules/AppConstants.jsm"
 );
 
 const DIR_UPDATES = "updates";
 const FILE_UPDATE_STATUS = "update.status";
+const FILE_ACTIVE_UPDATE_XML = "active-update.xml";
+const FILE_LAST_UPDATE_LOG = "last-update.log";
+const FILE_UPDATES_XML = "updates.xml";
+const FILE_UPDATE_LOG = "update.log";
 const FILE_UPDATE_MESSAGES = "update_messages.log";
 const FILE_BACKUP_MESSAGES = "update_messages_old.log";
 
 const KEY_UPDROOT = "UpdRootD";
 const KEY_OLD_UPDROOT = "OldUpdRootD";
 const KEY_PROFILE_DIR = "ProfD";
 
 // The pref prefix below should have the hash of the install path appended to
 // ensure that this is a per-installation pref (i.e. to ensure that migration
 // happens for every install rather than once per profile)
-const PREF_PREFIX_UPDATE_DIR_MIGRATED = "app.update.migrated.updateDir3.";
+const PREF_PREFIX_UPDATE_DIR_MIGRATED = "app.update.migrated.updateDir2.";
 const PREF_APP_UPDATE_ALTUPDATEDIRPATH = "app.update.altUpdateDirPath";
 const PREF_APP_UPDATE_LOG = "app.update.log";
 const PREF_APP_UPDATE_FILE_LOGGING = "app.update.log.file";
 
 XPCOMUtils.defineLazyGetter(this, "gLogEnabled", function aus_gLogEnabled() {
   return Services.prefs.getBoolPref(PREF_APP_UPDATE_LOG, false);
 });
 
@@ -79,29 +83,18 @@ function UpdateServiceStub() {
   updateDir = null; // We don't need updateDir anymore, plus now its nsIFile
   // contains the status file's path
 
   // We may need to migrate update data
   if (
     AppConstants.platform == "win" &&
     !Services.prefs.getBoolPref(prefUpdateDirMigrated, false)
   ) {
+    migrateUpdateDirectory();
     Services.prefs.setBoolPref(prefUpdateDirMigrated, true);
-    try {
-      migrateUpdateDirectory();
-    } catch (ex) {
-      // For the most part, migrateUpdateDirectory() catches its own errors.
-      // But there are technically things that could happen that might not be
-      // caught, like nsIFile.parent or nsIFile.append could unexpectedly fail.
-      // So we will catch any errors here, just in case.
-      LOG(
-        `UpdateServiceStub:UpdateServiceStub Failed to migrate update ` +
-          `directory. Exception: ${ex}`
-      );
-    }
   }
 
   // Prevent file logging from persisting for more than a session by disabling
   // it on startup.
   if (Services.prefs.getBoolPref(PREF_APP_UPDATE_FILE_LOGGING, false)) {
     deactivateUpdateLogFile();
   }
 
@@ -144,281 +137,130 @@ function deactivateUpdateLogFile() {
   }
 }
 
 /**
  * This function should be called when there are files in the old update
  * directory that may need to be migrated to the new update directory.
  */
 function migrateUpdateDirectory() {
-  LOG("UpdateServiceStub:migrateUpdateDirectory Performing migration");
-
   let sourceRootDir = FileUtils.getDir(KEY_OLD_UPDROOT, [], false);
   let destRootDir = FileUtils.getDir(KEY_UPDROOT, [], false);
-  let hash = destRootDir.leafName;
 
   if (!sourceRootDir.exists()) {
-    // Nothing to migrate.
-    return;
-  }
-
-  // List of files to migrate. Each is specified as a list of path components.
-  const toMigrate = [
-    ["updates.xml"],
-    ["active-update.xml"],
-    ["update-config.json"],
-    ["updates", "last-update.log"],
-    ["updates", "backup-update.log"],
-    ["updates", "downloading", FILE_UPDATE_STATUS],
-    ["updates", "downloading", "update.mar"],
-    ["updates", "0", FILE_UPDATE_STATUS],
-    ["updates", "0", "update.mar"],
-    ["updates", "0", "update.version"],
-    ["updates", "0", "update.log"],
-    ["backgroundupdate", "datareporting", "glean", "db", "data.safe.bin"],
-  ];
-
-  // Before we copy anything, double check that a different profile hasn't
-  // already performed migration. If we don't have the necessary permissions to
-  // remove the pre-migration files, we don't want to copy any old files and
-  // potentially make the current update state inconsistent.
-  for (let pathComponents of toMigrate) {
-    // Assemble the destination nsIFile.
-    let destFile = destRootDir.clone();
-    for (let pathComponent of pathComponents) {
-      destFile.append(pathComponent);
-    }
-
-    if (destFile.exists()) {
-      LOG(
-        `UpdateServiceStub:migrateUpdateDirectory Aborting migration because ` +
-          `"${destFile.path}" already exists.`
-      );
-      return;
-    }
-  }
-
-  // Before we migrate everything in toMigrate, there are a few things that
-  // need special handling.
-  let sourceRootParent = sourceRootDir.parent.parent;
-  let destRootParent = destRootDir.parent.parent;
-
-  let profileCountFile = sourceRootParent.clone();
-  profileCountFile.append(`profile_count_${hash}.json`);
-  migrateFile(profileCountFile, destRootParent);
-
-  const updatePingPrefix = `uninstall_ping_${hash}_`;
-  const updatePingSuffix = ".json";
-  try {
-    for (let file of sourceRootParent.directoryEntries) {
-      if (
-        file.leafName.startsWith(updatePingPrefix) &&
-        file.leafName.endsWith(updatePingSuffix)
-      ) {
-        migrateFile(file, destRootParent);
-      }
-    }
-  } catch (ex) {
-    // migrateFile should catch its own errors, but it is possible that
-    // sourceRootParent.directoryEntries could throw.
     LOG(
-      `UpdateServiceStub:migrateUpdateDirectory Failed to migrate uninstall ` +
-        `ping. Exception: ${ex}`
-    );
-  }
-
-  // Migrate "backgroundupdate.moz_log" and child process logs like
-  // "backgroundupdate.child-1.moz_log".
-  const backgroundLogPrefix = `backgroundupdate`;
-  const backgroundLogSuffix = ".moz_log";
-  try {
-    for (let file of sourceRootDir.directoryEntries) {
-      if (
-        file.leafName.startsWith(backgroundLogPrefix) &&
-        file.leafName.endsWith(backgroundLogSuffix)
-      ) {
-        migrateFile(file, destRootDir);
-      }
-    }
-  } catch (ex) {
-    LOG(
-      `UpdateServiceStub:migrateUpdateDirectory Failed to migrate background ` +
-        `log file. Exception: ${ex}`
-    );
-  }
-
-  const pendingPingRelDir =
-    "backgroundupdate\\datareporting\\glean\\pending_pings";
-  let pendingPingSourceDir = sourceRootDir.clone();
-  pendingPingSourceDir.appendRelativePath(pendingPingRelDir);
-  let pendingPingDestDir = destRootDir.clone();
-  pendingPingDestDir.appendRelativePath(pendingPingRelDir);
-  // Pending ping filenames are UUIDs.
-  const pendingPingFilenameRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
-  if (pendingPingSourceDir.exists()) {
-    try {
-      for (let file of pendingPingSourceDir.directoryEntries) {
-        if (pendingPingFilenameRegex.test(file.leafName)) {
-          migrateFile(file, pendingPingDestDir);
-        }
-      }
-    } catch (ex) {
-      // migrateFile should catch its own errors, but it is possible that
-      // pendingPingSourceDir.directoryEntries could throw.
-      LOG(
-        `UpdateServiceStub:migrateUpdateDirectory Failed to migrate ` +
-          `pending pings. Exception: ${ex}`
-      );
-    }
-  }
-
-  // Migrate everything in toMigrate.
-  for (let pathComponents of toMigrate) {
-    let filename = pathComponents.pop();
-
-    // Assemble the source and destination nsIFile's.
-    let sourceFile = sourceRootDir.clone();
-    let destDir = destRootDir.clone();
-    for (let pathComponent of pathComponents) {
-      sourceFile.append(pathComponent);
-      destDir.append(pathComponent);
-    }
-    sourceFile.append(filename);
-
-    migrateFile(sourceFile, destDir);
-  }
-
-  // There is no reason to keep this file, and it often hangs around and could
-  // interfere with cleanup.
-  let updateLockFile = sourceRootParent.clone();
-  updateLockFile.append(`UpdateLock-${hash}`);
-  try {
-    updateLockFile.remove(false);
-  } catch (ex) {}
-
-  // We want to recursively remove empty directories out of the sourceRootDir.
-  // And if that was the only remaining update directory in sourceRootParent,
-  // we want to remove that too. But we don't want to recurse into other update
-  // directories in sourceRootParent.
-  //
-  // Potentially removes "C:\ProgramData\Mozilla\updates\<hash>" and
-  // subdirectories.
-  cleanupDir(sourceRootDir, true);
-  // Potentially removes "C:\ProgramData\Mozilla\updates"
-  cleanupDir(sourceRootDir.parent, false);
-  // Potentially removes "C:\ProgramData\Mozilla"
-  cleanupDir(sourceRootParent, false);
-}
-
-/**
- * Attempts to move the source file to the destination directory. If the file
- * cannot be moved, we attempt to copy it and remove the original. All errors
- * are logged, but no exceptions are thrown. Both arguments must be of type
- * nsIFile and are expected to be regular files.
- *
- * Non-existent files are silently ignored.
- *
- * The reason that we are migrating is to deal with problematic inherited
- * permissions. But, luckily, neither nsIFile.moveTo nor nsIFile.copyTo preserve
- * inherited permissions.
- */
-function migrateFile(sourceFile, destDir) {
-  if (!sourceFile.exists()) {
-    return;
-  }
-
-  if (sourceFile.isDirectory()) {
-    LOG(
-      `UpdateServiceStub:migrateFile Aborting attempt to migrate ` +
-        `"${sourceFile.path}" because it is a directory.`
+      "UpdateServiceStub:_migrateUpdateDirectory - Abort: No migration " +
+        "necessary. Nothing to migrate."
     );
     return;
   }
 
-  // Create destination directory.
-  try {
-    // Pass an arbitrary value for permissions. Windows doesn't use octal
-    // permissions, so that value doesn't really do anything.
-    destDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0);
-  } catch (ex) {
-    if (ex.result != Cr.NS_ERROR_FILE_ALREADY_EXISTS) {
+  if (destRootDir.exists()) {
+    // Migration must have already been done by another user
+    LOG(
+      "UpdateServiceStub:_migrateUpdateDirectory - migrated and unmigrated " +
+        "update directories found. Deleting the unmigrated directory: " +
+        sourceRootDir.path
+    );
+    try {
+      sourceRootDir.remove(true);
+    } catch (e) {
       LOG(
-        `UpdateServiceStub:migrateFile Unable to create destination ` +
-          `directory "${destDir.path}": ${ex}`
+        "UpdateServiceStub:_migrateUpdateDirectory - Deletion of " +
+          "unmigrated directory failed. Exception: " +
+          e
       );
     }
+    return;
   }
 
+  let sourceUpdateDir = sourceRootDir.clone();
+  sourceUpdateDir.append(DIR_UPDATES);
+  let destUpdateDir = destRootDir.clone();
+  destUpdateDir.append(DIR_UPDATES);
+
+  let sourcePatchDir = sourceUpdateDir.clone();
+  sourcePatchDir.append("0");
+  let destPatchDir = destUpdateDir.clone();
+  destPatchDir.append("0");
+
+  let sourceStatusFile = sourcePatchDir.clone();
+  sourceStatusFile.append(FILE_UPDATE_STATUS);
+  let destStatusFile = destPatchDir.clone();
+  destStatusFile.append(FILE_UPDATE_STATUS);
+
+  let sourceActiveXML = sourceRootDir.clone();
+  sourceActiveXML.append(FILE_ACTIVE_UPDATE_XML);
   try {
-    sourceFile.moveTo(destDir, null);
-    return;
-  } catch (ex) {}
+    sourceActiveXML.moveTo(destRootDir, sourceActiveXML.leafName);
+  } catch (e) {
+    LOG(
+      "UpdateServiceStub:_migrateUpdateDirectory - Unable to move active " +
+        "update XML file. Exception: " +
+        e
+    );
+  }
 
+  let sourceUpdateXML = sourceRootDir.clone();
+  sourceUpdateXML.append(FILE_UPDATES_XML);
   try {
-    sourceFile.copyTo(destDir, null);
-  } catch (ex) {
+    sourceUpdateXML.moveTo(destRootDir, sourceUpdateXML.leafName);
+  } catch (e) {
+    LOG(
+      "UpdateServiceStub:_migrateUpdateDirectory - Unable to move " +
+        "update XML file. Exception: " +
+        e
+    );
+  }
+
+  let sourceUpdateLog = sourcePatchDir.clone();
+  sourceUpdateLog.append(FILE_UPDATE_LOG);
+  try {
+    sourceUpdateLog.moveTo(destPatchDir, sourceUpdateLog.leafName);
+  } catch (e) {
     LOG(
-      `UpdateServiceStub:migrateFile Failed to migrate file from ` +
-        `"${sourceFile.path}" to "${destDir.path}". Exception: ${ex}`
+      "UpdateServiceStub:_migrateUpdateDirectory - Unable to move " +
+        "update log file. Exception: " +
+        e
     );
-    return;
+  }
+
+  let sourceLastUpdateLog = sourceUpdateDir.clone();
+  sourceLastUpdateLog.append(FILE_LAST_UPDATE_LOG);
+  try {
+    sourceLastUpdateLog.moveTo(destUpdateDir, sourceLastUpdateLog.leafName);
+  } catch (e) {
+    LOG(
+      "UpdateServiceStub:_migrateUpdateDirectory - Unable to move " +
+        "last-update log file. Exception: " +
+        e
+    );
   }
 
   try {
-    sourceFile.remove(false);
-  } catch (ex) {
+    sourceStatusFile.moveTo(destStatusFile.parent, destStatusFile.leafName);
+  } catch (e) {
     LOG(
-      `UpdateServiceStub:migrateFile Successfully migrated file from ` +
-        `"${sourceFile.path}" to "${destDir.path}", but was unable to remove ` +
-        `the original. Exception: ${ex}`
+      "UpdateServiceStub:_migrateUpdateDirectory - Unable to move update " +
+        "status file. Exception: " +
+        e
     );
   }
-}
 
-/**
- * If recurse is true, recurses through the directory's contents. Any empty
- * directories are removed. Directories with remaining files are left behind.
- *
- * If recurse if false, we delete the directory passed as long as it is empty.
- *
- * All errors are silenced and not thrown.
- *
- * Returns true if the directory passed in was removed. Otherwise false.
- */
-function cleanupDir(dir, recurse) {
-  let directoryEmpty = true;
+  // Remove all remaining files in the old update directory. We don't need
+  // them anymore
   try {
-    for (let file of dir.directoryEntries) {
-      if (!recurse) {
-        // If we aren't recursing, bail out after we find a single file. The
-        // directory isn't empty so we can't delete it, and we aren't going to
-        // clean out and remove any other directories.
-        return false;
-      }
-      if (file.isDirectory()) {
-        if (!cleanupDir(file, recurse)) {
-          directoryEmpty = false;
-        }
-      } else {
-        directoryEmpty = false;
-      }
-    }
-  } catch (ex) {
-    // If any of our nsIFile calls fail, just err on the side of caution and
-    // don't delete anything.
-    return false;
+    sourceRootDir.remove(true);
+  } catch (e) {
+    LOG(
+      "UpdateServiceStub:_migrateUpdateDirectory - Deletion of old update " +
+        "directory failed. Exception: " +
+        e
+    );
   }
-
-  if (directoryEmpty) {
-    try {
-      dir.remove(false);
-      return true;
-    } catch (ex) {}
-  }
-  return false;
 }
 
 /**
  * Logs a string to the error console.
  * @param   string
  *          The string to write to the error console.
  */
 function LOG(string) {
--- a/toolkit/mozapps/update/common/commonupdatedir.cpp
+++ b/toolkit/mozapps/update/common/commonupdatedir.cpp
@@ -26,36 +26,36 @@
 #  include <shlobj.h>
 #  include <strsafe.h>
 #  include <winerror.h>
 #  include "nsWindowsHelpers.h"
 #  include "updateutils_win.h"
 #endif
 
 #ifdef XP_WIN
-// This is the name of the old update directory
-// (i.e. C:\ProgramData\<OLD_ROOT_UPDATE_DIR_NAME>)
-#  define OLD_ROOT_UPDATE_DIR_NAME "Mozilla"
-// This is the name of the current update directory
-// (i.e. C:\ProgramData\<ROOT_UPDATE_DIR_NAME>)
-// It is really important that we properly set the permissions on this
-// directory at creation time. Thus, it is really important that this code be
-// the creator of this directory. We had many problems with the old update
-// directory having been previously created by old versions of Firefox. To avoid
-// this problem in the future, we are including a UUID in the root update
-// directory name to attempt to ensure that it will be created by this code and
-// won't already exist with the wrong permissions.
-#  define ROOT_UPDATE_DIR_NAME "Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38"
+// This is the name of the directory to be put in the application data directory
+// if no vendor or application name is specified.
+// (i.e. C:\ProgramData\<FALLBACK_VENDOR_NAME>)
+#  define FALLBACK_VENDOR_NAME "Mozilla"
 // This describes the directory between the "Mozilla" directory and the install
 // path hash (i.e. C:\ProgramData\Mozilla\<UPDATE_PATH_MID_DIR_NAME>\<hash>)
 #  define UPDATE_PATH_MID_DIR_NAME "updates"
+// This describes the directory between the update directory and the patch
+// directory.
+// (i.e. C:\ProgramData\Mozilla\updates\<hash>\<UPDATE_SUBDIRECTORY>\0)
+#  define UPDATE_SUBDIRECTORY "updates"
+// This defines the leaf update directory, where the MAR file is downloaded to
+// (i.e. C:\ProgramData\Mozilla\updates\<hash>\updates\<PATCH_DIRECTORY>)
+#  define PATCH_DIRECTORY "0"
+// This defines the prefix of files created to lock a directory
+#  define LOCK_FILE_PREFIX "mozlock."
 
 enum class WhichUpdateDir {
-  CurrentUpdateDir,
-  UnmigratedUpdateDir,
+  CommonAppData,
+  UserAppData,
 };
 
 /**
  * This is a very simple string class.
  *
  * This class has some substantial limitations for the sake of simplicity. It
  * has no support whatsoever for modifying a string that already has data. There
  * is, therefore, no append function and no support for automatically resizing
@@ -364,24 +364,374 @@ struct AutoPerms {
   UniqueSidPtr systemSID;
   EXPLICIT_ACCESS_W ea[3];
   mozilla::UniquePtr<ACL, LocalFreeDeleter> acl;
   mozilla::UniquePtr<uint8_t[]> securityDescriptorBuffer;
   PSECURITY_DESCRIPTOR securityDescriptor;
   SECURITY_ATTRIBUTES securityAttributes;
 };
 
+static HRESULT GetFilename(SimpleAutoString& path, SimpleAutoString& filename);
+
+enum class Tristate { False, True, Unknown };
+
+enum class Lockstate { Locked, Unlocked };
+
+/**
+ * This class will look up and store some data about the file or directory at
+ * the path given.
+ * The path can additionally be locked. For files, this is done by holding a
+ * handle to that file. For directories, this is done by holding a handle to a
+ * file within the directory.
+ */
+class FileOrDirectory {
+ private:
+  Tristate mIsHardLink;
+  DWORD mAttributes;
+  nsAutoHandle mLockHandle;
+  // This stores the name of the lock file. We need to keep track of this for
+  // directories, which are locked via a randomly named lock file inside. But
+  // we do not store a value here for files, as they do not have a separate lock
+  // file.
+  SimpleAutoString mDirLockFilename;
+
+  /**
+   * Locks the path. For directories, this is done by opening a file in the
+   * directory and storing its handle in mLockHandle. For files, we just open
+   * the file itself and store the handle.
+   * Returns true on success and false on failure.
+   *
+   * Calling this function will result in mAttributes being updated.
+   *
+   * This function is private to prevent callers from locking the directory
+   * after its attributes have been read. Part of the purpose of locking a
+   * directory is to ensure that its attributes are what we think they are and
+   * that they don't change while we hold the lock. If we get the lock after
+   * attributes are looked up, we can no longer provide that guarantee.
+   * If you think you want to call Lock(), you probably actually want to call
+   * Reset().
+   */
+  bool Lock(const wchar_t* path) {
+    mAttributes = GetFileAttributesW(path);
+    Tristate isDir = IsDirectory();
+    if (isDir == Tristate::Unknown) {
+      return false;
+    }
+
+    if (isDir == Tristate::True) {
+      SimpleAutoString lockPath;
+      if (!lockPath.AllocEmpty(MAX_PATH)) {
+        return false;
+      }
+      BOOL success = GetUUIDTempFilePath(path, NS_T(LOCK_FILE_PREFIX),
+                                         lockPath.MutableString());
+      if (!success || !lockPath.Check()) {
+        return false;
+      }
+
+      HRESULT hrv = GetFilename(lockPath, mDirLockFilename);
+      if (FAILED(hrv) || mDirLockFilename.Length() == 0) {
+        return false;
+      }
+
+      mLockHandle.own(CreateFileW(lockPath.String(), 0, 0, nullptr, OPEN_ALWAYS,
+                                  FILE_FLAG_DELETE_ON_CLOSE, nullptr));
+    } else {  // If path is not a directory
+      // The usual reason for us to lock a file is to read and change the
+      // permissions so, unlike the directory lock file, make sure we request
+      // the access necessary to read and write permissions.
+      mLockHandle.own(CreateFileW(path, WRITE_DAC | READ_CONTROL, 0, nullptr,
+                                  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
+                                  nullptr));
+    }
+    if (!IsLocked()) {
+      return false;
+    }
+    mAttributes = GetFileAttributesW(path);
+    // Directories and files are locked in different ways. If we think that we
+    // just locked one but we actually locked the other, our lock will be
+    // ineffective and we should not tell callers that this is locked.
+    // (This should fail earlier, since files cannot have children and
+    // directories cannot be opened with FILE_ATTRIBUTE_NORMAL. But just to be
+    // safe...)
+    if (isDir != IsDirectory()) {
+      Unlock();
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Helper function to normalize the access mask by converting generic access
+   * flags to specific ones to make it easier to check if permissions match.
+   */
+  void NormalizeAccessMask(ACCESS_MASK& mask) {
+    if ((mask & GENERIC_ALL) == GENERIC_ALL) {
+      mask &= ~GENERIC_ALL;
+      mask |= FILE_ALL_ACCESS;
+    }
+    if ((mask & GENERIC_READ) == GENERIC_READ) {
+      mask &= ~GENERIC_READ;
+      mask |= FILE_GENERIC_READ;
+    }
+    if ((mask & GENERIC_WRITE) == GENERIC_WRITE) {
+      mask &= ~GENERIC_WRITE;
+      mask |= FILE_GENERIC_WRITE;
+    }
+    if ((mask & GENERIC_EXECUTE) == GENERIC_EXECUTE) {
+      mask &= ~GENERIC_EXECUTE;
+      mask |= FILE_GENERIC_EXECUTE;
+    }
+  }
+
+ public:
+  FileOrDirectory()
+      : mIsHardLink(Tristate::Unknown),
+        mAttributes(INVALID_FILE_ATTRIBUTES),
+        mLockHandle(INVALID_HANDLE_VALUE) {}
+
+  /**
+   * If shouldLock is Locked:Locked, the file or directory will be locked.
+   * Note that locking is fallible and success should be checked via the
+   * IsLocked method.
+   */
+  FileOrDirectory(const SimpleAutoString& path, Lockstate shouldLock)
+      : FileOrDirectory() {
+    Reset(path, shouldLock);
+  }
+
+  /**
+   * Initializes the FileOrDirectory to the file with the path given.
+   *
+   * If shouldLock is Locked:Locked, the file or directory will be locked.
+   * Note that locking is fallible and success should be checked via the
+   * IsLocked method.
+   */
+  void Reset(const SimpleAutoString& path, Lockstate shouldLock) {
+    Unlock();
+    mDirLockFilename.Truncate();
+    if (shouldLock == Lockstate::Locked) {
+      // This will also update mAttributes.
+      Lock(path.String());
+    } else {
+      mAttributes = GetFileAttributesW(path.String());
+    }
+
+    mIsHardLink = Tristate::Unknown;
+    nsAutoHandle autoHandle;
+    HANDLE handle;
+    if (IsLocked() && IsDirectory() == Tristate::False) {
+      // If the path is a file and we locked it, we already have a handle to it.
+      // No need to open it again.
+      handle = mLockHandle.get();
+    } else {
+      handle = CreateFileW(path.String(), 0, FILE_SHARE_READ, nullptr,
+                           OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
+      // Make sure this handle gets freed automatically.
+      autoHandle.own(handle);
+    }
+
+    Tristate isLink = Tristate::Unknown;
+    if (handle != INVALID_HANDLE_VALUE) {
+      BY_HANDLE_FILE_INFORMATION info;
+      BOOL success = GetFileInformationByHandle(handle, &info);
+      if (success) {
+        if (info.nNumberOfLinks > 1) {
+          isLink = Tristate::True;
+        } else {
+          isLink = Tristate::False;
+        }
+      }
+    }
+
+    mIsHardLink = Tristate::Unknown;
+    Tristate isSymLink = IsSymLink();
+    if (isLink == Tristate::False || isSymLink == Tristate::True) {
+      mIsHardLink = Tristate::False;
+    } else if (isLink == Tristate::True && isSymLink == Tristate::False) {
+      mIsHardLink = Tristate::True;
+    }
+  }
+
+  void Unlock() { mLockHandle.own(INVALID_HANDLE_VALUE); }
+
+  bool IsLocked() const { return mLockHandle.get() != INVALID_HANDLE_VALUE; }
+
+  Tristate IsSymLink() const {
+    if (mAttributes == INVALID_FILE_ATTRIBUTES) {
+      return Tristate::Unknown;
+    }
+    if (mAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+      return Tristate::True;
+    }
+    return Tristate::False;
+  }
+
+  Tristate IsHardLink() const { return mIsHardLink; }
+
+  Tristate IsLink() const {
+    Tristate isSymLink = IsSymLink();
+    if (mIsHardLink == Tristate::True || isSymLink == Tristate::True) {
+      return Tristate::True;
+    }
+    if (mIsHardLink == Tristate::Unknown || isSymLink == Tristate::Unknown) {
+      return Tristate::Unknown;
+    }
+    return Tristate::False;
+  }
+
+  Tristate IsDirectory() const {
+    if (mAttributes == INVALID_FILE_ATTRIBUTES) {
+      return Tristate::Unknown;
+    }
+    if (mAttributes & FILE_ATTRIBUTE_DIRECTORY) {
+      return Tristate::True;
+    }
+    return Tristate::False;
+  }
+
+  Tristate IsReadonly() const {
+    if (mAttributes == INVALID_FILE_ATTRIBUTES) {
+      return Tristate::Unknown;
+    }
+    if (mAttributes & FILE_ATTRIBUTE_READONLY) {
+      return Tristate::True;
+    }
+    return Tristate::False;
+  }
+
+  DWORD Attributes() const { return mAttributes; }
+
+  /**
+   * Sets the permissions to those passed. For this to be done safely, the file
+   * must be locked and must not be a directory or a link. If these conditions
+   * are not met, the function will fail.
+   * Without locking, we can't guarantee that the file is the one we think it
+   * is. Someone might have replaced a component of the path with a symlink.
+   * With directories, setting the permissions can have the effect of setting
+   * the permissions of a malicious hardlink within.
+   */
+  HRESULT SetPerms(const AutoPerms& perms) {
+    if (IsDirectory() != Tristate::False || !IsLocked() ||
+        IsHardLink() != Tristate::False) {
+      return E_FAIL;
+    }
+
+    DWORD drv = SetSecurityInfo(mLockHandle.get(), SE_FILE_OBJECT,
+                                DACL_SECURITY_INFORMATION, nullptr, nullptr,
+                                perms.acl.get(), nullptr);
+    return HRESULT_FROM_WIN32(drv);
+  }
+
+  /**
+   * Checks the permissions of a file to make sure that they match the expected
+   * permissions.
+   */
+  Tristate PermsOk(const SimpleAutoString& path, const AutoPerms& perms) {
+    nsAutoHandle autoHandle;
+    HANDLE handle;
+    if (IsDirectory() == Tristate::False && IsLocked()) {
+      handle = mLockHandle.get();
+    } else {
+      handle =
+          CreateFileW(path.String(), READ_CONTROL, FILE_SHARE_READ, nullptr,
+                      OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
+      // Make sure this handle gets freed automatically.
+      autoHandle.own(handle);
+    }
+
+    PACL dacl = nullptr;
+    SECURITY_DESCRIPTOR* securityDescriptor = nullptr;
+    DWORD drv = GetSecurityInfo(
+        handle, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr,
+        &dacl, nullptr,
+        reinterpret_cast<PSECURITY_DESCRIPTOR*>(&securityDescriptor));
+    // Store the security descriptor in a UniquePtr so that it automatically
+    // gets freed properly. We don't need to worry about dacl, since it will
+    // point within the security descriptor.
+    mozilla::UniquePtr<SECURITY_DESCRIPTOR, LocalFreeDeleter>
+        autoSecurityDescriptor(securityDescriptor);
+    if (drv == ERROR_ACCESS_DENIED) {
+      // If access was denied reading the permissions, it seems pretty safe to
+      // say that the permissions are wrong.
+      return Tristate::False;
+    }
+    if (drv != ERROR_SUCCESS || dacl == nullptr) {
+      return Tristate::Unknown;
+    }
+
+    size_t eaLen = sizeof(perms.ea) / sizeof(perms.ea[0]);
+    for (size_t eaIndex = 0; eaIndex < eaLen; ++eaIndex) {
+      PTRUSTEE_W trustee = const_cast<PTRUSTEE_W>(&perms.ea[eaIndex].Trustee);
+      ACCESS_MASK expectedMask = perms.ea[eaIndex].grfAccessPermissions;
+      ACCESS_MASK actualMask;
+      drv = GetEffectiveRightsFromAclW(dacl, trustee, &actualMask);
+      if (drv == ERROR_ACCESS_DENIED) {
+        return Tristate::False;
+      }
+      if (drv != ERROR_SUCCESS) {
+        return Tristate::Unknown;
+      }
+      NormalizeAccessMask(expectedMask);
+      NormalizeAccessMask(actualMask);
+      if ((actualMask & expectedMask) != expectedMask) {
+        return Tristate::False;
+      }
+    }
+
+    return Tristate::True;
+  }
+
+  /**
+   * Valid only if IsDirectory() == True.
+   * Checks to see if the string given matches the filename of the lock file.
+   */
+  bool LockFilenameMatches(const wchar_t* filename) {
+    if (mDirLockFilename.Length() == 0) {
+      return false;
+    }
+    return wcscmp(filename, mDirLockFilename.String()) == 0;
+  }
+};
+
 static bool GetCachedHash(const char16_t* installPath, HKEY rootKey,
                           const SimpleAutoString& regPath,
                           mozilla::UniquePtr<NS_tchar[]>& result);
 static HRESULT GetUpdateDirectory(const wchar_t* installPath,
+                                  const char* vendor, const char* appName,
                                   WhichUpdateDir whichDir,
+                                  SetPermissionsOf permsToSet,
                                   mozilla::UniquePtr<wchar_t[]>& result);
+static HRESULT EnsureUpdateDirectoryPermissions(
+    const SimpleAutoString& basePath, const SimpleAutoString& updatePath,
+    bool fullUpdatePath, SetPermissionsOf permsToSet);
 static HRESULT GeneratePermissions(AutoPerms& result);
 static HRESULT MakeDir(const SimpleAutoString& path, const AutoPerms& perms);
+static HRESULT RemoveRecursive(const SimpleAutoString& path,
+                               FileOrDirectory& file);
+static HRESULT MoveConflicting(const SimpleAutoString& path,
+                               FileOrDirectory& file,
+                               SimpleAutoString* outPath);
+static HRESULT EnsureCorrectPermissions(SimpleAutoString& path,
+                                        FileOrDirectory& file,
+                                        const SimpleAutoString& leafUpdateDir,
+                                        const AutoPerms& perms,
+                                        SetPermissionsOf permsToSet);
+static HRESULT FixDirectoryPermissions(const SimpleAutoString& path,
+                                       FileOrDirectory& directory,
+                                       const AutoPerms& perms,
+                                       bool& permissionsFixed);
+static HRESULT MoveFileOrDir(const SimpleAutoString& moveFrom,
+                             const SimpleAutoString& moveTo,
+                             const AutoPerms& perms);
+static HRESULT SplitPath(const SimpleAutoString& path,
+                         SimpleAutoString& parentPath,
+                         SimpleAutoString& filename);
+static bool PathConflictsWithLeaf(const SimpleAutoString& path,
+                                  const SimpleAutoString& leafPath);
 #endif  // XP_WIN
 
 /**
  * Returns a hash of the install path, suitable for uniquely identifying the
  * particular Firefox installation that is running.
  *
  * This function includes a compatibility mode that should NOT be used except by
  * GetUserUpdateDirectory. Previous implementations of this function could
@@ -390,36 +740,56 @@ static HRESULT MakeDir(const SimpleAutoS
  * values consistent with those generated by the installer. The compatibility
  * mode is retained only so that we can properly get the old update directory
  * when migrating it.
  *
  * @param   installPath
  *          The null-terminated path to the installation directory (i.e. the
  *          directory that contains the binary). Must not be null. The path must
  *          not include a trailing slash.
+ * @param   vendor
+ *          A pointer to a null-terminated string containing the vendor name, or
+ *          null. This is only used to look up a registry key on Windows. On
+ *          other platforms, the value has no effect. If null is passed on
+ *          Windows, "Mozilla" will be used.
  * @param   result
  *          The out parameter that will be set to contain the resulting hash.
  *          The value is wrapped in a UniquePtr to make cleanup easier on the
  *          caller.
+ * @param   useCompatibilityMode
+ *          Enables compatibility mode. Defaults to false.
  * @return  true if successful and false otherwise.
  */
-bool GetInstallHash(const char16_t* installPath,
-                    mozilla::UniquePtr<NS_tchar[]>& result) {
+bool GetInstallHash(const char16_t* installPath, const char* vendor,
+                    mozilla::UniquePtr<NS_tchar[]>& result,
+                    bool useCompatibilityMode /* = false */) {
   MOZ_ASSERT(installPath != nullptr,
              "Install path must not be null in GetInstallHash");
 
+  // Unable to get the cached hash, so compute it.
   size_t pathSize =
       std::char_traits<char16_t>::length(installPath) * sizeof(*installPath);
   uint64_t hash =
       CityHash64(reinterpret_cast<const char*>(installPath), pathSize);
 
   size_t hashStrSize = sizeof(hash) * 2 + 1;  // 2 hex digits per byte + null
   result = mozilla::MakeUnique<NS_tchar[]>(hashStrSize);
-  int charsWritten =
-      NS_tsnprintf(result.get(), hashStrSize, NS_T("%") NS_T(PRIX64), hash);
+  int charsWritten;
+  if (useCompatibilityMode) {
+    // This behavior differs slightly from the default behavior.
+    // When the default output would be "1234567800000009", this instead
+    // produces "123456789".
+    charsWritten = NS_tsnprintf(result.get(), hashStrSize,
+                                NS_T("%") NS_T(PRIX32) NS_T("%") NS_T(PRIX32),
+                                static_cast<uint32_t>(hash >> 32),
+                                static_cast<uint32_t>(hash));
+  } else {
+    charsWritten =
+        NS_tsnprintf(result.get(), hashStrSize, NS_T("%") NS_T(PRIX64), hash);
+  }
   return !(charsWritten < 1 ||
            static_cast<size_t>(charsWritten) > hashStrSize - 1);
 }
 
 #ifdef XP_WIN
 /**
  * Returns true if the registry key was successfully found and read into result.
  */
@@ -448,170 +818,350 @@ static bool GetCachedHash(const char16_t
  * different permissions from the default, so we don't really want anyone using
  * the path without the directory already being created with the correct
  * permissions. Therefore, this function also ensures that the base directory
  * that needs permissions set already exists. If it does not exist, it is
  * created with the needed permissions.
  * The desired permissions give Full Control to SYSTEM, Administrators, and
  * Users.
  *
+ * vendor and appName are passed as char*, not because we want that (we don't,
+ * we want wchar_t), but because of the expected origin of the data. If this
+ * data is available, it is probably available via XREAppData::vendor and
+ * XREAppData::name.
+ *
  * @param   installPath
- *          Must be the null-terminated path to the installation directory (i.e.
- *          the directory that contains the binary). The path must not include a
- *          trailing slash.
+ *          The null-terminated path to the installation directory (i.e. the
+ *          directory that contains the binary). The path must not include a
+ *          trailing slash. If null is passed for this value, the entire update
+ *          directory path cannot be retrieved, so the function will return the
+ *          update directory without the installation-specific leaf directory.
+ *          This feature exists for when the caller wants to use this function
+ *          to set directory permissions and does not need the full update
+ *          directory path.
+ * @param   vendor
+ *          A pointer to a null-terminated string containing the vendor name.
+ *          Will default to "Mozilla" if null is passed.
+ * @param   appName
+ *          A pointer to a null-terminated string containing the application
+ *          name, or null.
+ * @param   permsToSet
+ *          Determines how aggressive to be when setting permissions.
+ *          This is the behavior by value:
+ *          BaseDirIfNotExists - Sets the permissions on the base
+ *                               directory, but only if it does not
+ *                               already exist.
+ *          AllFilesAndDirs - Recurses through the base directory,
+ *                            setting the permissions on all files
+ *                            and directories contained. Symlinks
+ *                            are removed. Files with names
+ *                            conflicting with the creation of the
+ *                            update directory are moved or removed.
+ *          FilesAndDirsWithBadPerms - Same as AllFilesAndDirs, but does not
+ *                                     attempt to fix permissions if they
+ *                                     cannot be determined.
  * @param   result
  *          The out parameter that will be set to contain the resulting path.
  *          The value is wrapped in a UniquePtr to make cleanup easier on the
  *          caller.
  *
  * @return  An HRESULT that should be tested with SUCCEEDED or FAILED.
  */
 HRESULT
 GetCommonUpdateDirectory(const wchar_t* installPath,
+                         SetPermissionsOf permsToSet,
                          mozilla::UniquePtr<wchar_t[]>& result) {
-  return GetUpdateDirectory(installPath, WhichUpdateDir::CurrentUpdateDir,
-                            result);
+  return GetUpdateDirectory(installPath, nullptr, nullptr,
+                            WhichUpdateDir::CommonAppData, permsToSet, result);
 }
 
 /**
  * This function is identical to the function above except that it gets the
- * "old" (pre-migration) update directory.
+ * "old" (pre-migration) update directory that is located in the user's app data
+ * directory, rather than the new one in the common app data directory.
  *
- * The other difference is that this function does not create the directory.
+ * The other difference is that this function does not create or change the
+ * permissions of the update directory since the default permissions on this
+ * directory are acceptable as they are.
  */
 HRESULT
-GetOldUpdateDirectory(const wchar_t* installPath,
-                      mozilla::UniquePtr<wchar_t[]>& result) {
-  return GetUpdateDirectory(installPath, WhichUpdateDir::UnmigratedUpdateDir,
-                            result);
+GetUserUpdateDirectory(const wchar_t* installPath, const char* vendor,
+                       const char* appName,
+                       mozilla::UniquePtr<wchar_t[]>& result) {
+  return GetUpdateDirectory(
+      installPath, vendor, appName, WhichUpdateDir::UserAppData,
+      SetPermissionsOf::BaseDirIfNotExists,  // Arbitrary value
+      result);
 }
 
 /**
- * This is a version of the GetCommonUpdateDirectory that can be called from
- * Rust.
+ * This is a much more limited version of the GetCommonUpdateDirectory that can
+ * be called from Rust.
  * The result parameter must be a valid pointer to a buffer of length
  * MAX_PATH + 1
  */
 extern "C" HRESULT get_common_update_directory(const wchar_t* installPath,
                                                wchar_t* result) {
   mozilla::UniquePtr<wchar_t[]> uniqueResult;
-  HRESULT hr = GetCommonUpdateDirectory(installPath, uniqueResult);
+  HRESULT hr = GetCommonUpdateDirectory(
+      installPath, SetPermissionsOf::BaseDirIfNotExists, uniqueResult);
   if (FAILED(hr)) {
     return hr;
   }
   return StringCchCopyW(result, MAX_PATH + 1, uniqueResult.get());
 }
 
 /**
  * This is a helper function that does all of the work for
- * GetCommonUpdateDirectory and GetUserUpdateDirectory.
+ * GetCommonUpdateDirectory and GetUserUpdateDirectory. It partially exists to
+ * prevent callers of GetUserUpdateDirectory from having to pass a useless
+ * SetPermissionsOf argument, which will be ignored if whichDir is UserAppData.
  *
  * For information on the parameters and return value, see
  * GetCommonUpdateDirectory.
  */
 static HRESULT GetUpdateDirectory(const wchar_t* installPath,
+                                  const char* vendor, const char* appName,
                                   WhichUpdateDir whichDir,
+                                  SetPermissionsOf permsToSet,
                                   mozilla::UniquePtr<wchar_t[]>& result) {
-  MOZ_ASSERT(installPath != nullptr,
-             "Install path must not be null in GetUpdateDirectory");
-
-  AutoPerms perms;
-  HRESULT hrv = GeneratePermissions(perms);
-  if (FAILED(hrv)) {
-    return hrv;
-  }
-
   PWSTR baseDirParentPath;
-  hrv = SHGetKnownFolderPath(FOLDERID_ProgramData, KF_FLAG_CREATE, nullptr,
-                             &baseDirParentPath);
+  REFKNOWNFOLDERID folderID = (whichDir == WhichUpdateDir::CommonAppData)
+                                  ? FOLDERID_ProgramData
+                                  : FOLDERID_LocalAppData;
+  HRESULT hrv = SHGetKnownFolderPath(folderID, KF_FLAG_CREATE, nullptr,
+                                     &baseDirParentPath);
   // Free baseDirParentPath when it goes out of scope.
   mozilla::UniquePtr<wchar_t, CoTaskMemFreeDeleter> baseDirParentPathUnique(
       baseDirParentPath);
   if (FAILED(hrv)) {
     return hrv;
   }
 
   SimpleAutoString baseDir;
-  if (whichDir == WhichUpdateDir::UnmigratedUpdateDir) {
-    const wchar_t baseDirLiteral[] = NS_T(OLD_ROOT_UPDATE_DIR_NAME);
-    hrv = baseDir.CopyFrom(baseDirLiteral);
+  if (whichDir == WhichUpdateDir::UserAppData && (vendor || appName)) {
+    const char* rawBaseDir = vendor ? vendor : appName;
+    hrv = baseDir.CopyFrom(rawBaseDir);
   } else {
-    const wchar_t baseDirLiteral[] = NS_T(ROOT_UPDATE_DIR_NAME);
+    const wchar_t baseDirLiteral[] = NS_T(FALLBACK_VENDOR_NAME);
     hrv = baseDir.CopyFrom(baseDirLiteral);
   }
   if (FAILED(hrv)) {
     return hrv;
   }
 
-  // Generate the base path
-  // (C:\ProgramData\Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38)
+  // Generate the base path (C:\ProgramData\Mozilla)
   SimpleAutoString basePath;
   size_t basePathLen =
       wcslen(baseDirParentPath) + 1 /* path separator */ + baseDir.Length();
   basePath.AllocAndAssignSprintf(basePathLen, L"%s\\%s", baseDirParentPath,
                                  baseDir.String());
   if (basePath.Length() != basePathLen) {
     return E_FAIL;
   }
 
-  if (whichDir == WhichUpdateDir::CurrentUpdateDir) {
-    hrv = MakeDir(basePath, perms);
+  // Generate the update directory path. This is the value to be returned by
+  // this function.
+  SimpleAutoString updatePath;
+  if (installPath) {
+    mozilla::UniquePtr<NS_tchar[]> hash;
+
+    // The Windows installer caches this hash value in the registry
+    bool gotHash = false;
+    SimpleAutoString regPath;
+    regPath.AutoAllocAndAssignSprintf(L"SOFTWARE\\%S\\%S\\TaskBarIDs",
+                                      vendor ? vendor : "Mozilla",
+                                      MOZ_APP_BASENAME);
+    if (regPath.Length() != 0) {
+      gotHash = GetCachedHash(reinterpret_cast<const char16_t*>(installPath),
+                              HKEY_LOCAL_MACHINE, regPath, hash);
+      if (!gotHash) {
+        gotHash = GetCachedHash(reinterpret_cast<const char16_t*>(installPath),
+                                HKEY_CURRENT_USER, regPath, hash);
+      }
+    }
+    bool success = true;
+    if (!gotHash) {
+      bool useCompatibilityMode = (whichDir == WhichUpdateDir::UserAppData);
+      success = GetInstallHash(reinterpret_cast<const char16_t*>(installPath),
+                               vendor, hash, useCompatibilityMode);
+    }
+    if (success) {
+      const wchar_t midPathDirName[] = NS_T(UPDATE_PATH_MID_DIR_NAME);
+      size_t updatePathLen = basePath.Length() + 1 /* path separator */ +
+                             wcslen(midPathDirName) + 1 /* path separator */ +
+                             wcslen(hash.get());
+      updatePath.AllocAndAssignSprintf(updatePathLen, L"%s\\%s\\%s",
+                                       basePath.String(), midPathDirName,
+                                       hash.get());
+      // Permissions can still be set without this string, so wait until after
+      // setting permissions to return failure if the string assignment failed.
+    }
+  }
+
+  if (whichDir == WhichUpdateDir::CommonAppData) {
+    if (updatePath.Length() > 0) {
+      hrv = EnsureUpdateDirectoryPermissions(basePath, updatePath, true,
+                                             permsToSet);
+    } else {
+      hrv = EnsureUpdateDirectoryPermissions(basePath, basePath, false,
+                                             permsToSet);
+    }
     if (FAILED(hrv)) {
       return hrv;
     }
   }
 
-  // Generate what we are going to call the mid-path
-  // (C:\ProgramData\Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38\updates)
-  const wchar_t midPathDirName[] = NS_T(UPDATE_PATH_MID_DIR_NAME);
-  size_t midPathLen =
-      basePath.Length() + 1 /* path separator */ + wcslen(midPathDirName);
-  SimpleAutoString midPath;
-  midPath.AllocAndAssignSprintf(midPathLen, L"%s\\%s", basePath.String(),
-                                midPathDirName);
-  if (midPath.Length() != midPathLen) {
+  if (!installPath) {
+    basePath.SwapBufferWith(result);
+    return S_OK;
+  }
+
+  if (updatePath.Length() == 0) {
     return E_FAIL;
   }
+  updatePath.SwapBufferWith(result);
+  return S_OK;
+}
+
+/**
+ * If the basePath does not exist, it is created with the expected permissions.
+ *
+ * It used to be that if basePath exists and SetPermissionsOf::AllFilesAndDirs
+ * was passed in, this function would aggressively set the permissions of
+ * the directory and everything in it. But that caused a problem: There does not
+ * seem to be a good way to ensure that, when setting permissions on a
+ * directory, a malicious process does not sneak a hard link into that directory
+ * (causing it to inherit the permissions set on the directory).
+ *
+ * To address that issue, this function now takes a different approach.
+ * To prevent abuse, permissions of directories will not be changed.
+ * Instead, directories with bad permissions are deleted and re-created with the
+ * correct permissions.
+ *
+ * @param   basePath
+ *          The top directory within the application data directory.
+ *          Typically "C:\ProgramData\Mozilla".
+ * @param   updatePath
+ *          The update directory to be checked for conflicts. If files
+ *          conflicting with this directory structure exist, they may be moved
+ *          or deleted depending on the value of permsToSet.
+ * @param   fullUpdatePath
+ *          Set to true if updatePath is the full update path. If set to false,
+ *          it means that we don't have the installation-specific path
+ *          component.
+ * @param   permsToSet
+ *          See the documentation for GetCommonUpdateDirectory for the
+ *          descriptions of the effects of each SetPermissionsOf value.
+ */
+static HRESULT EnsureUpdateDirectoryPermissions(
+    const SimpleAutoString& basePath, const SimpleAutoString& updatePath,
+    bool fullUpdatePath, SetPermissionsOf permsToSet) {
+  HRESULT returnValue = S_OK;  // Stores the value that will eventually be
+                               // returned. If errors occur, this is set to the
+                               // first error encountered.
+
+  Lockstate shouldLock = permsToSet == SetPermissionsOf::BaseDirIfNotExists
+                             ? Lockstate::Unlocked
+                             : Lockstate::Locked;
+  FileOrDirectory baseDir(basePath, shouldLock);
+  // validBaseDir will be true if the basePath exists, and is a non-symlinked
+  // directory.
+  bool validBaseDir = baseDir.IsDirectory() == Tristate::True &&
+                      baseDir.IsLink() == Tristate::False;
+
+  // The most common case when calling this function is when the caller of
+  // GetCommonUpdateDirectory just wants the update directory path, and passes
+  // in the least aggressive option for setting permissions.
+  // The most common environment is that the update directory already exists.
+  // Optimize for this case.
+  if (permsToSet == SetPermissionsOf::BaseDirIfNotExists && validBaseDir) {
+    return S_OK;
+  }
 
-  mozilla::UniquePtr<NS_tchar[]> hash;
+  AutoPerms perms;
+  HRESULT hrv = GeneratePermissions(perms);
+  if (FAILED(hrv)) {
+    // Fatal error. There is no real way to recover from this.
+    return hrv;
+  }
+
+  if (permsToSet == SetPermissionsOf::BaseDirIfNotExists) {
+    // We know that the base directory is invalid, because otherwise we would
+    // have exited already.
+    // Ignore errors here. It could be that the directory doesn't exist at all.
+    // And ultimately, we are only interested in whether or not we successfully
+    // create the new directory.
+    MoveConflicting(basePath, baseDir, nullptr);
+
+    hrv = MakeDir(basePath, perms);
+    returnValue = FAILED(returnValue) ? returnValue : hrv;
+    return returnValue;
+  }
+
+  // We need to pass a mutable basePath to EnsureCorrectPermissions, so copy it.
+  SimpleAutoString mutBasePath;
+  hrv = mutBasePath.CopyFrom(basePath);
+  if (FAILED(hrv) || mutBasePath.Length() == 0) {
+    returnValue = FAILED(returnValue) ? returnValue : hrv;
+    return returnValue;
+  }
 
-  // The Windows installer caches this hash value in the registry
-  bool gotHash = false;
-  SimpleAutoString regPath;
-  regPath.AutoAllocAndAssignSprintf(L"SOFTWARE\\Mozilla\\%S\\TaskBarIDs",
-                                    MOZ_APP_BASENAME);
-  if (regPath.Length() != 0) {
-    gotHash = GetCachedHash(reinterpret_cast<const char16_t*>(installPath),
-                            HKEY_LOCAL_MACHINE, regPath, hash);
-    if (!gotHash) {
-      gotHash = GetCachedHash(reinterpret_cast<const char16_t*>(installPath),
-                              HKEY_CURRENT_USER, regPath, hash);
+  if (fullUpdatePath) {
+    // When we are doing a full permissions reset, we are also ensuring that no
+    // files are in the way of our required directory structure. Generate the
+    // path of the furthest leaf in our directory structure so that we can check
+    // for conflicting files.
+    SimpleAutoString leafDirPath;
+    wchar_t updateSubdirectoryName[] = NS_T(UPDATE_SUBDIRECTORY);
+    wchar_t patchDirectoryName[] = NS_T(PATCH_DIRECTORY);
+    size_t leafDirLen = updatePath.Length() + wcslen(updateSubdirectoryName) +
+                        wcslen(patchDirectoryName) + 2; /* 2 path separators */
+    leafDirPath.AllocAndAssignSprintf(
+        leafDirLen, L"%s\\%s\\%s", updatePath.String(), updateSubdirectoryName,
+        patchDirectoryName);
+    if (leafDirPath.Length() == leafDirLen) {
+      hrv = EnsureCorrectPermissions(mutBasePath, baseDir, leafDirPath, perms,
+                                     permsToSet);
+    } else {
+      // If we cannot generate the leaf path, just do the best we can by using
+      // the updatePath.
+      returnValue = FAILED(returnValue) ? returnValue : E_FAIL;
+      hrv = EnsureCorrectPermissions(mutBasePath, baseDir, updatePath, perms,
+                                     permsToSet);
     }
+  } else {
+    hrv = EnsureCorrectPermissions(mutBasePath, baseDir, updatePath, perms,
+                                   permsToSet);
   }
-  // If we couldn't get it out of the registry, we'll just have to regenerate
-  // it.
-  if (!gotHash) {
-    bool success =
-        GetInstallHash(reinterpret_cast<const char16_t*>(installPath), hash);
-    if (!success) {
+  returnValue = FAILED(returnValue) ? returnValue : hrv;
+
+  // EnsureCorrectPermissions does its best to remove links and conflicting
+  // files but, in doing so, it may leave us without a base update directory.
+  // Rather than checking whether it exists first, just try to create it. If
+  // successful, the directory now exists with the right permissions and no
+  // contents, which this function considers a success. If unsuccessful,
+  // most likely the directory just already exists. But we need to verify that
+  // before we can return success.
+  BOOL success = CreateDirectoryW(
+      basePath.String(),
+      const_cast<LPSECURITY_ATTRIBUTES>(&perms.securityAttributes));
+  if (success) {
+    return S_OK;
+  }
+  if (SUCCEEDED(returnValue)) {
+    baseDir.Reset(basePath, Lockstate::Unlocked);
+    if (baseDir.IsDirectory() != Tristate::True ||
+        baseDir.IsLink() != Tristate::False ||
+        baseDir.PermsOk(basePath, perms) != Tristate::True) {
       return E_FAIL;
     }
   }
 
-  size_t updatePathLen =
-      midPath.Length() + 1 /* path separator */ + wcslen(hash.get());
-  SimpleAutoString updatePath;
-  updatePath.AllocAndAssignSprintf(updatePathLen, L"%s\\%s", midPath.String(),
-                                   hash.get());
-  if (updatePath.Length() != updatePathLen) {
-    return E_FAIL;
-  }
-
-  updatePath.SwapBufferWith(result);
-  return S_OK;
+  return returnValue;
 }
 
 /**
  * Generates the permission set that we want to be applied to the update
  * directory and its contents. Returns the permissions data via the result
  * outparam.
  *
  * These are also the permissions that will be used to check that file
@@ -700,24 +1250,647 @@ static HRESULT GeneratePermissions(AutoP
   result.securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
   result.securityAttributes.lpSecurityDescriptor = result.securityDescriptor;
   result.securityAttributes.bInheritHandle = FALSE;
   return S_OK;
 }
 
 /**
  * Creates a directory with the permissions specified. If the directory already
- * exists, this function will return success.
+ * exists, this function will return success as long as it is a non-link
+ * directory.
  */
 static HRESULT MakeDir(const SimpleAutoString& path, const AutoPerms& perms) {
   BOOL success = CreateDirectoryW(
       path.String(),
       const_cast<LPSECURITY_ATTRIBUTES>(&perms.securityAttributes));
   if (success) {
     return S_OK;
   }
   DWORD error = GetLastError();
-  if (error == ERROR_ALREADY_EXISTS) {
+  if (error != ERROR_ALREADY_EXISTS) {
+    return HRESULT_FROM_WIN32(error);
+  }
+  FileOrDirectory dir(path, Lockstate::Unlocked);
+  if (dir.IsDirectory() == Tristate::True && dir.IsLink() == Tristate::False) {
     return S_OK;
   }
   return HRESULT_FROM_WIN32(error);
 }
+
+/**
+ * Attempts to move the file or directory to the Windows Recycle Bin.
+ * If removal fails with an ERROR_FILE_NOT_FOUND, the file must not exist, so
+ * this will return success in that case.
+ *
+ * The file will be unlocked in order to remove it.
+ *
+ * Whether this function succeeds or fails, the file parameter should no longer
+ * be considered accurate. If it succeeds, it will be inaccurate because the
+ * file no longer exists. If it fails, it may be inaccurate due to this function
+ * potentially setting file attributes.
+ */
+static HRESULT RemoveRecursive(const SimpleAutoString& path,
+                               FileOrDirectory& file) {
+  file.Unlock();
+  if (file.IsReadonly() != Tristate::False) {
+    // Ignore errors setting attributes. We only care if it was successfully
+    // deleted.
+    DWORD attributes = file.Attributes();
+    if (attributes == INVALID_FILE_ATTRIBUTES) {
+      SetFileAttributesW(path.String(), FILE_ATTRIBUTE_NORMAL);
+    } else {
+      SetFileAttributesW(path.String(), attributes & ~FILE_ATTRIBUTE_READONLY);
+    }
+  }
+
+  // The SHFILEOPSTRUCTW expects a list of paths. The list is simply one long
+  // string separated by null characters. The end of the list is designated by
+  // two null characters.
+  SimpleAutoString pathList;
+  pathList.AllocAndAssignSprintf(path.Length() + 1, L"%s\0", path.String());
+
+  SHFILEOPSTRUCTW fileOperation;
+  fileOperation.hwnd = nullptr;
+  fileOperation.wFunc = FO_DELETE;
+  fileOperation.pFrom = pathList.String();
+  fileOperation.pTo = nullptr;
+  fileOperation.fFlags = FOF_ALLOWUNDO | FOF_NO_UI;
+  fileOperation.lpszProgressTitle = nullptr;
+
+  int rv = SHFileOperationW(&fileOperation);
+  if (rv == 0 || rv == ERROR_FILE_NOT_FOUND) {
+    return S_OK;
+  }
+
+  // Some files such as hard links can't be deleted properly with
+  // SHFileOperation, so additionally try DeleteFile.
+  BOOL success = DeleteFileW(path.String());
+  return success ? S_OK : HRESULT_FROM_WIN32(GetLastError());
+}
+
+/**
+ * Attempts to move the file or directory to a path that will not conflict with
+ * our directory structure. If this fails, the path will instead be deleted.
+ *
+ * If an attempt results in the error ERROR_FILE_NOT_FOUND, this function
+ * considers the file to no longer be a conflict and returns success.
+ *
+ * The file will be unlocked in order to move it. Strictly speaking, it may be
+ * possible to move non-directories without unlocking them, but this function
+ * will unconditionally unlock the file.
+ *
+ * If a non-null pointer is passed for outPath, the path that the file was moved
+ * to will be stored there. If the file was removed, an empty string will be
+ * stored. Note that if outPath is set to an empty string, it may not have a
+ * buffer allocated, so outPath.Length() should be checked before using
+ * outPath.String().
+ * It is ok for outPath to point to the path parameter.
+ * This function guarantees that if failure is returned, outPath will not be
+ * modified.
+ */
+static HRESULT MoveConflicting(const SimpleAutoString& path,
+                               FileOrDirectory& file,
+                               SimpleAutoString* outPath) {
+  file.Unlock();
+  // Try to move the file to a backup location
+  SimpleAutoString newPath;
+  unsigned int maxTries = 3;
+  const wchar_t newPathFormat[] = L"%s.bak%u";
+  size_t newPathMaxLength =
+      newPath.AllocFromScprintf(newPathFormat, path.String(), maxTries);
+  if (newPathMaxLength > 0) {
+    for (unsigned int suffix = 0; suffix <= maxTries; ++suffix) {
+      newPath.AssignSprintf(newPathMaxLength + 1, newPathFormat, path.String(),
+                            suffix);
+      if (newPath.Length() == 0) {
+        // If we failed to make this string, we probably aren't going to
+        // succeed on the next one.
+        break;
+      }
+      BOOL success;
+      if (suffix < maxTries) {
+        success = MoveFileW(path.String(), newPath.String());
+      } else {
+        // Moving a file can sometimes work when deleting a file does not. If
+        // there are already the maximum number of backed up files, try
+        // overwriting the last backup before we fall back to deleting the
+        // original.
+        success = MoveFileExW(path.String(), newPath.String(),
+                              MOVEFILE_REPLACE_EXISTING);
+      }
+      if (success) {
+        if (outPath) {
+          outPath->Swap(newPath);
+        }
+        return S_OK;
+      }
+      DWORD drv = GetLastError();
+      if (drv == ERROR_FILE_NOT_FOUND) {
+        if (outPath) {
+          outPath->Truncate();
+        }
+        return S_OK;
+      }
+      // If the move failed because newPath already exists, loop to try a new
+      // suffix. If the move failed for any other reason, a new suffix will
+      // probably not help.
+      // Sometimes, however, if we cannot read the existing file due to lack of
+      // permissions, we may get an "Access Denied" error. So retry in that case
+      // too.
+      if (drv != ERROR_ALREADY_EXISTS && drv != ERROR_ACCESS_DENIED) {
+        break;
+      }
+    }
+  }
+
+  // Moving failed. Try to delete.
+  HRESULT hrv = RemoveRecursive(path, file);
+  if (SUCCEEDED(hrv)) {
+    if (outPath) {
+      outPath->Truncate();
+    }
+  }
+  return hrv;
+}
+
+/**
+ * This function will ensure that the specified path and all contained files and
+ * subdirectories have the correct permissions.
+ * Files will have their permissions set to match those specified.
+ * Unfortunately, setting the permissions on directories is prone to abuse,
+ * since it can potentially result in a hard link within the directory
+ * inheriting those permissions. To get around this issue, directories will not
+ * have their permissions changed. Instead, the directory will be moved
+ * elsewhere so that it can be recreated with the correct permissions and its
+ * contents moved back in.
+ *
+ * Symlinks and hard links are removed from the checked directories.
+ *
+ * This function also ensures that nothing is in the way of leafUpdateDir.
+ * Non-directory files that conflict with this are moved or deleted.
+ *
+ * This function's second argument must receive a locked FileOrDirectory to
+ * ensure that it is not tampered with while fixing the permissions of the
+ * file/directory and any contents.
+ *
+ * If we cannot successfully determine if the path is a file or directory, we
+ * simply attempt to delete it.
+ *
+ * Note that the path parameter is not constant. Its contents may be changed by
+ * this function.
+ */
+static HRESULT EnsureCorrectPermissions(SimpleAutoString& path,
+                                        FileOrDirectory& file,
+                                        const SimpleAutoString& leafUpdateDir,
+                                        const AutoPerms& perms,
+                                        SetPermissionsOf permsToSet) {
+  HRESULT returnValue = S_OK;  // Stores the value that will eventually be
+                               // returned. If errors occur, this is set to the
+                               // first error encountered.
+  HRESULT hrv;
+  bool conflictsWithLeaf = PathConflictsWithLeaf(path, leafUpdateDir);
+  if (file.IsDirectory() != Tristate::True ||
+      file.IsLink() != Tristate::False) {
+    // We want to keep track of the result of trying to set the permissions
+    // separately from returnValue. If we later remove the file, we should not
+    // report an error to set permissions.
+    // SetPerms will automatically abort and return failure if it is unsafe to
+    // set the permissions on the file (for example, if it is a hard link).
+    HRESULT permSetResult = file.SetPerms(perms);
+
+    bool removed = false;
+    if (file.IsLink() != Tristate::False) {
+      hrv = RemoveRecursive(path, file);
+      returnValue = FAILED(returnValue) ? returnValue : hrv;
+      if (SUCCEEDED(hrv)) {
+        removed = true;
+      }
+    }
+
+    if (FAILED(permSetResult) && !removed) {
+      returnValue = FAILED(returnValue) ? returnValue : permSetResult;
+    }
+
+    if (conflictsWithLeaf && !removed) {
+      hrv = MoveConflicting(path, file, nullptr);
+      returnValue = FAILED(returnValue) ? returnValue : hrv;
+    }
+    return returnValue;
+  }
+
+  // If the permissions cannot be read, only try to fix them if the most
+  // aggressive permission-setting option was passed. If Firefox is experiencing
+  // problems updating, it makes sense to try to force the permissions back to
+  // being correct. But there are other times when this is run more proactively,
+  // and we don't really want to move everything around unnecessarily in those
+  // cases.
+  Tristate permissionsOk = file.PermsOk(path, perms);
+  if (permissionsOk == Tristate::False ||
+      (permissionsOk == Tristate::Unknown &&
+       permsToSet == SetPermissionsOf::AllFilesAndDirs)) {
+    bool permissionsFixed;
+    hrv = FixDirectoryPermissions(path, file, perms, permissionsFixed);
+    returnValue = FAILED(returnValue) ? returnValue : hrv;
+    // We only need to move conflicting directories if they have bad permissions
+    // that we are unable to fix. If its permissions are correct, it isn't
+    // conflicting with the leaf path, it is a component of the leaf path.
+    if (!permissionsFixed && conflictsWithLeaf) {
+      // No need to check for error here. returnValue is already a failure code
+      // because FixDirectoryPermissions failed. MoveConflicting will ensure
+      // that path is correct (or empty, on deletion) whether it succeeds or
+      // fails.
+      MoveConflicting(path, file, &path);
+      if (path.Length() == 0) {
+        // Path has been deleted.
+        return returnValue;
+      }
+    }
+    if (!file.IsLocked()) {
+      // FixDirectoryPermissions or MoveConflicting may have left the directory
+      // unlocked, but we still want to recurse into it, so re-lock it.
+      file.Reset(path, Lockstate::Locked);
+    }
+  } else if (permissionsOk != Tristate::True) {
+    // If we are skipping permission setting, we want to report failure since
+    // this function did not do its job.
+    returnValue = FAILED(returnValue) ? returnValue : E_FAIL;
+  }
+
+  // We MUST not recurse into unlocked directories or links.
+  if (!file.IsLocked() || file.IsLink() != Tristate::False ||
+      file.IsDirectory() != Tristate::True) {
+    returnValue = FAILED(returnValue) ? returnValue : E_FAIL;
+    return returnValue;
+  }
+
+  // Recurse into the directory.
+  DIR directoryHandle(path.String());
+  errno = 0;
+  for (dirent* entry = readdir(&directoryHandle); entry;
+       entry = readdir(&directoryHandle)) {
+    if (wcscmp(entry->d_name, L".") == 0 || wcscmp(entry->d_name, L"..") == 0 ||
+        file.LockFilenameMatches(entry->d_name)) {
+      continue;
+    }
+
+    SimpleAutoString childBuffer;
+    if (!childBuffer.AllocEmpty(MAX_PATH)) {
+      // Just return on this failure rather than continuing. It is unlikely that
+      // this error will go away for the next path we try.
+      return FAILED(returnValue) ? returnValue : E_OUTOFMEMORY;
+    }
+
+    childBuffer.AssignSprintf(MAX_PATH + 1, L"%s\\%s", path.String(),
+                              entry->d_name);
+    if (childBuffer.Length() == 0) {
+      returnValue = FAILED(returnValue)
+                        ? returnValue
+                        : HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW);
+      continue;
+    }
+
+    FileOrDirectory child(childBuffer, Lockstate::Locked);
+    hrv = EnsureCorrectPermissions(childBuffer, child, leafUpdateDir, perms,
+                                   permsToSet);
+    returnValue = FAILED(returnValue) ? returnValue : hrv;
+
+    // Before looping, clear any errors that might have been encountered so we
+    // can correctly get errors from readdir.
+    errno = 0;
+  }
+  if (errno != 0) {
+    returnValue = FAILED(returnValue) ? returnValue : E_FAIL;
+  }
+
+  return returnValue;
+}
+
+/**
+ * This function fixes directory permissions without setting them directly.
+ * The reasoning behind this is that if someone puts a hardlink in the
+ * directory before we set the permissions, the permissions of the linked file
+ * will be changed too. To prevent this, we will instead move the directory,
+ * recreate it with the correct permissions, and move the contents back in.
+ *
+ * The new directory will be locked with the directory parameter so that the
+ * caller can safely use the new directory. If the function fails, the directory
+ * parameter may be left locked or unlocked. However, the function will never
+ * leave the directory parameter locking something invalid. In other words, if
+ * the directory parameter is locked after this function exits, it is safe to
+ * assume that it is a locked non-link directory at the same location as the
+ * original path.
+ *
+ * The permissionsFixed outparam serves as sort of a supplement to the return
+ * value. The return value will be an error code if any part of this function
+ * fails. But the function can fail at some parts while still completing its
+ * main goal of fixing the directory permissions. To distinguish between these,
+ * this value will be set to true if the directory permissions were successfully
+ * fixed.
+ */
+static HRESULT FixDirectoryPermissions(const SimpleAutoString& path,
+                                       FileOrDirectory& directory,
+                                       const AutoPerms& perms,
+                                       bool& permissionsFixed) {
+  permissionsFixed = false;
+
+  SimpleAutoString parent;
+  SimpleAutoString dirName;
+  HRESULT hrv = SplitPath(path, parent, dirName);
+  if (FAILED(hrv)) {
+    return E_FAIL;
+  }
+
+  SimpleAutoString tempPath;
+  if (!tempPath.AllocEmpty(MAX_PATH)) {
+    return E_FAIL;
+  }
+  BOOL success = GetUUIDTempFilePath(parent.String(), dirName.String(),
+                                     tempPath.MutableString());
+  if (!success || !tempPath.Check() || tempPath.Length() == 0) {
+    return E_FAIL;
+  }
+
+  directory.Unlock();
+  success = MoveFileW(path.String(), tempPath.String());
+  if (!success) {
+    return HRESULT_FROM_WIN32(GetLastError());
+  }
+
+  success = CreateDirectoryW(path.String(), const_cast<LPSECURITY_ATTRIBUTES>(
+                                                &perms.securityAttributes));
+  if (!success) {
+    return E_FAIL;
+  }
+  directory.Reset(path, Lockstate::Locked);
+  if (!directory.IsLocked() || directory.IsLink() != Tristate::False ||
+      directory.IsDirectory() != Tristate::True ||
+      directory.PermsOk(path, perms) != Tristate::True) {
+    // Don't leave an invalid file locked when we return.
+    directory.Unlock();
+    return E_FAIL;
+  }
+  permissionsFixed = true;
+
+  FileOrDirectory tempDir(tempPath, Lockstate::Locked);
+  if (!tempDir.IsLocked() || tempDir.IsLink() != Tristate::False ||
+      tempDir.IsDirectory() != Tristate::True) {
+    return E_FAIL;
+  }
+
+  SimpleAutoString moveFrom;
+  SimpleAutoString moveTo;
+  if (!moveFrom.AllocEmpty(MAX_PATH) || !moveTo.AllocEmpty(MAX_PATH)) {
+    return E_OUTOFMEMORY;
+  }
+
+  // If we fail to move one file, we still want to try for the others. This will
+  // store the first error we encounter so it can be returned.
+  HRESULT returnValue = S_OK;
+
+  // Copy the contents of tempDir back to the original directory.
+  DIR directoryHandle(tempPath.String());
+  errno = 0;
+  for (dirent* entry = readdir(&directoryHandle); entry;
+       entry = readdir(&directoryHandle)) {
+    if (wcscmp(entry->d_name, L".") == 0 || wcscmp(entry->d_name, L"..") == 0 ||
+        tempDir.LockFilenameMatches(entry->d_name)) {
+      continue;
+    }
+
+    moveFrom.AssignSprintf(MAX_PATH + 1, L"%s\\%s", tempPath.String(),
+                           entry->d_name);
+    if (moveFrom.Length() == 0) {
+      returnValue = FAILED(returnValue)
+                        ? returnValue
+                        : HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW);
+      continue;
+    }
+
+    moveTo.AssignSprintf(MAX_PATH + 1, L"%s\\%s", path.String(), entry->d_name);
+    if (moveTo.Length() == 0) {
+      returnValue = FAILED(returnValue)
+                        ? returnValue
+                        : HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW);
+      continue;
+    }
+
+    hrv = MoveFileOrDir(moveFrom, moveTo, perms);
+    if (FAILED(hrv)) {
+      returnValue = FAILED(returnValue) ? returnValue : hrv;
+    }
+
+    // Before looping, clear any errors that might have been encountered so we
+    // can correctly get errors from readdir.
+    errno = 0;
+  }
+  if (errno != 0) {
+    returnValue = FAILED(returnValue) ? returnValue : E_FAIL;
+  }
+
+  hrv = RemoveRecursive(tempPath, tempDir);
+  returnValue = FAILED(returnValue) ? returnValue : hrv;
+
+  return returnValue;
+}
+
+/**
+ * This function moves a file or directory from one location to another.
+ * Sometimes it cannot be moved because something (probably anti-virus) has
+ * opened it. In that case, we copy the file and attempt to remove the original.
+ *
+ * If the file cannot be copied, this function will try to remove the original
+ * anyway.
+ */
+static HRESULT MoveFileOrDir(const SimpleAutoString& moveFrom,
+                             const SimpleAutoString& moveTo,
+                             const AutoPerms& perms) {
+  BOOL success = MoveFileW(moveFrom.String(), moveTo.String());
+  if (success) {
+    return S_OK;
+  }
+
+  FileOrDirectory fileToMove(moveFrom, Lockstate::Locked);
+
+  // If we fail to move one file, we still want to try for the others. This will
+  // store the first error we encounter so it can be returned.
+  HRESULT returnValue = S_OK;
+
+  if (fileToMove.IsDirectory() != Tristate::True) {
+    fileToMove.Unlock();
+    if (fileToMove.IsLink() == Tristate::False) {
+      success = CopyFileW(moveFrom.String(), moveTo.String(), TRUE);
+      if (!success) {
+        returnValue = FAILED(returnValue) ? returnValue
+                                          : HRESULT_FROM_WIN32(GetLastError());
+      }
+    }
+    success = DeleteFileW(moveFrom.String());
+    if (!success) {
+      // If we failed to delete it, try having it removed at reboot.
+      success =
+          MoveFileExW(moveFrom.String(), nullptr, MOVEFILE_DELAY_UNTIL_REBOOT);
+      if (!success) {
+        returnValue = FAILED(returnValue) ? returnValue
+                                          : HRESULT_FROM_WIN32(GetLastError());
+      }
+    }
+    return returnValue;
+  }  // Done handling files. The rest of this function is for moving a
+     // directory.
+
+  success = CreateDirectoryW(moveTo.String(), const_cast<LPSECURITY_ATTRIBUTES>(
+                                                  &perms.securityAttributes));
+  if (!success) {
+    return HRESULT_FROM_WIN32(GetLastError());
+  }
+  FileOrDirectory destDir(moveTo, Lockstate::Locked);
+
+  SimpleAutoString childPath;
+  SimpleAutoString childDestPath;
+  if (!childPath.AllocEmpty(MAX_PATH) || !childDestPath.AllocEmpty(MAX_PATH)) {
+    return E_OUTOFMEMORY;
+  }
+
+  if (!fileToMove.IsLocked() || !destDir.IsLocked() ||
+      destDir.IsDirectory() != Tristate::True ||
+      destDir.IsLink() != Tristate::False) {
+    returnValue = FAILED(returnValue) ? returnValue : E_FAIL;
+  } else if (fileToMove.IsLink() == Tristate::False) {
+    DIR directoryHandle(moveFrom.String());
+    errno = 0;
+    for (dirent* entry = readdir(&directoryHandle); entry;
+         entry = readdir(&directoryHandle)) {
+      if (wcscmp(entry->d_name, L".") == 0 ||
+          wcscmp(entry->d_name, L"..") == 0 ||
+          fileToMove.LockFilenameMatches(entry->d_name)) {
+        continue;
+      }
+
+      childPath.AssignSprintf(MAX_PATH + 1, L"%s\\%s", moveFrom.String(),
+                              entry->d_name);
+      if (childPath.Length() == 0) {
+        returnValue = FAILED(returnValue)
+                          ? returnValue
+                          : HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW);
+        continue;
+      }
+
+      childDestPath.AssignSprintf(MAX_PATH + 1, L"%s\\%s", moveTo.String(),
+                                  entry->d_name);
+      if (childDestPath.Length() == 0) {
+        returnValue = FAILED(returnValue)
+                          ? returnValue
+                          : HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW);
+        continue;
+      }
+
+      HRESULT hrv = MoveFileOrDir(childPath, childDestPath, perms);
+      if (FAILED(hrv)) {
+        returnValue = FAILED(returnValue) ? returnValue : hrv;
+      }
+
+      // Before looping, clear any errors that might have been encountered so we
+      // can correctly get errors from readdir.
+      errno = 0;
+    }
+    if (errno != 0) {
+      returnValue = FAILED(returnValue) ? returnValue : E_FAIL;
+    }
+  }
+
+  // Everything has been copied out of the directory. Now remove it.
+  HRESULT hrv = RemoveRecursive(moveFrom, fileToMove);
+  if (FAILED(hrv)) {
+    // If we failed to remove it, try having it removed on reboot.
+    success =
+        MoveFileExW(moveFrom.String(), nullptr, MOVEFILE_DELAY_UNTIL_REBOOT);
+    if (!success) {
+      returnValue = FAILED(returnValue) ? returnValue
+                                        : HRESULT_FROM_WIN32(GetLastError());
+    }
+  }
+
+  return returnValue;
+}
+
+/**
+ * Splits an absolute path into its parent directory and filename.
+ * For example, splits path="C:\foo\bar" into parentPath="C:\foo" and
+ * filename="bar".
+ */
+static HRESULT SplitPath(const SimpleAutoString& path,
+                         SimpleAutoString& parentPath,
+                         SimpleAutoString& filename) {
+  HRESULT hrv = parentPath.CopyFrom(path);
+  if (FAILED(hrv) || parentPath.Length() == 0) {
+    return hrv;
+  }
+
+  hrv = GetFilename(parentPath, filename);
+  if (FAILED(hrv)) {
+    return hrv;
+  }
+
+  size_t parentPathLen = parentPath.Length();
+  if (parentPathLen < filename.Length() + 1) {
+    return E_FAIL;
+  }
+  parentPathLen -= filename.Length() + 1;
+  parentPath.Truncate(parentPathLen);
+  if (parentPath.Length() == 0) {
+    return E_FAIL;
+  }
+
+  return S_OK;
+}
+
+/**
+ * Gets the filename of the given path. Also removes trailing path separators
+ * from the input path.
+ * Ex: If path="C:\foo\bar", filename="bar"
+ */
+static HRESULT GetFilename(SimpleAutoString& path, SimpleAutoString& filename) {
+  // Remove trailing path separators.
+  size_t pathLen = path.Length();
+  if (pathLen == 0) {
+    return E_FAIL;
+  }
+  wchar_t lastChar = path.String()[pathLen - 1];
+  while (lastChar == '/' || lastChar == '\\') {
+    --pathLen;
+    path.Truncate(pathLen);
+    if (pathLen == 0) {
+      return E_FAIL;
+    }
+    lastChar = path.String()[pathLen - 1];
+  }
+
+  const wchar_t* separator1 = wcsrchr(path.String(), '/');
+  const wchar_t* separator2 = wcsrchr(path.String(), '\\');
+  const wchar_t* separator =
+      (separator1 > separator2) ? separator1 : separator2;
+  if (separator == nullptr) {
+    return E_FAIL;
+  }
+
+  HRESULT hrv = filename.CopyFrom(separator + 1);
+  if (FAILED(hrv) || filename.Length() == 0) {
+    return E_FAIL;
+  }
+  return S_OK;
+}
+
+/**
+ * Returns true if the path conflicts with the leaf path.
+ */
+static bool PathConflictsWithLeaf(const SimpleAutoString& path,
+                                  const SimpleAutoString& leafPath) {
+  if (!leafPath.StartsWith(path)) {
+    return false;
+  }
+  // Make sure that the next character after the path ends is a path separator
+  // or the end of the string. We don't want to say that "C:\f" conflicts with
+  // "C:\foo\bar".
+  wchar_t charAfterPath = leafPath.String()[path.Length()];
+  return (charAfterPath == L'\\' || charAfterPath == L'\0');
+}
 #endif  // XP_WIN
--- a/toolkit/mozapps/update/common/commonupdatedir.h
+++ b/toolkit/mozapps/update/common/commonupdatedir.h
@@ -9,32 +9,29 @@
 
 #ifdef XP_WIN
 #  include <windows.h>
 typedef WCHAR NS_tchar;
 #else
 typedef char NS_tchar;
 #endif
 
-bool GetInstallHash(const char16_t* installPath,
-                    mozilla::UniquePtr<NS_tchar[]>& result);
+bool GetInstallHash(const char16_t* installPath, const char* vendor,
+                    mozilla::UniquePtr<NS_tchar[]>& result,
+                    bool useCompatibilityMode = false);
 
 #ifdef XP_WIN
-// In addition to getting the update directory, this function also creates it.
-// This is to ensure that, when it is created, it is created with the correct
-// permissions. The default permissions on the containing directory can cause
-// problems, so it is very, very important that we make sure that the
-// permissions are set properly. Thus, we won't even give out the path of the
-// update directory without ensuring that it was created with the correct
-// permissions.
+enum class SetPermissionsOf {
+  BaseDirIfNotExists,
+  AllFilesAndDirs,
+  FilesAndDirsWithBadPerms,
+};
+// This function does two things. It retrieves the update directory and it sets
+// the permissions of the directory and, optionally, its contents.
 HRESULT GetCommonUpdateDirectory(const wchar_t* installPath,
+                                 SetPermissionsOf dirPermsToSet,
                                  mozilla::UniquePtr<wchar_t[]>& result);
-// Returns the old common update directory. Since this directory was used before
-// we made sure to always set the correct permissions, it is possible that the
-// permissions on this directory are set such that files can only be modified
-// or deleted by the user that created them. This function exists entirely to
-// allow us to migrate files out of the old update directory and into the new
-// one.
-HRESULT GetOldUpdateDirectory(const wchar_t* installPath,
-                              mozilla::UniquePtr<wchar_t[]>& result);
+HRESULT GetUserUpdateDirectory(const wchar_t* installPath, const char* vendor,
+                               const char* appName,
+                               mozilla::UniquePtr<wchar_t[]>& result);
 #endif
 
 #endif
--- a/toolkit/mozapps/update/nsIUpdateService.idl
+++ b/toolkit/mozapps/update/nsIUpdateService.idl
@@ -458,16 +458,40 @@ interface nsIApplicationUpdateService : 
 interface nsIUpdateProcessor : nsISupports
 {
   /**
    * Stages an update while the application is running.
    */
   void processUpdate();
 
   /**
+   * Attempts to fix the permissions of the update directory. This can be done
+   * in two ways. Firefox can attempt to fix the permissions itself, or it can
+   * call into the maintenance service to request that it attempt to fix the
+   * permissions.
+   *
+   * Fixing the permissions can take some time, so this work is all done off of
+   * the main thread.
+   *
+   * Currently, this function only has a Windows implementation. On other
+   * operating systems, it will throw NS_ERROR_NOT_IMPLEMENTED.
+   *
+   * Since this function does its work off of the main thread and does not
+   * block, it will only throw if it was unable to dispatch to another thread.
+   *
+   * @param useServiceOnFailure
+   *        If set to false, Firefox will attempt to fix the permissions itself,
+   *        but the maintenance service will not be used. If set to true and
+   *        Firefox is unable to fix the permissions itself, it will attempt to
+   *        call into the maintenance service to request that it attempt to fix
+   *        the permissions.
+   */
+  void fixUpdateDirectoryPerms(in boolean useServiceOnFailure);
+
+  /**
    * The installer writes an installation-specific registry key if the
    * Maintenance Service can be used for this installation. This function checks
    * for that key's existence (it does not read or verify the key's contents).
    *
    * This function should only be called on Windows.
    *
    * @returns true if the registry key exists, false if it does not.
    * @throws  NS_ERROR_NOT_AVAILABLE
--- a/toolkit/mozapps/update/tests/TestAUSHelper.cpp
+++ b/toolkit/mozapps/update/tests/TestAUSHelper.cpp
@@ -339,17 +339,18 @@ int NS_main(int argc, NS_tchar** argv) {
     // Not implemented on non-Windows platforms
     return 1;
 #endif
   }
 
   if (!NS_tstrcmp(argv[1], NS_T("create-update-dir"))) {
 #ifdef XP_WIN
     mozilla::UniquePtr<wchar_t[]> updateDir;
-    HRESULT result = GetCommonUpdateDirectory(argv[2], updateDir);
+    HRESULT result = GetCommonUpdateDirectory(
+        argv[2], SetPermissionsOf::BaseDirIfNotExists, updateDir);
     return SUCCEEDED(result) ? 0 : 1;
 #else
     // Not implemented on non-Windows platforms
     return 1;
 #endif
   }
 
   if (NS_tchdir(argv[1]) != 0) {
--- a/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js
+++ b/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js
@@ -1764,21 +1764,27 @@ function getMockUpdRootD(aGetOldLocation
  * @throws  If called from a platform other than Windows.
  */
 function getMockUpdRootDWin(aGetOldLocation) {
   if (AppConstants.platform != "win") {
     do_throw("Windows only function called by a different platform!");
   }
 
   let relPathUpdates = "";
-  let dataDirectory = gCommonAppDataDir.clone();
+  let dataDirectory;
   if (aGetOldLocation) {
+    dataDirectory = gLocalAppDataDir.clone();
+    if (MOZ_APP_VENDOR || MOZ_APP_BASENAME) {
+      relPathUpdates += MOZ_APP_VENDOR ? MOZ_APP_VENDOR : MOZ_APP_BASENAME;
+    } else {
+      relPathUpdates += "Mozilla";
+    }
+  } else {
+    dataDirectory = gCommonAppDataDir.clone();
     relPathUpdates += "Mozilla";
-  } else {
-    relPathUpdates += "Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38";
   }
 
   relPathUpdates += "\\" + DIR_UPDATES + "\\" + gInstallDirPathHash;
   let updatesDir = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
   updatesDir.initWithPath(dataDirectory.path + "\\" + relPathUpdates);
   return updatesDir;
 }
 
--- a/toolkit/mozapps/update/tests/unit_aus_update/updateDirectoryMigrate.js
+++ b/toolkit/mozapps/update/tests/unit_aus_update/updateDirectoryMigrate.js
@@ -73,29 +73,16 @@ function writeUpdatesToOldXMLFile(aConte
  */
 function writeOldStatusFile(aStatus) {
   let file = getOldUpdatesPatchDir();
   file.append(FILE_UPDATE_STATUS);
   writeFile(file, aStatus + "\n");
 }
 
 /**
- * Writes the given data to the config file in the old (unmigrated)
- * patch directory.
- *
- * @param  aData
- *         The config data to write.
- */
-function writeOldConfigFile(aData) {
-  let file = getOldUpdatesRootDir();
-  file.append(FILE_UPDATE_CONFIG_JSON);
-  writeFile(file, aData);
-}
-
-/**
  * Gets the specified update log from the old (unmigrated) update directory
  *
  * @param   aLogLeafName
  *          The leaf name of the log to get.
  * @return  nsIFile for the update log.
  */
 function getOldUpdateLog(aLogLeafName) {
   let updateLog = getOldUpdatesDir();
@@ -115,49 +102,20 @@ async function run_test() {
 
   Services.prefs.setIntPref(PREF_APP_UPDATE_CANCELATIONS, 5);
 
   let patchProps = { state: STATE_PENDING };
   let patches = getLocalPatchString(patchProps);
   let updates = getLocalUpdateString({}, patches);
   writeUpdatesToOldXMLFile(getLocalUpdatesXMLString(updates), true);
   writeOldStatusFile(STATE_SUCCEEDED);
-  writeOldConfigFile('{"app.update.auto":false}');
 
   let log = getOldUpdateLog(FILE_UPDATE_LOG);
   writeFile(log, "Last Update Log");
 
-  let oldUninstallPingFile = getOldUpdatesRootDir();
-  const hash = oldUninstallPingFile.leafName;
-  const uninstallPingFilename = `uninstall_ping_${hash}_98537294-d37b-4b8b-a4e9-ab417a5d7a87.json`;
-  oldUninstallPingFile = oldUninstallPingFile.parent.parent;
-  oldUninstallPingFile.append(uninstallPingFilename);
-  const uninstallPingContents = "arbitrary uninstall ping file contents";
-  writeFile(oldUninstallPingFile, uninstallPingContents);
-
-  let oldBackgroundUpdateLog1File = getOldUpdatesRootDir();
-  const oldBackgroundUpdateLog1Filename = "backgroundupdate.moz_log";
-  oldBackgroundUpdateLog1File.append(oldBackgroundUpdateLog1Filename);
-  const oldBackgroundUpdateLog1Contents = "arbitrary log 1 contents";
-  writeFile(oldBackgroundUpdateLog1File, oldBackgroundUpdateLog1Contents);
-
-  let oldBackgroundUpdateLog2File = getOldUpdatesRootDir();
-  const oldBackgroundUpdateLog2Filename = "backgroundupdate.child-1.moz_log";
-  oldBackgroundUpdateLog2File.append(oldBackgroundUpdateLog2Filename);
-  const oldBackgroundUpdateLog2Contents = "arbitrary log 2 contents";
-  writeFile(oldBackgroundUpdateLog2File, oldBackgroundUpdateLog2Contents);
-
-  const pendingPingRelativePath =
-    "backgroundupdate\\datareporting\\glean\\pending_pings\\" +
-    "01234567-89ab-cdef-fedc-0123456789ab";
-  let oldPendingPingFile = getOldUpdatesRootDir();
-  oldPendingPingFile.appendRelativePath(pendingPingRelativePath);
-  const pendingPingContents = "arbitrary pending ping file contents";
-  writeFile(oldPendingPingFile, pendingPingContents);
-
   standardInit();
 
   Assert.ok(
     !gUpdateManager.downloadingUpdate,
     "there should not be a downloading update"
   );
   Assert.ok(!gUpdateManager.readyUpdate, "there should not be a ready update");
   Assert.equal(
@@ -195,52 +153,10 @@ async function run_test() {
   );
 
   log = getUpdateDirFile(FILE_BACKUP_UPDATE_LOG);
   Assert.ok(!log.exists(), MSG_SHOULD_NOT_EXIST);
 
   let dir = getUpdateDirFile(DIR_PATCH);
   Assert.ok(dir.exists(), MSG_SHOULD_EXIST);
 
-  Assert.equal(
-    await UpdateUtils.getAppUpdateAutoEnabled(),
-    false,
-    "Automatic update download setting should have been migrated."
-  );
-
-  let newUninstallPing = newDir.parent.parent;
-  newUninstallPing.append(uninstallPingFilename);
-  Assert.ok(newUninstallPing.exists(), MSG_SHOULD_EXIST);
-  Assert.equal(
-    readFile(newUninstallPing),
-    uninstallPingContents,
-    "the uninstall ping contents" + MSG_SHOULD_EQUAL
-  );
-
-  let newBackgroundUpdateLog1File = newDir.clone();
-  newBackgroundUpdateLog1File.append(oldBackgroundUpdateLog1Filename);
-  Assert.ok(newBackgroundUpdateLog1File.exists(), MSG_SHOULD_EXIST);
-  Assert.equal(
-    readFile(newBackgroundUpdateLog1File),
-    oldBackgroundUpdateLog1Contents,
-    "background log file 1 contents" + MSG_SHOULD_EQUAL
-  );
-
-  let newBackgroundUpdateLog2File = newDir.clone();
-  newBackgroundUpdateLog2File.append(oldBackgroundUpdateLog2Filename);
-  Assert.ok(newBackgroundUpdateLog2File.exists(), MSG_SHOULD_EXIST);
-  Assert.equal(
-    readFile(newBackgroundUpdateLog2File),
-    oldBackgroundUpdateLog2Contents,
-    "background log file 2 contents" + MSG_SHOULD_EQUAL
-  );
-
-  let newPendingPing = newDir.clone();
-  newPendingPing.appendRelativePath(pendingPingRelativePath);
-  Assert.ok(newPendingPing.exists(), MSG_SHOULD_EXIST);
-  Assert.equal(
-    readFile(newPendingPing),
-    pendingPingContents,
-    "the pending ping contents" + MSG_SHOULD_EQUAL
-  );
-
   doTestFinish();
 }
--- a/toolkit/xre/MultiInstanceLock.cpp
+++ b/toolkit/xre/MultiInstanceLock.cpp
@@ -7,91 +7,49 @@
 #include "MultiInstanceLock.h"
 
 #include "commonupdatedir.h"  // for GetInstallHash
 #include "mozilla/UniquePtr.h"
 #include "nsPrintfCString.h"
 #include "nsPromiseFlatString.h"
 #include "updatedefines.h"  // for NS_t* definitions
 
-#ifdef XP_WIN
-#  include <shlwapi.h>
-#else
+#ifndef XP_WIN
 #  include <fcntl.h>
 #  include <sys/stat.h>
 #  include <sys/types.h>
 #endif
 
 namespace mozilla {
 
 static bool GetLockFileName(const char* nameToken, const char16_t* installPath,
                             nsCString& filePath) {
-#ifdef XP_WIN
-  // On Windows, the lock file is placed at the path
-  // [updateDirectory]\[nameToken]-[pathHash], so first we need to get the
-  // update directory path and then append the file name.
-
-  // Note: This will return something like
-  //   C:\ProgramData\Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38\updates\<hash>
-  // But we actually are going to want to return the root update directory,
-  // the grandparent of this directory, which will look something like this:
-  //   C:\ProgramData\Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38
-  mozilla::UniquePtr<wchar_t[]> updateDir;
-  HRESULT hr = GetCommonUpdateDirectory(
-      reinterpret_cast<const wchar_t*>(installPath), updateDir);
-  if (FAILED(hr)) {
+  mozilla::UniquePtr<NS_tchar[]> pathHash;
+  if (!GetInstallHash(installPath, MOZ_APP_VENDOR, pathHash)) {
     return false;
   }
 
-  // For the path manipulation that we are about to do, it is important that
-  // the update directory have no trailing slash.
-  size_t len = wcslen(updateDir.get());
-  if (len == 0) {
-    return false;
-  }
-  if (updateDir.get()[len - 1] == '/' || updateDir.get()[len - 1] == '\\') {
-    updateDir.get()[len - 1] = '\0';
-  }
-
-  wchar_t* hashPtr = PathFindFileNameW(updateDir.get());
-  // PathFindFileNameW returns a pointer to the beginning of the string on
-  // failure.
-  if (hashPtr == updateDir.get()) {
+#ifdef XP_WIN
+  // On Windows, the lock file is placed at the path
+  // ProgramData\[vendor]\[nameToken]-[pathHash], so first we need to get the
+  // ProgramData path and then append our directory and the file name.
+  PWSTR programDataPath;
+  HRESULT hr = SHGetKnownFolderPath(FOLDERID_ProgramData, KF_FLAG_CREATE,
+                                    nullptr, &programDataPath);
+  if (FAILED(hr)) {
     return false;
   }
-
-  // We need to make a copy of the hash before we modify updateDir to get the
-  // root update dir.
-  size_t hashSize = wcslen(hashPtr) + 1;
-  mozilla::UniquePtr<wchar_t[]> hash = mozilla::MakeUnique<wchar_t[]>(hashSize);
-  errno_t error = wcscpy_s(hash.get(), hashSize, hashPtr);
-  if (error != 0) {
-    return false;
-  }
+  mozilla::UniquePtr<wchar_t, CoTaskMemFreeDeleter> programDataPathUnique(
+      programDataPath);
 
-  // Get the root update dir from the update dir.
-  BOOL success = PathRemoveFileSpecW(updateDir.get());
-  if (!success) {
-    return false;
-  }
-  success = PathRemoveFileSpecW(updateDir.get());
-  if (!success) {
-    return false;
-  }
-
-  filePath =
-      nsPrintfCString("%s\\%s-%s", NS_ConvertUTF16toUTF8(updateDir.get()).get(),
-                      nameToken, NS_ConvertUTF16toUTF8(hash.get()).get());
+  filePath = nsPrintfCString(
+      "%s\\%s\\%s-%s", NS_ConvertUTF16toUTF8(programDataPath).get(),
+      MOZ_APP_VENDOR, nameToken, NS_ConvertUTF16toUTF8(pathHash.get()).get());
 
 #else
-  mozilla::UniquePtr<NS_tchar[]> pathHash;
-  if (!GetInstallHash(installPath, pathHash)) {
-    return false;
-  }
-
   // On POSIX platforms the base path is /tmp/[vendor][nameToken]-[pathHash].
   filePath = nsPrintfCString("/tmp/%s%s-%s", MOZ_APP_VENDOR, nameToken,
                              pathHash.get());
 
 #endif
 
   return true;
 }
--- a/toolkit/xre/nsUpdateDriver.cpp
+++ b/toolkit/xre/nsUpdateDriver.cpp
@@ -792,16 +792,264 @@ nsUpdateProcessor::ProcessUpdate() {
   MOZ_ASSERT(NS_IsMainThread(), "not main thread");
   nsCOMPtr<nsIRunnable> r =
       NewRunnableMethod("nsUpdateProcessor::StartStagedUpdate", this,
                         &nsUpdateProcessor::StartStagedUpdate);
   return NS_NewNamedThread("Update Watcher", getter_AddRefs(mProcessWatcher),
                            r);
 }
 
+NS_IMETHODIMP
+nsUpdateProcessor::FixUpdateDirectoryPerms(bool aUseServiceOnFailure) {
+#ifndef XP_WIN
+  return NS_ERROR_NOT_IMPLEMENTED;
+#else
+  enum class State {
+    Initializing,
+    WaitingToStart,
+    Starting,
+    WaitingForFinish,
+  };
+
+  class FixUpdateDirectoryPermsRunnable final : public mozilla::Runnable {
+   public:
+    FixUpdateDirectoryPermsRunnable(const char* aName,
+                                    bool aUseServiceOnFailure,
+                                    const nsAutoString& aInstallPath)
+        : Runnable(aName),
+          mState(State::Initializing)
+#  ifdef MOZ_MAINTENANCE_SERVICE
+          ,
+          mUseServiceOnFailure(aUseServiceOnFailure)
+#  endif
+    {
+      size_t installPathSize = aInstallPath.Length() + 1;
+      mInstallPath = mozilla::MakeUnique<wchar_t[]>(installPathSize);
+      if (mInstallPath) {
+        HRESULT hrv = StringCchCopyW(mInstallPath.get(), installPathSize,
+                                     PromiseFlatString(aInstallPath).get());
+        if (FAILED(hrv)) {
+          mInstallPath.reset();
+        }
+      }
+    }
+
+    NS_IMETHOD Run() override {
+#  ifdef MOZ_MAINTENANCE_SERVICE
+      // These constants control how often and how many times we poll the
+      // maintenance service to see if it has stopped. If there is no delay in
+      // the event queue, this works out to 8 minutes of polling.
+      const unsigned int kMaxQueries = 2400;
+      const unsigned int kQueryIntervalMS = 200;
+      // These constants control how often and how many times we attempt to
+      // start the service. If there is no delay in the event queue, this works
+      // out to 5 seconds of polling.
+      const unsigned int kMaxStartAttempts = 50;
+      const unsigned int kStartAttemptIntervalMS = 100;
+#  endif
+
+      if (mState == State::Initializing) {
+        if (!mInstallPath) {
+          LOG(
+              ("Warning: No install path available in "
+               "FixUpdateDirectoryPermsRunnable\n"));
+        }
+        // In the event that the directory is owned by this user, we may be able
+        // to fix things without the maintenance service
+        mozilla::UniquePtr<wchar_t[]> updateDir;
+        HRESULT permResult = GetCommonUpdateDirectory(
+            mInstallPath.get(), SetPermissionsOf::AllFilesAndDirs, updateDir);
+        if (SUCCEEDED(permResult)) {
+          LOG(("Successfully fixed permissions from within Firefox\n"));
+          return NS_OK;
+        }
+#  ifdef MOZ_MAINTENANCE_SERVICE
+        else if (!mUseServiceOnFailure) {
+          LOG(
+              ("Error: Unable to fix permissions within Firefox and "
+               "maintenance service is disabled\n"));
+          return ReportUpdateError();
+        }
+#  else
+        LOG(("Error: Unable to fix permissions\n"));
+        return ReportUpdateError();
+#  endif
+
+#  ifdef MOZ_MAINTENANCE_SERVICE
+        SC_HANDLE serviceManager =
+            OpenSCManager(nullptr, nullptr,
+                          SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE);
+        mServiceManager.own(serviceManager);
+        if (!serviceManager) {
+          LOG(
+              ("Error: Unable to get the service manager. Cannot fix "
+               "permissions.\n"));
+          return NS_ERROR_FAILURE;
+        }
+        SC_HANDLE service = OpenServiceW(serviceManager, MAINTENANCE_SVC_NAME,
+                                         SERVICE_QUERY_STATUS | SERVICE_START);
+        mService.own(service);
+        if (!service) {
+          LOG(
+              ("Error: Unable to get the maintenance service. Unable fix "
+               "permissions without it.\n"));
+          return NS_ERROR_FAILURE;
+        }
+
+        mStartServiceArgCount = mInstallPath ? 3 : 2;
+        mStartServiceArgs =
+            mozilla::MakeUnique<LPCWSTR[]>(mStartServiceArgCount);
+        mStartServiceArgs[0] = L"MozillaMaintenance";
+        mStartServiceArgs[1] = L"fix-update-directory-perms";
+        if (mInstallPath) {
+          mStartServiceArgs[2] = mInstallPath.get();
+        }
+
+        mState = State::WaitingToStart;
+        mCurrentTry = 1;
+#  endif
+      }
+#  ifdef MOZ_MAINTENANCE_SERVICE
+      if (mState == State::WaitingToStart ||
+          mState == State::WaitingForFinish) {
+        SERVICE_STATUS_PROCESS ssp;
+        DWORD bytesNeeded;
+        BOOL success =
+            QueryServiceStatusEx(mService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp,
+                                 sizeof(SERVICE_STATUS_PROCESS), &bytesNeeded);
+        if (!success) {
+          DWORD lastError = GetLastError();
+          // These 3 errors can occur when the service is not yet stopped but it
+          // is stopping. If we got another error, waiting will probably not
+          // help.
+          if (lastError != ERROR_INVALID_SERVICE_CONTROL &&
+              lastError != ERROR_SERVICE_CANNOT_ACCEPT_CTRL &&
+              lastError != ERROR_SERVICE_NOT_ACTIVE) {
+            LOG(
+                ("Error: Unable to query service when fixing permissions. Got "
+                 "an error that cannot be fixed by waiting: 0x%lx\n",
+                 lastError));
+            return NS_ERROR_FAILURE;
+          }
+          if (mCurrentTry >= kMaxQueries) {
+            LOG(
+                ("Error: Unable to query service when fixing permissions: "
+                 "Timed out after %u attempts.\n",
+                 mCurrentTry));
+            return NS_ERROR_FAILURE;
+          }
+          return RetryInMS(kQueryIntervalMS);
+        } else {  // We successfully queried the service
+          if (ssp.dwCurrentState != SERVICE_STOPPED) {
+            return RetryInMS(kQueryIntervalMS);
+          }
+          if (mState == State::WaitingForFinish) {
+            if (ssp.dwWin32ExitCode != NO_ERROR) {
+              LOG(
+                  ("Error: Maintenance Service was unable to fix update "
+                   "directory permissions\n"));
+              return ReportUpdateError();
+            }
+            LOG(
+                ("Maintenance service successully fixed update directory "
+                 "permissions\n"));
+            return NS_OK;
+          }
+          mState = State::Starting;
+          mCurrentTry = 1;
+        }
+      }
+      if (mState == State::Starting) {
+        BOOL success = StartServiceW(mService, mStartServiceArgCount,
+                                     mStartServiceArgs.get());
+        if (success) {
+          mState = State::WaitingForFinish;
+          mCurrentTry = 1;
+          return RetryInMS(kQueryIntervalMS);
+        } else if (mCurrentTry >= kMaxStartAttempts) {
+          LOG(
+              ("Error: Unable to fix permissions: Timed out after %u attempts "
+               "to start the maintenance service\n",
+               mCurrentTry));
+          return NS_ERROR_FAILURE;
+        }
+        return RetryInMS(kStartAttemptIntervalMS);
+      }
+#  endif
+      // We should not have fallen through all three state checks above
+      LOG(
+          ("Error: Reached logically unreachable code when correcting update "
+           "directory permissions\n"));
+      return NS_ERROR_FAILURE;
+    }
+
+   private:
+    State mState;
+    mozilla::UniquePtr<wchar_t[]> mInstallPath;
+#  ifdef MOZ_MAINTENANCE_SERVICE
+    bool mUseServiceOnFailure;
+    unsigned int mCurrentTry;
+    nsAutoServiceHandle mServiceManager;
+    nsAutoServiceHandle mService;
+    DWORD mStartServiceArgCount;
+    mozilla::UniquePtr<LPCWSTR[]> mStartServiceArgs;
+
+    nsresult RetryInMS(unsigned int aDelayMS) {
+      ++mCurrentTry;
+      nsCOMPtr<nsIRunnable> runnable(this);
+      return NS_DelayedDispatchToCurrentThread(runnable.forget(), aDelayMS);
+    }
+#  endif
+    nsresult ReportUpdateError() {
+      return NS_DispatchToMainThread(NS_NewRunnableFunction(
+          "nsUpdateProcessor::FixUpdateDirectoryPerms::"
+          "FixUpdateDirectoryPermsRunnable::ReportUpdateError",
+          []() -> void {
+            nsCOMPtr<nsIObserverService> observerService =
+                services::GetObserverService();
+            if (NS_WARN_IF(!observerService)) {
+              return;
+            }
+            observerService->NotifyObservers(nullptr, "update-error",
+                                             u"bad-perms");
+          }));
+    }
+  };
+
+  nsCOMPtr<nsIProperties> dirSvc(
+      do_GetService("@mozilla.org/file/directory_service;1"));
+  NS_ENSURE_TRUE(dirSvc, NS_ERROR_FAILURE);
+
+  nsCOMPtr<nsIFile> appPath;
+  nsresult rv = dirSvc->Get(XRE_EXECUTABLE_FILE, NS_GET_IID(nsIFile),
+                            getter_AddRefs(appPath));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  nsCOMPtr<nsIFile> installDir;
+  rv = appPath->GetParent(getter_AddRefs(installDir));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  nsAutoString installPath;
+  rv = installDir->GetPath(installPath);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  // Stream transport service has a thread pool we can use so that this happens
+  // off the main thread.
+  nsCOMPtr<nsIEventTarget> eventTarget =
+      do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
+  NS_ENSURE_TRUE(eventTarget, NS_ERROR_FAILURE);
+
+  nsCOMPtr<nsIRunnable> runnable = new FixUpdateDirectoryPermsRunnable(
+      "FixUpdateDirectoryPermsRunnable", aUseServiceOnFailure, installPath);
+  rv = eventTarget->Dispatch(runnable.forget());
+  NS_ENSURE_SUCCESS(rv, rv);
+#endif
+  return NS_OK;
+}
+
 void nsUpdateProcessor::StartStagedUpdate() {
   MOZ_ASSERT(!NS_IsMainThread(), "main thread");
 
   nsresult rv = ProcessUpdates(mInfo.mGREDir, mInfo.mAppDir, mInfo.mUpdateRoot,
                                mInfo.mArgc, mInfo.mArgv,
                                mInfo.mAppVersion.get(), false, &mUpdaterPID);
   NS_ENSURE_SUCCESS_VOID(rv);
 
--- a/toolkit/xre/nsXREDirProvider.cpp
+++ b/toolkit/xre/nsXREDirProvider.cpp
@@ -108,33 +108,31 @@ static already_AddRefed<nsIFile> CreateP
 nsXREDirProvider* gDirServiceProvider = nullptr;
 nsIFile* gDataDirHomeLocal = nullptr;
 nsIFile* gDataDirHome = nullptr;
 nsCOMPtr<nsIFile> gDataDirProfileLocal = nullptr;
 nsCOMPtr<nsIFile> gDataDirProfile = nullptr;
 
 // These are required to allow nsXREDirProvider to be usable in xpcshell tests.
 // where gAppData is null.
-#if defined(XP_MACOSX) || defined(XP_UNIX)
+#if defined(XP_MACOSX) || defined(XP_WIN) || defined(XP_UNIX)
 static const char* GetAppName() {
   if (gAppData) {
     return gAppData->name;
   }
   return nullptr;
 }
 #endif
 
-#ifndef XP_WIN
 static const char* GetAppVendor() {
   if (gAppData) {
     return gAppData->vendor;
   }
   return nullptr;
 }
-#endif
 
 nsXREDirProvider::nsXREDirProvider() : mProfileNotified(false) {
   gDirServiceProvider = this;
 }
 
 nsXREDirProvider::~nsXREDirProvider() {
   gDirServiceProvider = nullptr;
   gDataDirHomeLocal = nullptr;
@@ -1107,18 +1105,24 @@ static nsresult GetRegWindowsAppDataFold
     _retval.Truncate(resultLen - 1);
   }
 
   return NS_OK;
 }
 #endif
 
 static nsresult HashInstallPath(nsAString& aInstallPath, nsAString& aPathHash) {
+  const char* vendor = GetAppVendor();
+  if (vendor && vendor[0] == '\0') {
+    vendor = nullptr;
+  }
+
   mozilla::UniquePtr<NS_tchar[]> hash;
-  bool success = ::GetInstallHash(PromiseFlatString(aInstallPath).get(), hash);
+  bool success =
+      ::GetInstallHash(PromiseFlatString(aInstallPath).get(), vendor, hash);
   if (!success) {
     return NS_ERROR_FAILURE;
   }
 
   // The hash string is a NS_tchar*, which is wchar* in Windows and char*
   // elsewhere.
 #ifdef XP_WIN
   aPathHash.Assign(hash.get());
@@ -1287,20 +1291,29 @@ nsresult nsXREDirProvider::GetUpdateRoot
 #elif XP_WIN
   nsAutoString installPath;
   rv = updRoot->GetPath(installPath);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mozilla::UniquePtr<wchar_t[]> updatePath;
   HRESULT hrv;
   if (aGetOldLocation) {
-    hrv =
-        GetOldUpdateDirectory(PromiseFlatString(installPath).get(), updatePath);
+    const char* vendor = GetAppVendor();
+    if (vendor && vendor[0] == '\0') {
+      vendor = nullptr;
+    }
+    const char* appName = GetAppName();
+    if (appName && appName[0] == '\0') {
+      appName = nullptr;
+    }
+    hrv = GetUserUpdateDirectory(PromiseFlatString(installPath).get(), vendor,
+                                 appName, updatePath);
   } else {
     hrv = GetCommonUpdateDirectory(PromiseFlatString(installPath).get(),
+                                   SetPermissionsOf::BaseDirIfNotExists,
                                    updatePath);
   }
   if (FAILED(hrv)) {
     return NS_ERROR_FAILURE;
   }
   nsAutoString updatePathStr;
   updatePathStr.Assign(updatePath.get());
   updRoot->InitWithPath(updatePathStr);