Exemplo n.º 1
0
 public CorDebugProcess(DebugPort port, PortDefinition portDefinition)
 {
     m_port = port;
     m_portDefinition = portDefinition;
     m_guidProcessId = Guid.NewGuid();
     m_syncTerminatingObject = new object();
 }
        int IVsDeployableProjectCfg.QueryStartDeploy(uint dwOptions, int[] pfSupported, int[] pfReady)
        {
            Debug.Assert(pfSupported == null || pfSupported.Length > 0);
            Debug.Assert(pfReady == null || pfReady.Length > 0);
            Debug.Assert(dwOptions == 0);

            if (pfSupported != null)
            {
                pfSupported[0] = Utility.Boolean.TRUE;
            }

            if (pfReady != null)
            {
                pfReady[0] = Utility.Boolean.TRUE;
            }

            DebugPort port = GetDebugPort();

            if (port != null && !port.IsLocalPort)
            {
                // run this prior to deploy to assure we get the assembly list before
                // deploying, because build tasks are not allowed during deployment.
                m_project.GetDependencies(true, true, false);
            }

            return(Utility.COM_HResults.S_OK);
        }
        private bool IsTargetBigEndian()
        {
            bool fBE;

            DebugPort port = GetDebugPort();

            if (port == null)
            {
                return(false);
            }

            if (!port.IsLocalPort)
            {
                CorDebugProcess process = GetDeviceProcess();
                bool            detach  = !process.IsAttachedToEngine;
                Engine          engine  = process.AttachToEngine();
                fBE = engine.IsTargetBigEndian;
                if (detach)
                {
                    process.DetachFromEngine();
                }
            }
            else
            {
                // emulator is little endian
                fBE = false;
            }
            return(fBE);
        }
        internal CorDebugProcess GetDeviceProcess()
        {
            DebugPort port = GetDebugPort();

            Debug.Assert(!port.IsLocalPort);

            return(port.GetDeviceProcess(this.DeployDeviceName));
        }
        internal void EnsureDeviceProcess()
        {
            DebugPort port = GetDebugPort();

            if (!port.IsLocalPort)
            {
                CorDebugProcess process = port.GetDeviceProcess(this.DeployDeviceName);
            }
        }
Exemplo n.º 6
0
            public override DebugPort FindPort(string name)
            {
                for (int i = 0; i < m_ports.Length; i++)
                {
                    DebugPort port = m_ports [i];

                    if (String.Compare(port.Name, name, true) == 0)
                    {
                        return(port);
                    }
                }

                return(null);
            }
            new public int AddPort(IDebugPortRequest2 pRequest, out IDebugPort2 ppPort)
            {
                string name;

                pRequest.GetPortName(out name);
                ppPort = FindPort(name);

                if (ppPort == null)
                {
                    DebugPort port = m_ports[(int)PortFilter.TcpIp];
                    //hack, hack.  Abusing the Attach to dialog box to force the NetworkDevice port to
                    //look for a TinyCLR process
                    if (port.TryAddProcess(name) != null)
                    {
                        ppPort = port;
                    }
                }

                return(Utility.COM_HResults.BOOL_TO_HRESULT_FAIL(ppPort != null));
            }
Exemplo n.º 8
0
        private void InitializeDeployDevice(PortDefinition selected)
        {
            //What about EmulatorExe????

            int       iSelected = -1;
            DebugPort port      = this.SelectedDeployPort;

            if (port == null)
            {
                return;
            }

            PortDefinition[] portDefinitions;

            if (port.IsLocalPort)
            {
                PlatformInfo platformInfo = this.VsProjectFlavorCfg.PlatformInfo;

                PlatformInfo.Emulator[] emulators = platformInfo.Emulators;

                portDefinitions = new PortDefinition[emulators.Length];

                for (int i = 0; i < emulators.Length; i++)
                {
                    portDefinitions[i] = new PlatformInfo.PortDefinition_PeristableEmulator(emulators[i]);
                }
            }
            else
            {
                portDefinitions = port.GetPersistablePortDefinitions();
            }

            m_cbDeployDevice.Items.Clear();

            for (int iPortDefinition = 0; iPortDefinition < portDefinitions.Length; iPortDefinition++)
            {
                PortDefinition pd = portDefinitions[iPortDefinition];

                ComboBoxItemDevice cbi = new ComboBoxItemDevice(pd);
                m_cbDeployDevice.Items.Add(cbi);

                if (Object.Equals(selected, pd))
                {
                    iSelected = m_cbDeployDevice.Items.Count - 1;
                }
            }

            if (m_cbDeployDevice.Items.Count == 0)
            {
                if (selected != null && port.PortFilter == PortFilter.TcpIp && selected is PortDefinition_Tcp)
                {
                    m_cbDeployDevice.Items.Add(new ComboBoxItemDevice(selected));
                }
                else
                {
                    ComboBoxItemDevice cbi = new ComboBoxItemDevice("<none>");
                    m_cbDeployDevice.Items.Insert(0, cbi);
                }
                iSelected = 0;
            }

            if (port.PortFilter != PortFilter.TcpIp)
            {
                iSelected = 0;
            }

            if (iSelected != -1)
            {
                m_cbDeployDevice.SelectedIndex = iSelected;
            }
        }
Exemplo n.º 9
0
 public ComboBoxItemPort(DebugPort port) : base(port.Name)
 {
     m_port = port;
 }
Exemplo n.º 10
0
		public static CorDebugProcess CreateProcess (DebugPort pPort, string lpCommandLine)
		{
			CommandLineBuilder cb = new CommandLineBuilder (lpCommandLine);
			string[] args = cb.Arguments;
			string deployDeviceName = args [args.Length - 1];

			//Extract deployDeviceName
			if (!deployDeviceName.StartsWith (CorDebugProcess.c_DeployDeviceName))
				throw new Exception (String.Format ("\"{0}\" does not appear to be a valid Micro Framework device name", deployDeviceName));

			deployDeviceName = deployDeviceName.Substring (CorDebugProcess.c_DeployDeviceName.Length);
			cb.RemoveArguments (args.Length - 1, 1);

			lpCommandLine = cb.ToString ();
			//CorDebugProcess process = port.GetDeviceProcess(deployDeviceName, 60);
			CorDebugProcess process = pPort.GetDeviceProcess (deployDeviceName, 60);
			if (process == null)
				throw new Exception ("CorDebugProcess.CreateProcessEx() could not create or find the device process");

			process.StoreAssemblyPaths (args);

			bool fDidDeploy = true;     //What if we did a launch but no deploy to a device...

			if (!fDidDeploy) {
				process.Engine.RebootDevice (Engine.RebootOption.RebootClrWaitForDebugger);
			}

			return process;
		}
 public ComboBoxItemPort(DebugPort port) : base(port.Name)
 {
     m_port = port;
 }
Exemplo n.º 12
0
 private void InternalCreateProcess(
     DebugPort   port,
     string      lpApplicationName,
     string      lpCommandLine,
     IntPtr      lpProcessAttributes,
     IntPtr      lpThreadAttributes,
     int         bInheritHandles,
     uint        dwCreationFlags,
     System.IntPtr lpEnvironment,
     string      lpCurrentDirectory,
     ref _STARTUPINFO lpStartupInfo,
     ref _PROCESS_INFORMATION lpProcessInformation,
     uint        debuggingFlags
     )
 {
     if (port.IsLocalPort)
         this.CreateEmulatorProcess(port, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, ref lpProcessInformation, debuggingFlags);
     else
         this.CreateDeviceProcess(port, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, ref lpProcessInformation, debuggingFlags);
 }
Exemplo n.º 13
0
        private void UnInit()
        {
            if (m_assemblies != null)
            {
                foreach (CorDebugAssembly assembly in m_assemblies)
                {
                    ((IDisposable)assembly).Dispose();
                }

                m_assemblies = null;
            }

            if(m_win32process != null)
            {
                m_win32process.EnableRaisingEvents = false;

                // If the process hasn't already exited, we'll wait another 2 sec and kill it.
                for (int i = 1; !m_win32process.HasExited && i <= 2; i++)
                {
                    if (i == 1)
                    {
                        Thread.Yield();
                    }
                    else
                    {
                        try
                        { 
                            m_win32process.Kill();
                        }
                        catch(Win32Exception)
                        {
                        }
                        catch( NotSupportedException )
                        {
                        }
                        catch( InvalidOperationException )
                        {
                        }
                    }
                }

                m_win32process.Dispose();
                m_win32process = null;
            }

            if (m_port != null)
            {
                m_port.RemoveProcess(this.m_portDefinition);
                m_port = null;
            }

            m_appDomains = null;
            m_events = null;
            m_threads = null;
            m_assemblyPaths = null;
            m_breakpoints = null;
            m_fExecutionPaused = false;
            m_eventDispatch = null;
            m_fUpdateBreakpoints = false;
            m_cStopped = 0;
            m_fLaunched = false;
            m_fTerminating = false;
            m_fDetaching = false;
            m_dummyThreadEvent = null;
            m_cEvalThreads = 0;
            m_tdBuiltin = null;
            m_scratchPad = null;

            m_threadDispatch = null;

            if (m_corDebug != null)
            {
                m_corDebug.UnregisterProcess(this);
                m_corDebug = null;
            }
        }
Exemplo n.º 14
0
        private void CreateEmulatorProcess(
            DebugPort   port,
            string      lpApplicationName,
            string      lpCommandLine,
            IntPtr      lpProcessAttributes,
            IntPtr      lpThreadAttributes,
            int         bInheritHandles,
            uint        dwCreationFlags,
            System.IntPtr lpEnvironment,
            string      lpCurrentDirectory,
            ref _STARTUPINFO lpStartupInfo,
            ref _PROCESS_INFORMATION lpProcessInformation,
            uint        debuggingFlags
            )
        {
            VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.EmulatorCommandLine, lpCommandLine));

            try
            {
                Process emuProcess = new Process();
                emuProcess.StartInfo.FileName = lpApplicationName;
                emuProcess.StartInfo.Arguments = lpCommandLine.Substring(lpApplicationName.Length+2);
                emuProcess.StartInfo.UseShellExecute = false;

                emuProcess.StartInfo.RedirectStandardOutput = true;
                emuProcess.StartInfo.RedirectStandardError = true;
                emuProcess.StartInfo.RedirectStandardInput = false;

                // Set our event handler to asynchronously read the emulator's outputs.
                emuProcess.OutputDataReceived += new DataReceivedEventHandler(VsPackage.MessageCentre.OutputMsgHandler);
                emuProcess.ErrorDataReceived += new DataReceivedEventHandler(VsPackage.MessageCentre.ErrorMsgHandler);

                emuProcess.StartInfo.WorkingDirectory = lpCurrentDirectory;

                // Start the process.
                if(!emuProcess.Start())
                    throw new Exception("Process.Start() returned false.");

                // Start the asynchronous reads of the emulator's output streams
                emuProcess.BeginOutputReadLine();
                emuProcess.BeginErrorReadLine();

                this.PortDefinition = new PortDefinition_Emulator("Emulator", emuProcess.Id);
                this.SetPid((uint)emuProcess.Id);

                port.AddProcess(this);

                const int DUPLICATE_SAME_ACCESS = 0x00000002;
                Utility.Kernel32.DuplicateHandle(Utility.Kernel32.GetCurrentProcess(), emuProcess.Handle,
                                                 Utility.Kernel32.GetCurrentProcess(), out lpProcessInformation.hProcess,
                                                 0, false, DUPLICATE_SAME_ACCESS);
                
                lpProcessInformation.dwProcessId = (uint)emuProcess.Id;
                CreateDummyThread(out lpProcessInformation.hThread, out lpProcessInformation.dwThreadId);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(String.Format("Could not create emulator process."),ex);
            }
        }
Exemplo n.º 15
0
        private void CreateDeviceProcess(DebugPort port, string lpApplicationName, string lpCommandLine, System.IntPtr lpProcessAttributes, System.IntPtr lpThreadAttributes, int bInheritHandles, uint dwCreationFlags, System.IntPtr lpEnvironment, string lpCurrentDirectory, ref _STARTUPINFO lpStartupInfo, ref _PROCESS_INFORMATION lpProcessInformation, uint debuggingFlags)
        {
            bool fDidDeploy = true;     //What if we did a launch but no deploy to a device...

            if (!fDidDeploy)
            {
                this.Engine.RebootDevice(Engine.RebootOption.RebootClrWaitForDebugger);
            }

            DebugAssert(m_port == port);

            lpProcessInformation.dwProcessId = m_pid;

            CreateDummyThread(out lpProcessInformation.hThread, out lpProcessInformation.dwThreadId);
        }
        private void Deploy(DebugPort port)
        {
            Debug.Assert(port != null && !port.IsLocalPort);

            VsPackage.MessageCentre.InternalErrorMsg(DiagnosticStrings.StartDeployAssemblies);

            CorDebugProcess process      = null;
            bool            fDeviceFound = false;

            VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.StartingDeviceDeployment);

            for (int retries = 0; retries < 60; retries++)
            {
                VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.Iteration, retries));

                try
                {
                    process = GetDeviceProcess();

                    if (process != null)
                    {
                        switch (port.PortFilter)
                        {
                        case PortFilter.Serial:
                        case PortFilter.Usb:
                        case PortFilter.TcpIp:
                            //test the connection.  This doesn't tell you if the connection will fail during the AttachToEngine,
                            //but it's a pretty good guess.
                            VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.OpeningPort, process.PortDefinition.Port));
                            fDeviceFound = process.PortDefinition.TryToOpen();
                            if (!fDeviceFound)
                            {
                                VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.PortNotFound, process.PortDefinition.Port));
                            }
                            break;

                        default:
                            SetDeployFailure(string.Format("Device {0} has an unsupported/unexpected port type", this.DeployDeviceDescription));
                            return;
                        }

                        if (fDeviceFound)
                        {
                            break;
                        }
                    }
                }
                catch (IOException)
                {
                }

                Thread.Sleep(500);
            }

            if (!fDeviceFound || process == null)
            {
                SetDeployFailure(string.Format("Device not found or cannot be opened - {0}", this.DeployDeviceDescription));
                return;
            }

            VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.AttachingEngine);

            Engine engine = process.AttachToEngine();

            if (engine == null)
            {
                VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.CannotAttachEngine);
                SetDeployFailure(string.Format(DiagnosticStrings.UnableToCommunicate, this.DeployDeviceDescription));
                return;
            }

            VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.EngineAttached);

            try
            {
                VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.QueryingDeviceAssemblies);

                ArrayList assemblies       = new ArrayList();
                Hashtable systemAssemblies = new Hashtable();
                //Ensure Assemblies are loaded
                if (process.IsDeviceInInitializeState())
                {
                    engine.ResumeExecution();
                    Thread.Sleep(200);

                    while (process.IsDeviceInInitializeState())
                    {
                        VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.WaitingInitialize);

                        //need to break out of this or timeout or something?
                        Thread.Sleep(200);
                    }
                }

                WireProtocol.Commands.Debugging_Resolve_Assembly[] assms = engine.ResolveAllAssemblies();

                // find out which are the system assemblies
                // we will insert each system assemblies in a hash table where the value will be the assembly version
                foreach (Debugging_Resolve_Assembly resolvedAssembly in assms)
                {
                    VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.FoundAssembly, resolvedAssembly.m_reply.Name, resolvedAssembly.m_reply.m_version.ToString()));
                    if ((resolvedAssembly.m_reply.m_flags & Debugging_Resolve_Assembly.Reply.c_Deployed) == 0)
                    {
                        systemAssemblies[resolvedAssembly.m_reply.Name.ToLower()] = resolvedAssembly.m_reply.m_version;
                    }
                }

                string[] pes  = m_project.GetDependencies(true, true, engine.IsTargetBigEndian);
                string[] dlls = m_project.GetDependencies(true, false, engine.IsTargetBigEndian);

                Debug.Assert(pes.Length == dlls.Length);

                // now we will re-deploy all system assemblies
                for (int i = 0; i < pes.Length; ++i)
                {
                    string assemblyPath = pes[i];
                    string dllPath      = dlls[i];

                    //is this a system assembly?
                    string fileName          = Path.ChangeExtension(Path.GetFileName(assemblyPath), null).ToLower();
                    bool   fDeployNewVersion = true;

                    if (systemAssemblies.ContainsKey(fileName))
                    {
                        // get the version of the assembly on the device
                        Debugging_Resolve_Assembly.Version deviceVer = (WireProtocol.Commands.Debugging_Resolve_Assembly.Version)systemAssemblies[fileName];

                        // get the version of the assembly of the project
                        // We need to load the bytes for the assembly because other Load methods can override the path
                        // with gac or recently used paths.  This is the only way we control the exact assembly that is loaded.
                        byte[] asmData = null;

                        using (FileStream sr = new FileStream(dllPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            asmData = new byte[sr.Length];
                            sr.Read(asmData, 0, (int)sr.Length);
                        }

                        System.Reflection.Assembly assm = Assembly.Load(asmData); Version deployVer = assm.GetName().Version;

                        // compare versions strictly, and deploy whatever assembly does not match the version on the device
                        if (VsProject.TargetFrameworkExactMatch(deviceVer, deployVer))
                        {
                            fDeployNewVersion = false;
                        }
                        else
                        {
                            ////////////////////////////////////////////////
                            //            !!! SPECIAL CASE !!!            //
                            //                                            //
                            // MSCORLIB cannot be deployed more than once //
                            ////////////////////////////////////////////////

                            if (assm.GetName().Name.ToLower().Contains("mscorlib"))
                            {
                                string message = string.Format("Cannot deploy the base assembly '{9}', or any of his satellite assemblies, to device - {0} twice. Assembly '{9}' on the device has version {1}.{2}.{3}.{4}, while the program is trying to deploy version {5}.{6}.{7}.{8} ", this.DeployDeviceDescription, deviceVer.iMajorVersion, deviceVer.iMinorVersion, deviceVer.iBuildNumber, deviceVer.iRevisionNumber, deployVer.Major, deployVer.Minor, deployVer.Build, deployVer.Revision, assm.GetName().Name);
                                VsPackage.MessageCentre.DeploymentMsg(message);
                                SetDeployFailure(message);
                                return;
                            }
                        }
                    }
                    // append the assembly whose version does not match, or that still is not on the device, to the blob to deploy
                    if (fDeployNewVersion)
                    {
                        using (FileStream fs = File.Open(assemblyPath, FileMode.Open, FileAccess.Read))
                        {
                            VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.AddingPEtoBundle, assemblyPath));
                            long   length = (fs.Length + 3) / 4 * 4;
                            byte[] buf    = new byte[length];

                            fs.Read(buf, 0, (int)fs.Length);
                            assemblies.Add(buf);
                        }
                    }
                }

                VsPackage.MessageCentre.DeploymentMsg("Attempting deployment...");

                if (!engine.Deployment_Execute(assemblies, false, VsPackage.MessageCentre.DeploymentMsg))
                {
                    VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.DeployFailed);
                    SetDeployFailure();
                    return;
                }
            }
            finally
            {
                process.DetachFromEngine();
            }
        }
        private void Deploy(DebugPort port)
        {
            Debug.Assert(port != null && !port.IsLocalPort);

            VsPackage.MessageCentre.InternalErrorMsg(DiagnosticStrings.StartDeployAssemblies);

            CorDebugProcess process = null;
            bool fDeviceFound = false;

            VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.StartingDeviceDeployment);
            
            for(int retries = 0; retries < 60; retries++)
            {
                VsPackage.MessageCentre.DeploymentMsg( String.Format( DiagnosticStrings.Iteration, port.Name, DeployDeviceName, retries ) );
                
                try
                {   
                    process = GetDeviceProcess();

                    if (process != null)
                    {
                        switch (port.PortFilter)
                        {
                            case PortFilter.Serial:
                            case PortFilter.Usb:
                            case PortFilter.TcpIp:
                                //test the connection.  This doesn't tell you if the connection will fail during the AttachToEngine,
                                //but it's a pretty good guess.
                                VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.OpeningPort, process.PortDefinition.Port));
                                fDeviceFound = process.PortDefinition.TryToOpen();
                                if(!fDeviceFound)
                                {
                                    VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.PortNotFound, process.PortDefinition.Port));
                                }
                                break;
                            default:
                                SetDeployFailure(string.Format("Device {0} has an unsupported/unexpected port type", this.DeployDeviceDescription));
                                return;
                        }

                        if(fDeviceFound) break;
                    }
                }
                catch(IOException)
                {
                }

                Thread.Sleep(500);                
            }

            if (!fDeviceFound || process == null)
            {
                SetDeployFailure(string.Format("Device not found or cannot be opened - {0}", this.DeployDeviceDescription));
                return;
            }
            
            VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.AttachingEngine);

            Engine engine = process.AttachToEngine();

            if (engine == null)
            {
                VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.CannotAttachEngine);
                SetDeployFailure(string.Format(DiagnosticStrings.UnableToCommunicate, this.DeployDeviceDescription));
                return;
            }
            
            VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.EngineAttached);

            try
            {
                
                VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.QueryingDeviceAssemblies);
                
                ArrayList assemblies = new ArrayList();
                Hashtable systemAssemblies = new Hashtable();
                //Ensure Assemblies are loaded
                if(process.IsDeviceInInitializeState())
                {
                    engine.ResumeExecution();
                    Thread.Sleep(200);                    

                    while (process.IsDeviceInInitializeState())
                    {
                        VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.WaitingInitialize);
                    
                        //need to break out of this or timeout or something?
                        Thread.Sleep(200);
                    }
                }
                
                WireProtocol.Commands.Debugging_Resolve_Assembly[] assms = engine.ResolveAllAssemblies();
                
                // find out which are the system assemblies
                // we will insert each system assemblies in a hash table where the value will be the assembly version
                foreach (Debugging_Resolve_Assembly resolvedAssembly in assms)
                {
                    VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.FoundAssembly, resolvedAssembly.m_reply.Name, resolvedAssembly.m_reply.m_version.ToString()));
                    if ((resolvedAssembly.m_reply.m_flags & Debugging_Resolve_Assembly.Reply.c_Deployed) == 0)
                    {
                        systemAssemblies[resolvedAssembly.m_reply.Name.ToLower()] = resolvedAssembly.m_reply.m_version;
                    }
                }

                string[] pes = m_project.GetDependencies(true, true, engine.IsTargetBigEndian);
                string[] dlls = m_project.GetDependencies(true, false, engine.IsTargetBigEndian);

                Debug.Assert( pes.Length == dlls.Length );

                // now we will re-deploy all system assemblies
                for(int i = 0; i < pes.Length; ++i)
                {
                    string assemblyPath = pes[i];
                    string dllPath = dlls[i];
                    
                    //is this a system assembly?
                    string fileName = Path.ChangeExtension(Path.GetFileName(assemblyPath), null).ToLower();
                    bool fDeployNewVersion = true;

                    if (systemAssemblies.ContainsKey(fileName))
                    {
                        // get the version of the assembly on the device 
                        Debugging_Resolve_Assembly.Version deviceVer = (WireProtocol.Commands.Debugging_Resolve_Assembly.Version)systemAssemblies[fileName];
                        
                        // get the version of the assembly of the project
                        // We need to load the bytes for the assembly because other Load methods can override the path
                        // with gac or recently used paths.  This is the only way we control the exact assembly that is loaded.
                        byte[] asmData = null;

                        using(FileStream sr = new FileStream(dllPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            asmData = new byte[sr.Length];
                            sr.Read(asmData, 0, (int)sr.Length);
                        }

                        System.Reflection.Assembly assm = Assembly.Load(asmData); Version deployVer = assm.GetName().Version;

                        // compare versions strictly, and deploy whatever assembly does not match the version on the device
                        if (VsProject.TargetFrameworkExactMatch(deviceVer, deployVer))
                        {
                            fDeployNewVersion = false;
                        }
                        else
                        {
                            //////////////////////////////////////////////// 
                            //            !!! SPECIAL CASE !!!            //
                            //                                            //
                            // MSCORLIB cannot be deployed more than once //
                            ////////////////////////////////////////////////

                            if (assm.GetName().Name.ToLower().Contains("mscorlib"))
                            {
                                string message = string.Format("Cannot deploy the base assembly '{9}', or any of his satellite assemblies, to device - {0} twice. Assembly '{9}' on the device has version {1}.{2}.{3}.{4}, while the program is trying to deploy version {5}.{6}.{7}.{8} ", this.DeployDeviceDescription, deviceVer.iMajorVersion, deviceVer.iMinorVersion, deviceVer.iBuildNumber, deviceVer.iRevisionNumber, deployVer.Major, deployVer.Minor, deployVer.Build, deployVer.Revision, assm.GetName().Name);
                                VsPackage.MessageCentre.DeploymentMsg( message );
                                SetDeployFailure(message);
                                return;
                            }
                        }
                    }
                    // append the assembly whose version does not match, or that still is not on the device, to the blob to deploy
                    if (fDeployNewVersion)
                    {
                        using (FileStream fs = File.Open(assemblyPath, FileMode.Open, FileAccess.Read))
                        {
                            VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.AddingPEtoBundle, assemblyPath));
                            long length = (fs.Length + 3) / 4 * 4;
                            byte[] buf = new byte[length];

                            fs.Read(buf, 0, (int)fs.Length);
                            assemblies.Add(buf);
                        }
                    }
                }
                
                VsPackage.MessageCentre.DeploymentMsg("Attempting deployment...");

                if (!engine.Deployment_Execute(assemblies, false, VsPackage.MessageCentre.DeploymentMsg))
                {
                    VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.DeployFailed);
                    SetDeployFailure();
                    return;
                }
            }
            finally
            {
                process.DetachFromEngine();
            }
        }
        public unsafe int DebugLaunch(uint grfLaunch)
        {
            try
            {
                if (!this.m_project.CanLaunch)
                {
                    Utility.ShowMessageBox("The project must have either an output type of 'Console Application', or an output type of 'Class Library' and the start action set to a valid .NET MicroFramework application");
                    return(Utility.COM_HResults.E_FAIL);
                }

                //Consider Launching ourselves (at least for device), and then calling Attach.
                //This would get rid of the ugly dummy thread hack in CorDebugProcess.
                //However, we would need to jump through some other hoops, like resuming the process,
                //perhaps setting up the entry point breakpoint ourselves, ..?

                VsDebugTargetInfo2 vsDebugTargetInfo = new VsDebugTargetInfo2();
                DebugPort          port         = GetDebugPort();
                Process            processWin32 = null;
                bool fNoDebug = (__VSDBGLAUNCHFLAGS.DBGLAUNCH_NoDebug & (__VSDBGLAUNCHFLAGS)grfLaunch) != 0;
                int  hRes     = Utility.COM_HResults.S_OK;
                PlatformInfo.Emulator emulatorConfig = GetEmulatorConfig();

                if (port == null)
                {
                    throw new Exception("Cannot find port to deploy to");
                }

                string commandLine = GetCommandLineForLaunch(fNoDebug, emulatorConfig, IsTargetBigEndian());
                string exe         = port.IsLocalPort ? emulatorConfig.application : typeof(CorDebugProcess).Assembly.Location;

                if (!fNoDebug)
                {
                    commandLine = string.Format("{0} \"{1}{2}\"", commandLine, CorDebugProcess.c_DeployDeviceName, this.DeployDeviceName);
                }

                //use emulator args even though this may be a device launch.  This is needed to store
                //paths to assemblies.
                vsDebugTargetInfo.bstrArg           = commandLine;
                vsDebugTargetInfo.bstrCurDir        = (string)m_project.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectDir);
                vsDebugTargetInfo.bstrEnv           = null;
                vsDebugTargetInfo.bstrExe           = exe;
                vsDebugTargetInfo.bstrOptions       = null;
                vsDebugTargetInfo.bstrPortName      = DeployTransportName;
                vsDebugTargetInfo.bstrRemoteMachine = null;
                vsDebugTargetInfo.cbSize            = (uint)Marshal.SizeOf(vsDebugTargetInfo);
                vsDebugTargetInfo.dlo = (uint)DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
                vsDebugTargetInfo.dwDebugEngineCount    = 0;
                vsDebugTargetInfo.dwProcessId           = 0;
                vsDebugTargetInfo.dwReserved            = 0;
                vsDebugTargetInfo.fSendToOutputWindow   = 0;
                vsDebugTargetInfo.guidLaunchDebugEngine = CorDebug.s_guidDebugEngine;
                vsDebugTargetInfo.guidPortSupplier      = DebugPortSupplier.s_guidPortSupplier;
                vsDebugTargetInfo.guidProcessLanguage   = Guid.Empty;
                vsDebugTargetInfo.hStdError             = 0;
                vsDebugTargetInfo.hStdInput             = 0;
                vsDebugTargetInfo.hStdOutput            = 0;
                vsDebugTargetInfo.LaunchFlags           = grfLaunch;
                vsDebugTargetInfo.pDebugEngines         = IntPtr.Zero;
                vsDebugTargetInfo.pUnknown = null;

                if (fNoDebug)
                {
                    if (port.IsLocalPort)
                    {
                        processWin32 = new Process();

                        processWin32.StartInfo                  = new ProcessStartInfo();
                        processWin32.StartInfo.FileName         = vsDebugTargetInfo.bstrExe;
                        processWin32.StartInfo.Arguments        = vsDebugTargetInfo.bstrArg;
                        processWin32.StartInfo.WorkingDirectory = vsDebugTargetInfo.bstrCurDir;
                        processWin32.StartInfo.UseShellExecute  = false;
                        processWin32.Start();
                    }
                    else
                    {
                        RebootAndResumeExecution();
                    }
                }
                else
                {
                    byte * bpDebugTargetInfo = stackalloc byte[(int)vsDebugTargetInfo.cbSize];
                    IntPtr ipDebugTargetInfo = (IntPtr)bpDebugTargetInfo;
                    try
                    {
                        IVsDebugger2 iVsDebugger = ( IVsDebugger2 )ServiceProvider.GlobalProvider.GetService(typeof(IVsDebugger));
                        Marshal.StructureToPtr(vsDebugTargetInfo, ipDebugTargetInfo, false);
                        hRes = iVsDebugger.LaunchDebugTargets2(1, ipDebugTargetInfo);
                    }
                    finally
                    {
                        if (ipDebugTargetInfo != null)
                        {
                            Marshal.DestroyStructure(ipDebugTargetInfo, vsDebugTargetInfo.GetType());
                        }
                    }
                }

                return(hRes);
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(String.Format("An exception occurred while attempting to launch the debugger: {0}", ex.Message));
                return(Utility.COM_HResults.E_FAIL);
            }
        }
        int IVsDeployableProjectCfg.StartDeploy(IVsOutputWindowPane pIVsOutputWindowPane, uint dwOptions)
        {
            VsPackage.MessageCentre.ClearDeploymentMsgs();
            VsPackage.MessageCentre.StartProgressMsg(DiagnosticStrings.StartDeploy);
            VsPackage.MessageCentre.DeploymentMsg(string.Format(DiagnosticStrings.LookingUpDevice, this.DeployTransportName));

            int hr;

            m_deployState = new DeployState();
            m_deployState.m_outputWindowPane = pIVsOutputWindowPane;

            foreach (IVsDeployStatusCallback dsc in m_connectionsDeployStatusCallback)
            {
                int iContinue = Utility.Boolean.TRUE;
                dsc.OnStartDeploy(ref iContinue);
                m_deployState.m_deploySuccess = m_deployState.m_deploySuccess && (iContinue == Utility.Boolean.TRUE);
            }

            DebugPort port = GetDebugPort();


            if (port == null)
            {
                SetDeployFailure(string.Format("Invalid device transport setting '{0}', could not find a debug port", this.DeployTransportName));
            }

            //VsPackage.MessageCentre.DeploymentMsg(string.Format(DiagnosticStrings.FoundDevicePort, port.Name, port.PortId, port.PortFilter));

            hr = m_deployState.m_deploySuccess ? Utility.COM_HResults.S_OK : Utility.COM_HResults.E_FAIL;

            if (m_deployState.m_deploySuccess && !port.IsLocalPort)
            {
                m_deployState.m_deployCallbackControl = new System.Windows.Forms.Control();
                m_deployState.m_deployCallbackControl.CreateControl();
                m_deployState.m_threadDeploy = new Thread(delegate()
                {
                    try
                    {
                        Deploy(port);
                    }
                    catch (Exception ex)
                    {
                        SetDeployFailure("An error has occurred: please check your hardware.",
                                         "An error has occurred: please check your hardware.\n"
                                         + ex.Message + "\n"
                                         + "Source: " + ex.Source + "\n"
                                         + "Stack : \n"
                                         + ex.StackTrace + "\n"
                                         );
                    }

                    m_deployState.m_deployCallbackControl.Invoke(new DeployState.EndDeployDelegate(OnEndDeploy));
                });
                m_deployState.m_threadDeploy.Start();
            }
            else
            {
                OnEndDeploy();
            }

            return(hr);
        }
        public VsProjectFlavorCfg(VsProject project, IVsCfg baseCfg)
        {
            m_vsCfg   = baseCfg;
            m_project = project;

            m_innerIVsDebuggableProjectCfg = m_vsCfg as IVsDebuggableProjectCfg;
            m_IVsBuildPropertyStorage      = m_project as IVsBuildPropertyStorage;

            Debug.Assert(m_innerIVsDebuggableProjectCfg != null);

            m_connectionsDeployStatusCallback = new ConnectionPoint.Connections();

            DeployPropertyPort   = new ProjectBuildProperty("DeployTransport", m_IVsBuildPropertyStorage, this, _PersistStorageType.PST_USER_FILE, _PersistStorageType.PST_PROJECT_FILE, DebugPort.NameFromPortFilter(PortFilter.Emulator));
            DeployPropertyDevice = new ProjectBuildProperty("DeployDevice", m_IVsBuildPropertyStorage, this, _PersistStorageType.PST_USER_FILE, _PersistStorageType.PST_PROJECT_FILE);

            GenerateStubsFlag      = new ProjectBuildPropertyBool("MF_GenerateStubs", m_IVsBuildPropertyStorage, this, _PersistStorageType.PST_USER_FILE);
            GenerateStubsRootName  = new ProjectBuildProperty("MF_GenerateStubsRootName", m_IVsBuildPropertyStorage, this, _PersistStorageType.PST_USER_FILE, _PersistStorageType.PST_PROJECT_FILE, "TARGET");
            GenerateStubsDirectory = new ProjectBuildProperty("MF_GenerateStubsDirectory", m_IVsBuildPropertyStorage, this, _PersistStorageType.PST_USER_FILE, _PersistStorageType.PST_PROJECT_FILE, "DIRECTORY");

            try
            {
                ActivateDebugEngine();
            }
            catch (Exception e)
            {
                VsPackage.MessageCentre.InternalErrorMsg(false, String.Format("Unable to register debug engine: {0}", e.Message));
            }
        }