private void SwitchFromFlashToMassStorageMode(bool Continuation = false)
        {
            string ProgressText;

            if (Continuation)
            {
                ProgressText = "And now rebooting phone to Mass Storage mode...";
            }
            else
            {
                ProgressText = "Rebooting phone to Mass Storage mode...";
            }

            NokiaFlashModel FlashModel = (NokiaFlashModel)CurrentModel;

            if (CurrentMode == PhoneInterfaces.Lumia_Bootloader)
            {
                try
                {
                    FlashModel.SwitchToFlashAppContext();
                }
                catch { }
            }
            PhoneInfo Info = FlashModel.ReadPhoneInfo(ExtendedInfo: false);

            MassStorageWarning = null;
            if (Info.FlashAppProtocolVersionMajor < 2)
            {
                MassStorageWarning = "Switching to Mass Storage mode should take about 10 seconds. The phone should be unlocked using an Engineering SBL3 to enable Mass Storage mode. When you unlocked the bootloader, but you did not use an Engineering SBL3, an attempt to boot to Mass Storage mode may result in an unresponsive state. Installing drivers for this interface may also cause to hang the PC. So when this switch is taking too long, you should reboot both the PC and the phone. To reboot the phone, you have to perform a soft-reset. Press and hold the volume-down-button and the power-button at the same time for at least 10 seconds. This will trigger a power-cycle and the phone will reboot. Once fully booted, the phone may show strange behavior, like complaining about mail-accounts, showing old text-messages, inability to load https-websites, etc. This is expected behavior, because the time-settings of the phone are incorrect. Just wait a few seconds for the phone to get a data-connection and have the date/time synced. After that the strange behavior will stop automatically and normal operation is resumed.";
            }
            else
            {
                MassStorageWarning = "When the screen of the phone is black for a while, it could be that the phone is already in Mass Storage Mode, but there is no drive-letter assigned. To resolve this issue, open Device Manager and manually assign a drive-letter to the MainOS partition of your phone, or open a command-prompt and type: diskpart automount enable.";
                if (App.IsPnPEventLogMissing)
                {
                    MassStorageWarning += " It is also possible that the phone is in Mass Storage mode, but the Mass Storage driver on this PC failed. Your PC does not have an eventlog to detect this misbehaviour. But in this case you will see a device with an exclamation mark in Device Manager and then you need to manually reset the phone by pressing and holding the power-button for at least 10 seconds until it vibrates and reboots. After that Windows Phone Internals will revert the changes. After the phone has rebooted to the OS, you can retry to unlock the bootloader.";
                }
            }

            bool IsOldLumia    = (Info.FlashAppProtocolVersionMajor < 2);
            bool IsNewLumia    = (Info.FlashAppProtocolVersionMajor >= 2);
            bool IsUnlockedNew = false;

            if (IsNewLumia)
            {
                GPT GPT = FlashModel.ReadGPT();
                IsUnlockedNew = ((GPT.GetPartition("IS_UNLOCKED") != null) || (GPT.GetPartition("BACKUP_EFIESP") != null));
            }
            bool IsOriginalEngineeringLumia = ((!Info.SecureFfuEnabled || Info.Authenticated || Info.RdcPresent) && !IsUnlockedNew);

            if (IsOldLumia || IsOriginalEngineeringLumia)
            {
                byte[] BootModeFlagCommand        = new byte[] { 0x4E, 0x4F, 0x4B, 0x58, 0x46, 0x57, 0x00, 0x55, 0x42, 0x46, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00 }; // NOKFW UBF
                byte[] RebootCommand              = new byte[] { 0x4E, 0x4F, 0x4B, 0x52 };
                byte[] RebootToMassStorageCommand = new byte[] { 0x4E, 0x4F, 0x4B, 0x4D };                                                                         // NOKM
                IsSwitchingInterface = true;
                byte[] RebootCommandResult = ((NokiaPhoneModel)CurrentModel).ExecuteRawMethod(RebootToMassStorageCommand);
                if ((RebootCommandResult != null) && (RebootCommandResult.Length == 4)) // This means fail: NOKU (unknow command)
                {
                    BootModeFlagCommand[0x0F] = 0x4D;
                    byte[] BootFlagResult = ((NokiaPhoneModel)CurrentModel).ExecuteRawMethod(BootModeFlagCommand);
                    UInt16 ResultCode     = BitConverter.ToUInt16(BootFlagResult, 6);
                    if (ResultCode == 0)
                    {
                        PhoneNotifier.NewDeviceArrived += NewDeviceArrived;
                        ((NokiaPhoneModel)CurrentModel).ExecuteRawVoidMethod(RebootCommand);
                        ModeSwitchProgressWrapper(ProgressText, MassStorageWarning);
                        LogFile.Log("Rebooting phone to Mass Storage mode");
                    }
                    else
                    {
                        ModeSwitchErrorWrapper("Failed to switch to Mass Storage mode");
                        IsSwitchingInterface = false;
                    }
                }
                else
                {
                    PhoneNotifier.NewDeviceArrived += NewDeviceArrived;
                    ModeSwitchProgressWrapper(ProgressText, MassStorageWarning);
                    LogFile.Log("Rebooting phone to Mass Storage mode");
                }
            }
            else if (IsUnlockedNew)
            {
                new Thread(async() =>
                {
                    LogFile.BeginAction("SwitchToMassStorageMode");

                    try
                    {
                        // Implementation of writing a partition with SecureBoot variable to the phone
                        ModeSwitchProgressWrapper(ProgressText, MassStorageWarning);
                        LogFile.Log("Preparing phone for Mass Storage Mode", LogType.FileAndConsole);
                        var assembly = System.Reflection.Assembly.GetExecutingAssembly();

                        // Magic!
                        // The SBMSM resource is a compressed version of a raw NV-variable-partition.
                        // In this partition the SecureBoot variable is disabled and an extra variable is added which triggers Mass Storage Mode on next reboot.
                        // It overwrites the variable in a different NV-partition than where this variable is stored usually.
                        // This normally leads to endless-loops when the NV-variables are enumerated.
                        // But the partition contains an extra hack to break out the endless loops.
                        using (var stream = assembly.GetManifestResourceStream("WPinternals.SBMSM"))
                        {
                            using (DecompressedStream dec = new DecompressedStream(stream))
                            {
                                using (System.IO.MemoryStream SB = new System.IO.MemoryStream()) // Must be a seekable stream!
                                {
                                    dec.CopyTo(SB);

                                    // We don't need to check for the BACKUP_BS_NV partition here,
                                    // because the SecureBoot flag is disabled here.
                                    // So either the NV was already backupped or already overwritten.

                                    GPT GPT          = FlashModel.ReadGPT();
                                    Partition Target = GPT.GetPartition("UEFI_BS_NV");

                                    // We've been reading the GPT, so we let the phone reset once more to be sure that memory maps are the same
                                    WPinternalsStatus LastStatus = WPinternalsStatus.Undefined;
                                    List <FlashPart> Parts       = new List <FlashPart>();
                                    FlashPart Part   = new FlashPart();
                                    Part.StartSector = (uint)Target.FirstSector;
                                    Part.Stream      = SB;
                                    Parts.Add(Part);
                                    await LumiaV2UnlockBootViewModel.LumiaV2CustomFlash(PhoneNotifier, null, false, false, Parts, DoResetFirst: true, ClearFlashingStatusAtEnd: false, ShowProgress: false,
                                                                                        SetWorkingStatus: (m, s, v, a, st) =>
                                    {
                                        if (SetWorkingStatus != null)
                                        {
                                            if ((st == WPinternalsStatus.Scanning) || (st == WPinternalsStatus.WaitingForManualReset))
                                            {
                                                SetWorkingStatus(m, s, v, a, st);
                                            }
                                            else if ((LastStatus == WPinternalsStatus.Scanning) || (LastStatus == WPinternalsStatus.WaitingForManualReset))
                                            {
                                                SetWorkingStatus(ProgressText, MassStorageWarning);
                                            }
                                            LastStatus = st;
                                        }
                                    },
                                                                                        UpdateWorkingStatus: (m, s, v, st) =>
                                    {
                                        if (UpdateWorkingStatus != null)
                                        {
                                            if ((st == WPinternalsStatus.Scanning) || (st == WPinternalsStatus.WaitingForManualReset))
                                            {
                                                UpdateWorkingStatus(m, s, v, st);
                                            }
                                            else if ((LastStatus == WPinternalsStatus.Scanning) || (LastStatus == WPinternalsStatus.WaitingForManualReset))
                                            {
                                                SetWorkingStatus(ProgressText, MassStorageWarning);
                                            }
                                            LastStatus = st;
                                        }
                                    });
                                }
                            }
                        }

                        if (PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_BadMassStorage)
                        {
                            throw new WPinternalsException("Phone is in Mass Storage mode, but the driver on PC failed to start");
                        }

                        // Wait for bootloader
                        if (PhoneNotifier.CurrentInterface != PhoneInterfaces.Lumia_MassStorage)
                        {
                            LogFile.Log("Waiting for Mass Storage Mode (1)...", LogType.FileOnly);
                            await PhoneNotifier.WaitForArrival();
                        }

                        if (PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_BadMassStorage)
                        {
                            throw new WPinternalsException("Phone is in Mass Storage mode, but the driver on PC failed to start");
                        }

                        // Wait for mass storage mode
                        if (PhoneNotifier.CurrentInterface != PhoneInterfaces.Lumia_MassStorage)
                        {
                            LogFile.Log("Waiting for Mass Storage Mode (2)...", LogType.FileOnly);
                            await PhoneNotifier.WaitForArrival();
                        }

                        if (PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_BadMassStorage)
                        {
                            throw new WPinternalsException("Phone is in Mass Storage mode, but the driver on PC failed to start");
                        }

                        MassStorage Storage = null;
                        if (PhoneNotifier.CurrentModel is MassStorage)
                        {
                            Storage = (MassStorage)PhoneNotifier.CurrentModel;
                        }

                        if (Storage == null)
                        {
                            ModeSwitchErrorWrapper("Failed to switch to Mass Storage Mode");
                        }
                        else
                        {
                            ModeSwitchSuccessWrapper();
                        }
                    }
                    catch (Exception Ex)
                    {
                        LogFile.LogException(Ex);
                        ModeSwitchErrorWrapper(Ex.Message);
                    }

                    LogFile.EndAction("SwitchToMassStorageMode");
                }).Start();
            }
            else
            {
                ModeSwitchErrorWrapper("Bootloader was not unlocked. First unlock bootloader before you try to switch to Mass Storage Mode.");
            }
        }
 internal void SetWorkingStatus(string Message, string SubMessage, ulong?MaxProgressValue, bool ShowAnimation = true, WPinternalsStatus Status = WPinternalsStatus.Undefined)
 {
     ActivateSubContext(new BusyViewModel(Message, SubMessage, MaxProgressValue, UIContext: UIContext, ShowAnimation: ShowAnimation, ShowRebootHelp: Status == WPinternalsStatus.WaitingForManualReset));
 }
 internal void UpdateWorkingStatus(string Message, string SubMessage, ulong?CurrentProgressValue, WPinternalsStatus Status = WPinternalsStatus.Undefined)
 {
     if (SubContextViewModel is BusyViewModel Busy)
     {
         if (Message != null)
         {
             Busy.Message    = Message;
             Busy.SubMessage = SubMessage;
         }
         if ((CurrentProgressValue != null) && (Busy.ProgressUpdater != null))
         {
             try
             {
                 Busy.ProgressUpdater.SetProgress((ulong)CurrentProgressValue);
             }
             catch (Exception Ex)
             {
                 LogFile.LogException(Ex);
             }
         }
         Busy.SetShowRebootHelp(Status == WPinternalsStatus.WaitingForManualReset);
     }
 }
        internal void FlashFFUTask(string FFUPath)
        {
            new Thread(() =>
            {
                bool Result = true;

                NokiaFlashModel Phone = (NokiaFlashModel)PhoneNotifier.CurrentModel;
                PhoneInfo Info        = Phone.ReadPhoneInfo(false);

                #region Remove bootloader changes

                // If necessary remove bootloader changes
                // In case the NV vars were redirected, and a stock FFU is flashed, then the IsFlashing flag will be cleared in the redirected NV vars
                // And after a reboot the original NV vars are active again, but the IsFlashing flag is still set from when the bootloader was unlocked
                // So we will first restore the GPT, so the original vars are active again.
                // Then IsFlashing is true and the phone boots forcibly to FlashApp again.
                // Then we start normal FFU flasing and at the end the IsFlashing flag is cleared in the original vars.

                if (Info.FlashAppProtocolVersionMajor >= 2)
                {
                    byte[] GPTChunk = LumiaUnlockBootloaderViewModel.GetGptChunk(Phone, 0x20000); // TODO: Get proper profile FFU and get ChunkSizeInBytes
                    GPT GPT         = new GPT(GPTChunk);
                    FlashPart Part;
                    List <FlashPart> FlashParts = new List <FlashPart>();

                    Partition NvBackupPartition = GPT.GetPartition("BACKUP_BS_NV");
                    if (NvBackupPartition != null)
                    {
                        // This must be a left over of a half unlocked bootloader
                        Partition NvPartition               = GPT.GetPartition("UEFI_BS_NV");
                        NvBackupPartition.Name              = "UEFI_BS_NV";
                        NvBackupPartition.PartitionGuid     = NvPartition.PartitionGuid;
                        NvBackupPartition.PartitionTypeGuid = NvPartition.PartitionTypeGuid;
                        GPT.Partitions.Remove(NvPartition);

                        GPT.Rebuild();
                        Part             = new FlashPart();
                        Part.StartSector = 0;
                        Part.Stream      = new MemoryStream(GPTChunk);
                        FlashParts.Add(Part);
                    }

                    bool ClearFlashingStatus = true;

                    // We should only clear NV if there was no backup NV to be restored and the current NV contains the SB unlock.
                    if ((NvBackupPartition == null) && !Info.UefiSecureBootEnabled)
                    {
                        // ClearNV
                        Part             = new FlashPart();
                        Partition Target = GPT.GetPartition("UEFI_BS_NV");
                        Part.StartSector = (UInt32)Target.FirstSector;
                        Part.Stream      = new MemoryStream(new byte[0x40000]);
                        FlashParts.Add(Part);

                        ClearFlashingStatus = false;
                    }

                    if (FlashParts.Count > 0)
                    {
                        ActivateSubContext(new BusyViewModel("Restoring bootloader..."));
                        WPinternalsStatus LastStatus = WPinternalsStatus.Undefined;
                        LumiaV2UnlockBootViewModel.LumiaV2CustomFlash(PhoneNotifier, FFUPath, false, false, FlashParts, true, ClearFlashingStatusAtEnd: ClearFlashingStatus,
                                                                      SetWorkingStatus: (m, s, v, a, st) =>
                        {
                            if ((st == WPinternalsStatus.Scanning) || (st == WPinternalsStatus.WaitingForManualReset))
                            {
                                SetWorkingStatus(m, s, v, a, st);
                            }
                            else if ((LastStatus == WPinternalsStatus.Scanning) || (LastStatus == WPinternalsStatus.WaitingForManualReset))
                            {
                                SetWorkingStatus("Restoring bootloader...", null, null, Status: WPinternalsStatus.Flashing);
                            }
                            LastStatus = st;
                        },
                                                                      UpdateWorkingStatus: (m, s, v, st) =>
                        {
                            if ((st == WPinternalsStatus.Scanning) || (st == WPinternalsStatus.WaitingForManualReset))
                            {
                                UpdateWorkingStatus(m, s, v, st);
                            }
                            else if ((LastStatus == WPinternalsStatus.Scanning) || (LastStatus == WPinternalsStatus.WaitingForManualReset))
                            {
                                SetWorkingStatus("Restoring bootloader...", null, null, Status: WPinternalsStatus.Flashing);
                            }
                            LastStatus = st;
                        }
                                                                      ).Wait();

                        if ((PhoneNotifier.CurrentInterface != PhoneInterfaces.Lumia_Bootloader) && (PhoneNotifier.CurrentInterface != PhoneInterfaces.Lumia_Flash))
                        {
                            PhoneNotifier.WaitForArrival().Wait();
                        }

                        if (PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_Bootloader)
                        {
                            ((NokiaFlashModel)PhoneNotifier.CurrentModel).SwitchToFlashAppContext();
                        }
                    }
                }

                #endregion

                Phone = (NokiaFlashModel)PhoneNotifier.CurrentModel;

                ActivateSubContext(new BusyViewModel("Initializing flash..."));

                string ErrorSubMessage = null;

                try
                {
                    FFU FFU            = new FFU(FFUPath);
                    BusyViewModel Busy = new BusyViewModel("Flashing original FFU...", MaxProgressValue: FFU.TotalChunkCount, UIContext: UIContext);
                    ActivateSubContext(Busy);
                    byte Options = 0;
                    if (!Info.IsBootloaderSecure)
                    {
                        Options = (byte)((FlashOptions)Options | FlashOptions.SkipSignatureCheck);
                    }
                    Phone.FlashFFU(FFU, Busy.ProgressUpdater, true, Options);
                }
                catch (Exception Ex)
                {
                    LogFile.LogException(Ex);
                    if (Ex is WPinternalsException)
                    {
                        ErrorSubMessage = ((WPinternalsException)Ex).SubMessage;
                    }
                    Result = false;
                }


                if (!Result)
                {
                    ExitFailure("Flash failed!", ErrorSubMessage);
                    return;
                }

                ExitSuccess("Flash successful!", null);
            }).Start();
        }