protected internal RuntimeValue_Primitive( Engine eng, WireProtocol.Commands.Debugging_Value handle ) : base( eng, handle )
        {
            Type t;

            switch((RuntimeDataType)handle.m_dt)
            {
            case RuntimeDataType.DATATYPE_BOOLEAN: t = typeof( bool  ); break;
            case RuntimeDataType.DATATYPE_I1     : t = typeof(sbyte  ); break;
            case RuntimeDataType.DATATYPE_U1     : t = typeof( byte  ); break;

            case RuntimeDataType.DATATYPE_CHAR   : t = typeof( char  ); break;
            case RuntimeDataType.DATATYPE_I2     : t = typeof( short ); break;
            case RuntimeDataType.DATATYPE_U2     : t = typeof(ushort ); break;

            case RuntimeDataType.DATATYPE_I4     : t = typeof( int   ); break;
            case RuntimeDataType.DATATYPE_U4     : t = typeof(uint   ); break;
            case RuntimeDataType.DATATYPE_R4     : t = typeof( float ); break;

            case RuntimeDataType.DATATYPE_I8     : t = typeof( long  ); break;
            case RuntimeDataType.DATATYPE_U8     : t = typeof(ulong  ); break;
            case RuntimeDataType.DATATYPE_R8     : t = typeof( double); break;

            default: throw new ArgumentException( String.Format( "Not a primitive: {0}", handle.m_dt ) );
            }

            m_value = System.Runtime.Serialization.FormatterServices.GetUninitializedObject( t );

            m_eng.CreateConverter().Deserialize( m_value, handle.m_builtinValue );
        }
Пример #2
0
 internal EndPoint(Type type, uint id, Engine engine)
 {
     m_type = BinaryFormatter.LookupHash(type);
     m_id = id;
     m_seq = 0;
     m_eng = engine;
 }
Пример #3
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                if (device == null || form == null)
                {
                    return;
                }

                _DBG.Engine engine = device.DbgEngine;

                _DBG.WireProtocol.Commands.Monitor_MemoryMap.Range[] range = engine.MemoryMap();

                if (range != null && range.Length > 0)
                {
                    form.DumpToOutput("Type     Start       Size");
                    form.DumpToOutput("--------------------------------");
                    for (int i = 0; i < range.Length; i++)
                    {
                        string mem = "";
                        switch (range[i].m_flags)
                        {
                        case _DBG.WireProtocol.Commands.Monitor_MemoryMap.c_FLASH:
                            mem = "FLASH";
                            break;

                        case _DBG.WireProtocol.Commands.Monitor_MemoryMap.c_RAM:
                            mem = "RAM";
                            break;
                        }
                        form.DumpToOutput(string.Format("{0,-6} 0x{1:x08}  0x{2:x08}", mem, range[i].m_address, range[i].m_length));
                    }
                }
            }
        private void buttonPing_Click(object sender, EventArgs e)
        {
            bool bWasStarted = EnsureDebuggerConnection();

            _DBG.WireProtocol.Commands.Monitor_Ping.Reply reply;
            reply = m_eng.GetConnectionSource();
            if (reply != null)
            {
                switch (reply.m_source)
                {
                case _DBG.WireProtocol.Commands.Monitor_Ping.c_Ping_Source_TinyCLR:
                    NewText("Connected to TinyCLR\r\n");
                    break;

                case _DBG.WireProtocol.Commands.Monitor_Ping.c_Ping_Source_TinyBooter:
                    NewText("Connected to TinyBooter\r\n");
                    break;

                default:
                    NewText("Connected to unknown source\r\n");
                    break;
                }
            }
            else
            {
                NewText("No connection\r\n");
            }
            if (!bWasStarted)
            {
                m_eng.Stop();
                m_eng = null;
            }
        }
Пример #5
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                if (form == null || device == null)
                {
                    return;
                }

                _DBG.Engine engine = device.DbgEngine;

                _DBG.WireProtocol.Commands.Monitor_DeploymentMap.Reply reply = engine.DeploymentMap();

                if (reply != null)
                {
                    for (int i = 0; i < reply.m_count; i++)
                    {
                        _DBG.WireProtocol.Commands.Monitor_DeploymentMap.DeploymentData dd = reply.m_map[i];

                        form.DumpToOutput("Assembly " + i.ToString());
                        form.DumpToOutput("  Address: " + dd.m_address.ToString());
                        form.DumpToOutput("  Size   : " + dd.m_size.ToString());
                        form.DumpToOutput("  CRC    : " + dd.m_CRC.ToString());
                    }

                    if (reply.m_count == 0)
                    {
                        form.DumpToOutput("No deployed assemblies");
                    }
                }
                else
                {
                    form.DumpToOutput("Command Not Supported by Device");
                }
            }
 protected internal RuntimeValue_Indirect( Engine eng, WireProtocol.Commands.Debugging_Value[] array, int pos ) : base( eng, array[pos] )
 {
     if(++pos < array.Length)
     {
         m_value = Convert( eng, array, pos );
     }
 }
        private void buttonDeployMap_Click(object sender, EventArgs e)
        {
            bool bWasStarted = EnsureDebuggerConnection();

            Microsoft.SPOT.Debugger.WireProtocol.Commands.Monitor_DeploymentMap.Reply deployMap = m_eng.DeploymentMap();
            if (deployMap != null)
            {
                NewText("Deployment Map\r\n");
                for (int i = 0; i < deployMap.m_count; i++)
                {
                    NewText("Assembly " + i.ToString() + ":\r\n");
                    NewText(string.Format("\tAddress: 0x{0:x}\r\n", deployMap.m_map[i].m_address));
                    NewText(string.Format("\tCRC:     0x{0:x}\r\n", deployMap.m_map[i].m_CRC));
                    NewText(string.Format("\tSize:    0x{0:x}\r\n", deployMap.m_map[i].m_size));
                }
                if (deployMap.m_count == 0)
                {
                    NewText("No assemblies in deployment sector\r\n");
                }
            }
            else
            {
                NewText("Nothing in deployment sector - or - deployment map not supported\r\n");
            }
            if (!bWasStarted)
            {
                m_eng.Stop();
                m_eng = null;
            }
        }
Пример #8
0
        private void cLRCapabilitiesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                MFDevice device = ConnectToSelectedDevice();

                if (device != null)
                {
                    _DBG.Engine engine = device.DbgEngine;

                    engine.TryToConnect(0, 100, true, Microsoft.SPOT.Debugger.ConnectionSource.Unknown);

                    Microsoft.SPOT.CLRCapabilities caps = engine.Capabilities;

                    if (caps == null || caps.IsUnknown)
                    {
                        DumpToOutput(Properties.Resources.ErrorNotSupported);
                        DisconnectFromSelectedDevice();
                        return;
                    }

                    Type t = typeof(Microsoft.SPOT.CLRCapabilities);
                    foreach (PropertyInfo pi in t.GetProperties())
                    {
                        object o = pi.GetValue(caps, null);

                        try
                        {
                            if (o is Microsoft.SPOT.CLRCapabilities.LCDCapabilities ||
                                o is Microsoft.SPOT.CLRCapabilities.SoftwareVersionProperties ||
                                o is Microsoft.SPOT.CLRCapabilities.HalSystemInfoProperties ||
                                o is Microsoft.SPOT.CLRCapabilities.ClrInfoProperties ||
                                o is Microsoft.SPOT.CLRCapabilities.SolutionInfoProperties
                                )
                            {
                                foreach (FieldInfo fi in pi.PropertyType.GetFields())
                                {
                                    DumpToOutput(string.Format("{0,-40}{1}", pi.Name + "." + fi.Name + ":", fi.GetValue(o)));
                                }
                            }
                            else
                            {
                                DumpToOutput(string.Format("{0,-40}{1}", pi.Name + ":", o));
                            }
                        }
                        catch
                        {
                            DumpToOutput(Properties.Resources.ErrorNotSupported);
                        }
                    }
                    DisconnectFromSelectedDevice();
                }
            }
            catch
            {
                DumpToOutput(Properties.Resources.ErrorNotSupported);
            }
        }
Пример #9
0
        internal void CreateDeploymentData(BackgroundWorker backgroundWorker, DoWorkEventArgs doWorkEventArgs)
        {
            MFDevice device = doWorkEventArgs.Argument as MFDevice;

            _DBG.Engine eng = device.DbgEngine;

            Commands.Monitor_FlashSectorMap.Reply flashMap = eng.GetFlashSectorMap();

            //find deployment sectors.
            uint addressStart = 0;
            uint cBytes       = 0;

            //First, find out where the deployment sectors are
            for (int iSector = flashMap.m_map.Length - 1; iSector >= 0; iSector--)
            {
                Commands.Monitor_FlashSectorMap.FlashSectorData flashSectorData = flashMap.m_map[iSector];
                if ((flashSectorData.m_flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_DEPLOYMENT)
                {
                    addressStart = flashSectorData.m_address;
                    cBytes      += flashSectorData.m_size;
                }
            }

            if (cBytes == 0)
            {
                throw new ApplicationException("Could not find deployment sectorsd");
            }

            byte[] deploymentData = new byte[cBytes];

            //Read deployment data
            if (!CreateDeploymentReadHelper(backgroundWorker, doWorkEventArgs, eng, addressStart, deploymentData))
            {
                return;
            }

            //create deployment stream
            MemoryStream deploymentStream = new MemoryStream();

            deploymentStream.Write(deploymentData, 0, deploymentData.Length);

            //convert to srec
            MFApplicationDeploymentData data = new MFApplicationDeploymentData();
            MemoryStream streamSrec          = new MemoryStream();

            data.BinaryData = deploymentData;
            deploymentStream.Seek(0, SeekOrigin.Begin);
            new BinToSrec().DoConversion(deploymentStream, streamSrec, addressStart);

            //Get bytes
            long pos = streamSrec.Seek(0, SeekOrigin.Current);

            data.HexData = new byte[(int)pos];
            streamSrec.Seek(0, SeekOrigin.Begin);
            streamSrec.Read(data.HexData, 0, (int)pos);

            doWorkEventArgs.Result = data;
        }
Пример #10
0
        private void DetachFromEngine()
        {
            if (m_engine != null)
            {
                Thread.Sleep(500);

                m_engine.OnMessage -= new MessageEventHandler(OnMessage);
                m_engine.OnCommand -= new CommandEventHandler(OnCommand);
                m_engine.OnNoise   -= new NoiseEventHandler(OnNoise);

                try
                {
                    m_engine.Dispose();
                }
                catch
                {
                    // Depending on when we get called, stopping the engine
                    // throws anything from NullReferenceException, ArgumentNullException, IOException, etc.
                }

                m_engine = null;

                if (m_emulatorProcess != null && !m_emulatorProcess.WaitForExit(4000))
                {
                    if (m_emulatorProcess != null && !m_emulatorProcess.HasExited)
                    {
                        m_emulatorProcess.Kill();
                        m_emulatorProcess = null;
                    }

                    foreach (Process p in Process.GetProcessesByName("Microsoft.SPOT.Emulator.Sample.SampleEmulator"))
                    {
                        p.Kill();
                    }
                }

                GC.Collect();
            }

            ///
            /// Make sure process exit thread dies
            ///
            if (m_waitForProc != null && m_waitForProc.IsAlive)
            {
                try
                {
                    if (!m_waitForProc.Join(1000))
                    {
                        m_waitForProc.Abort();
                    }
                }
                catch
                {
                }
            }
        }
Пример #11
0
        internal bool Disconnect()
        {
            if (m_eng != null)
            {
                m_eng.OnNoise   -= new _DBG.NoiseEventHandler(OnNoiseHandler);
                m_eng.OnMessage -= new _DBG.MessageEventHandler(OnMessage);

                m_eng.Stop();
                m_eng = null;
            }
            return(true);
        }
 protected internal RuntimeValue_ByRef( Engine eng, WireProtocol.Commands.Debugging_Value[] array, int pos ) : base( eng, array, pos )
 {
     if(m_value == null && m_handle.m_arrayref_referenceID != 0)
     {
         m_value = m_eng.GetArrayElement( m_handle.m_arrayref_referenceID, m_handle.m_arrayref_index );
     }
  
     if(m_value == null)
     {
         throw new ArgumentException();
     }            
 }
Пример #13
0
		public static uint AppDomainIdFromCall (Engine engine, WireProtocol.Commands.Debugging_Thread_Stack.Reply.Call call)
		{
			uint appDomainId = CorDebugAppDomain.CAppDomainIdForNoAppDomainSupport;

			if (engine.Capabilities.AppDomains) {
				WireProtocol.Commands.Debugging_Thread_Stack.Reply.CallEx callEx = call as WireProtocol.Commands.Debugging_Thread_Stack.Reply.CallEx;

				appDomainId = callEx.m_appDomainID;
			}

			return appDomainId;
		}
        private void buttonRebootAndStop_Click(object sender, EventArgs e)
        {
            bool bWasStarted = EnsureDebuggerConnection( );

            m_eng.RebootDevice(_DBG.Engine.RebootOption.EnterBootloader);

            if (!bWasStarted)
            {
                m_eng.Stop();
                m_eng = null;
            }
        }
        /// <include file='doc\ConnectionManager.uex' path='docs/doc[@for="Manager.Connect"]/*' />
        public _DBG.Engine Connect(_DBG.PortDefinition pd)
        {
            _DBG.Engine eng = new _DBG.Engine();

            GatewayProxy gwp = new GatewayProxy();
            GatewayStub  gws = m_mgr.Connect(pd, gwp);

            gwp.SetOwner(eng);

            eng.SetController(gwp);

            return(eng);
        }
Пример #16
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                if (form == null || device == null)
                {
                    return;
                }

                _DBG.Engine engine = device.DbgEngine;

                engine.RebootDevice(Microsoft.SPOT.Debugger.Engine.RebootOption.EnterBootloader);

                device.ConnectToTinyBooter();
            }
Пример #17
0
        private void Disconnect()
        {
            if (m_state == ProfilingState.Disconnected)
            {
                return;
            }

            if (m_state == ProfilingState.Connected)
            {
                if (m_session != null)
                {
                    m_session.Disconnect();
                }

                if (m_exporter != null)
                {
                    m_exporter.Close();
                }
            }

            try
            {
                lock (m_engine)
                {
                    m_engine.Stop();
                }
            }
            catch { }  //Depending on when we get called, stopping the engine throws anything from NullReferenceException, ArgumentNullException, IOException, etc.

            m_engine = null;

            if (m_state == ProfilingState.Connected)
            {
                LogText("Disconnected from TinyCLR.");
            }

            KillEmulator();

            ProfilingState oldstate = m_state;

            m_state = ProfilingState.Disconnected;

            EnableUI();

            if (!m_closing && oldstate == ProfilingState.Connected && m_exporter is _PRF.Exporter_CLRProfiler)
            {
                clrProfiler.LoadLogFile(m_exporter.FileName);
                EnableDisableViewMenuItems();
            }
        }
Пример #18
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                _DBG.Engine engine = device.DbgEngine;

                if (device.ConnectToTinyBooter())
                {
                    // ExecuteMemory at address 0 performs an enumerate and execute, which
                    // will clear the bootloader entry flag
                    engine.ExecuteMemory(0);
                }
                else
                {
                    form.DumpToOutput("Unable to connect to TinyBooter!");
                }
            }
Пример #19
0
        void Run()
        {
            m_eng.Silent = true;

            m_eng.Start();

            m_eng.OnNoise   += new _DBG.NoiseEventHandler(OnNoise);
            m_eng.OnMessage += new _DBG.MessageEventHandler(OnMessage);

            Console.WriteLine("####### PRESS RETURN TO EXIT #######");
            Console.ReadLine();

            m_eng.Stop();
            m_eng = null;
        }
        protected internal RuntimeValue_String( Engine eng, WireProtocol.Commands.Debugging_Value handle ) : base( eng, handle )
        {
            byte[] buf = handle.m_builtinValue;

            if(handle.m_bytesInString >= buf.Length)
            {
                if(m_eng.ReadMemory( m_handle.m_charsInString, m_handle.m_bytesInString, out buf ) == false)
                {
                    // Revert to the preview on failure
                    buf = handle.m_builtinValue;
                }
            }

            m_value = WireProtocol.Commands.GetZeroTerminatedString( buf, true );
        }
		protected override void OnRun (DebuggerStartInfo startInfo)
		{
			var mfStartInfo = startInfo as MicroFrameworkDebuggerStartInfo;
			if (mfStartInfo == null)//This should never happen...
				throw new InvalidOperationException ();
			var command = mfStartInfo.MFCommand;
			var portDefinition = ((MicroFrameworkExecutionTarget)command.Target).PortDefinition;
			using (var deployEngine = new Engine (portDefinition)) {
				deployEngine.Start ();

				string newCommand = "/CorDebug_DeployDeviceName:" + portDefinition.PersistName;

				var listOfAseemblies = new ArrayList ();

				//TODO: Check if this is robust enough will "be" and "le" really always be in output folder?
				OutputDirectory = command.OutputDirectory;
				string dir = command.OutputDirectory;
				if (deployEngine.IsTargetBigEndian)
					dir = Path.Combine (dir, "be");
				else
					dir = Path.Combine (dir, "le");

				string[] files = Directory.GetFiles (dir, "*.pe");
				foreach (var file in files) {
					newCommand = "/load:" + file + " " + newCommand;
					using (var fs = new FileStream (file, FileMode.Open)) {
						byte[] data = new byte[fs.Length];
						fs.Read (data, 0, data.Length);
						listOfAseemblies.Add (data);
					}
				}
				startInfo.Command = newCommand;
				deployEngine.Deployment_Execute (listOfAseemblies, false, (str) => OnDebuggerOutput (false, "Deploy: " + str + Environment.NewLine));
				deployEngine.RebootDevice (Engine.RebootOption.RebootClrWaitForDebugger);
			}
			VsPackage.MessageCentre.Session = this;
			try {
				CorDebugProcess process = CorDebugProcess.CreateProcess (new DebugPortSupplier ().FindPort ("USB"), startInfo.Command);
				process.StartDebugging (this, false);
				// StartDebugging() will either get a connected device into a debuggable state and start the dispatch thread, or throw.
			} catch (ProcessExitException) {
				VsPackage.MessageCentre.DeploymentMsg (DiagnosticStrings.InitializeProcessFailedProcessDied);
			} catch (Exception ex) {
				VsPackage.MessageCentre.DeploymentMsg (DiagnosticStrings.InitializeProcessFailed);
				VsPackage.MessageCentre.InternalErrorMsg (false, ex.Message);
			}
		}
        private void buttonCLRCap_Click(object sender, EventArgs e)
        {
            bool bWasStarted = EnsureDebuggerConnection();

            Microsoft.SPOT.CLRCapabilities CLRCapabilities = m_eng.Capabilities;
            NewText("CLR Capabilities\r\n");
            if (CLRCapabilities.FloatingPoint)
            {
                NewText("Floating Point \r\n");
            }

            if (CLRCapabilities.SourceLevelDebugging)
            {
                NewText("Source Level Debugging \r\n");
            }

            if (CLRCapabilities.AppDomains)
            {
                NewText("Application Domain \r\n");
            }

            if (CLRCapabilities.ExceptionFilters)
            {
                NewText("Exception filter\r\n");
            }

            if (CLRCapabilities.IncrementalDeployment)
            {
                NewText("Incremental Deployment \r\n");
            }

            if (CLRCapabilities.SoftReboot)
            {
                NewText("Soft Reboot \r\n");
            }

            NewText("Done\r\n");
            if (!bWasStarted)
            {
                m_eng.Stop();
                m_eng = null;
            }
        }
Пример #23
0
        private bool CreateDeploymentReadHelper(
            BackgroundWorker backgroundWorker,
            DoWorkEventArgs doWorkEventArgs,
            Microsoft.SPOT.Debugger.Engine engine,
            uint address,
            byte[] buf
            )
        {
            uint bytesTotal     = (uint)buf.Length;
            uint bytesRemaining = bytesTotal;
            uint bytesRead      = 0;

            while (bytesRemaining > 0)
            {
                uint   cBytes = System.Math.Min(1024, bytesRemaining);
                byte[] bufT;

                if (!engine.ReadMemory(address, cBytes, out bufT))
                {
                    throw new ApplicationException("Cannot read data");
                }

                bufT.CopyTo(buf, bytesRead);

                address        += cBytes;
                bytesRead      += cBytes;
                bytesRemaining -= cBytes;

                if (backgroundWorker.WorkerReportsProgress)
                {
                    int progress = (int)(100.0 * (double)bytesRead / (double)bytesTotal);
                    backgroundWorker.ReportProgress(progress);
                }

                if (backgroundWorker.CancellationPending)
                {
                    doWorkEventArgs.Cancel = true;
                    return(false);
                }
            }

            return(true);
        }
        void Stop()
        {
            if (m_worker != null)
            {
                m_worker.Abort();
                m_worker.Join();
                m_worker = null;
            }

            if (m_fl != null)
            {
                m_fl.Stop();
                m_fl = null;
            }

            if (m_eng != null)
            {
                m_eng.Stop();
                m_eng = null;
            }
        }
Пример #25
0
        private bool CreateDeploymentReadHelper(
            BackgroundWorker backgroundWorker,
            DoWorkEventArgs doWorkEventArgs,
            Microsoft.SPOT.Debugger.Engine engine,
            ref uint address,
            uint addressStart,
            uint addressEnd,
            uint bytes,
            out byte[] data
            )
        {
            data = new byte[bytes];
            uint iByte = 0;

            while (bytes > 0)
            {
                uint   cBytes = System.Math.Min(1024, bytes);
                byte[] buf;

                if (!engine.ReadMemory(address, cBytes, out buf))
                {
                    throw new ApplicationException("Cannot read data");
                }

                buf.CopyTo(data, iByte);

                address += cBytes;
                iByte   += cBytes;
                bytes   -= cBytes;

                if (backgroundWorker.CancellationPending)
                {
                    doWorkEventArgs.Cancel = true;
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns>Returns the previous conneciton state of the debugger engine</returns>
        private bool EnsureDebuggerConnection()
        {
            if (m_eng == null)
            {
                _DBG.PortDefinition pd = GetSelectedPortDefinition();

                m_eng = new _DBG.Engine(pd);

                m_eng.OnNoise   += new _DBG.NoiseEventHandler(OnNoise);
                m_eng.OnMessage += new _DBG.MessageEventHandler(OnMessage);

                m_eng.Start();

                m_eng.TryToConnect(5, 100);

                return(false);
            }

            // TryToConnect calls GetCLRCapabilities which prevents a bunch of asserts
            m_eng.TryToConnect(5, 100);

            return(true);
        }
Пример #27
0
        public ProfilerSession(_DBG.Engine engine)
        {
            if (engine == null)
            {
                throw new ArgumentNullException();
            }

            m_connected = true;
            m_engine = engine;
            m_engine.OnCommand += new _DBG.CommandEventHandler(OnDeviceCommand);
            m_incomingStream = new _DBG.BitStream(true);

            m_startTime = 0;
            m_lastKnownTime = 0;
            m_currentHeapDump = null;
            m_threadCallStacks = new Dictionary<uint, Stack<uint>>();

            m_liveObjectTable = new List<uint>();

            m_firstPacket = true;

            m_receiverThread = new Thread(WorkerThread);
            m_receiverThread.Start();
        }
Пример #28
0
        public ProfilerSession(_DBG.Engine engine)
        {
            if (engine == null)
            {
                throw new ArgumentNullException();
            }

            m_connected         = true;
            m_engine            = engine;
            m_engine.OnCommand += new _DBG.CommandEventHandler(OnDeviceCommand);
            m_incomingStream    = new _DBG.BitStream(true);

            m_startTime        = 0;
            m_lastKnownTime    = 0;
            m_currentHeapDump  = null;
            m_threadCallStacks = new Dictionary <uint, Stack <uint> >();

            m_liveObjectTable = new List <uint>();

            m_firstPacket = true;

            m_receiverThread = new Thread(WorkerThread);
            m_receiverThread.Start();
        }
Пример #29
0
        private void Disconnect()
        {
            if (m_ah != null)
            {
                m_ah.Stop();
                m_ah.Dispose();

                m_ah = null;
            }

            if (m_eng != null)
            {
                if (m_deviceRunning)
                {
                    m_eng.ResumeExecution();
                }

                m_eng.Stop();

                m_eng = null;
            }

            m_deviceRunning = false;
        }
Пример #30
0
        private void buttonEraseDeployment_Click( object sender, EventArgs e )
        {
            bool bWasStarted = EnsureDebuggerConnection();
            Cursor old = Cursor.Current;
            Cursor = Cursors.WaitCursor;
            buttonEraseDeployment.Text = "Erasing...";
            buttonEraseDeployment.Update();
            NewText( "Erasing Deployment Sector...\r\n" );

            try
            {
                _DBG.WireProtocol.Commands.Monitor_Ping.Reply ping = m_eng.GetConnectionSource();
                if(ping == null) 
                {
                    NewText("Unable to connect to device\r\n");
                    return;
                }
                
                bool fClrConnection = ping.m_source == _DBG.WireProtocol.Commands.Monitor_Ping.c_Ping_Source_TinyCLR;

                if (fClrConnection)
                {
                    m_eng.PauseExecution();
                }

                _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.Reply status = m_eng.GetFlashSectorMap() as _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.Reply;

                if (status == null)
                {
                    NewText( "Erase Deployment may Not be supported on this device build\r\n" );                
                }
                else
                {
                    const uint c_deployFlag = _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_DEPLOYMENT;
                    const uint c_usageMask  = _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK;

                    foreach( _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.FlashSectorData sector in status.m_map)
                    {
                        if (c_deployFlag == (c_usageMask & sector.m_flags))
                        {
                            NewText(string.Format("Erasing sector at 0x{0:x08}\r\n", sector.m_address));
                            m_eng.EraseMemory(sector.m_address, sector.m_size);
                        }
                    }

                    if (fClrConnection)
                    {
                        m_eng.RebootDevice(_DBG.Engine.RebootOption.RebootClrOnly);
                    }
                    NewText("Erase Deployment Successfull");
                }
            }
            catch( Exception ex )
            {
                NewText( "Exception: " + ex.Message + "\r\n" );
            }
            finally
            {
                buttonEraseDeployment.Text = "Erase Deployment";

                Cursor = old;
                if( !bWasStarted )
                {
                    m_eng.Stop();
                    m_eng = null;
                }
            }
        }
Пример #31
0
        SerialDump(string[] args)
        {
            _DBG.PortDefinition pd = null;
            string port            = null;
            uint   baudrate        = 0;

            for (int i = 0; i < args.Length; i++)
            {
                string arg = args[i];

                if (String.Compare(arg, "-dump", true) == 0)
                {
                    m_output = new FileStream(args[++i], FileMode.Create, FileAccess.ReadWrite, FileShare.Read);

                    continue;
                }

                if (String.Compare(arg, "-timestamp", true) == 0)
                {
                    m_fTimestamp = true;

                    continue;
                }

                if (String.Compare(arg, "-usb", true) == 0)
                {
                    m_fUsb = true;

                    continue;
                }

                if (port == null)
                {
                    port = arg; continue;
                }
                if (baudrate == 0)
                {
                    baudrate = UInt32.Parse(arg); continue;
                }
            }

            if (m_fUsb)
            {
                _DBG.PortDefinition[] ports = _DBG.AsyncUsbStream.EnumeratePorts();

                if (port == null)
                {
                    if (ports.Length == 0)
                    {
                        System.Console.WriteLine("No Usb SPOT device is present");

                        throw new ApplicationException();
                    }
                    else if (ports.Length == 1)
                    {
                        pd = ports[0];
                    }
                    else
                    {
                        System.Console.WriteLine("More than one USB SPOT device is present");
                        System.Console.WriteLine("To dump data from a specific device, choose your device from the list below and execute:");
                        System.Console.WriteLine("  serialdump -usb <device> ");
                        System.Console.WriteLine("");

                        //
                        // More than one usb device attached; dump list so user can choose
                        //
                        for (int i = 0; i < ports.Length; ++i)
                        {
                            System.Console.WriteLine("Device " + i + ": " + ports[i].DisplayName);
                        }

                        throw new ApplicationException();
                    }
                }
                else
                {
                    foreach (_DBG.PortDefinition pd2 in ports)
                    {
                        if (port.Equals(pd2.DisplayName))
                        {
                            pd = pd2;
                            break;
                        }
                    }
                }
            }

            if (pd == null)
            {
                if (port == null)
                {
                    port = "COM1";
                }
                if (baudrate == 0)
                {
                    baudrate = 115200;
                }

                pd = _DBG.PortDefinition.CreateInstanceForSerial(port, port, baudrate);
            }

            m_eng = new _DBG.Engine(pd);
        }
Пример #32
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns>Returns the previous conneciton state of the debugger engine</returns>
        private bool EnsureDebuggerConnection()
        {
            if( m_eng == null )
            {
                _DBG.PortDefinition pd = GetSelectedPortDefinition();

                m_eng = new _DBG.Engine( pd );

                m_eng.OnNoise += new _DBG.NoiseEventHandler( OnNoise );
                m_eng.OnMessage += new _DBG.MessageEventHandler( OnMessage );

                m_eng.Start();

                m_eng.TryToConnect(5, 100);

                return false;
            }

            // TryToConnect calls GetCLRCapabilities which prevents a bunch of asserts
            m_eng.TryToConnect(5, 100);

            return true;
        }
Пример #33
0
        private void buttonCLRCap_Click( object sender, EventArgs e )
        {
            bool bWasStarted = EnsureDebuggerConnection();

            Microsoft.SPOT.CLRCapabilities CLRCapabilities = m_eng.Capabilities;
            NewText( "CLR Capabilities\r\n" );
            if (CLRCapabilities.FloatingPoint) 
            {
                NewText( "Floating Point \r\n" ); 
            }

            if (CLRCapabilities.SourceLevelDebugging)
            {
                NewText( "Source Level Debugging \r\n" ); 
            }

            if (CLRCapabilities.AppDomains)
            {
                NewText( "Application Domain \r\n" ); 
            }

            if (CLRCapabilities.ExceptionFilters)
            {
                NewText( "Exception filter\r\n" ); 
            }

            if (CLRCapabilities.IncrementalDeployment)
            {
                NewText( "Incremental Deployment \r\n" ); 
            }

            if (CLRCapabilities.SoftReboot)
            {
                NewText( "Soft Reboot \r\n" ); 
            }

            NewText( "Done\r\n" );                 
            if( !bWasStarted )
            {
                m_eng.Stop();
                m_eng = null;
            }
        }
        static internal object GetObject(Engine eng, EndPoint ep, Type classToRemote)
        {
            uint id = eng.RpcGetUniqueEndpointId();

            EndPoint epLocal = new EndPoint(typeof(EndPointProxy), id, eng);

            EndPointProxy prx = new EndPointProxy(eng, epLocal, ep, classToRemote);

            return prx.GetTransparentProxy();
        }
 public void Dispose()
 {
     try
     {
         if (m_from != null)
         {
             m_from.Deregister();
         }
     }
     catch
     {
     }
     finally
     {
         m_eng = null;
         m_from = null;
         m_to = null;
         m_type = null;
     }
 }
Пример #36
0
 protected internal RuntimeValue_Object( Engine eng, WireProtocol.Commands.Debugging_Value[] array, int pos ) : base( eng, array, pos )
 {
 }
 public EndPoint(Type type, uint id, object server, Type classToRemote, Engine engine)
     : this(type, id, engine)
 {
     m_server = server;
     m_serverClassToRemote = classToRemote;
 }
Пример #38
0
        private void EraseDialog_Load(object sender, EventArgs e)
        {
            _DBG.Engine engine = m_device.DbgEngine;

            _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.Reply reply = engine.GetFlashSectorMap();

            if (reply != null)
            {
                Dictionary <EraseOptions, _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.FlashSectorData> hashBlockType = new Dictionary <EraseOptions, _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.FlashSectorData>();
                Dictionary <EraseOptions, string> usageNameHash = new Dictionary <EraseOptions, string>();

                for (int i = 0; i < reply.m_map.Length; i++)
                {
                    _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.FlashSectorData fsd = reply.m_map[i];

                    string       usage = "";
                    EraseOptions eo    = (EraseOptions)(-1);

                    switch (fsd.m_flags & _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK)
                    {
                    case _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_BOOTSTRAP:
                        //usage = "Bootstrap";
                        break;

                    case _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_CONFIG:
                    case _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_CODE:
                        if (m_device.DbgEngine.ConnectionSource == _DBG.ConnectionSource.TinyBooter)
                        {
                            usage = "Firmware";
                            eo    = EraseOptions.Firmware;
                        }
                        break;

                    case _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_DEPLOYMENT:
                        usage = "Deployment";
                        eo    = EraseOptions.Deployment;
                        break;

                    case _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_UPDATE:
                        usage = "Update Storage";
                        eo    = EraseOptions.UpdateStorage;
                        break;

                    case _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_FS:
                        usage = "File System";
                        eo    = EraseOptions.FileSystem;
                        break;

                    case _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_SIMPLE_B:
                    case _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_SIMPLE_A:
                        usage = "Simple Storage";
                        eo    = EraseOptions.SimpleStorage;
                        break;

                    case _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_STORAGE_A:
                    case _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_STORAGE_B:
                        usage = "User Storage";
                        eo    = EraseOptions.UserStorage;
                        break;
                    }

                    if (eo != (EraseOptions)(-1))
                    {
                        if (hashBlockType.ContainsKey(eo))
                        {
                            _DBG.WireProtocol.Commands.Monitor_FlashSectorMap.FlashSectorData prev = hashBlockType[eo];
                            if (prev.m_address + prev.m_size == fsd.m_address)
                            {
                                prev.m_size      += fsd.m_size;
                                hashBlockType[eo] = prev;
                            }
                        }
                        else
                        {
                            hashBlockType[eo] = fsd;
                            usageNameHash[eo] = usage;
                        }
                    }
                }

                foreach (EraseOptions eo in hashBlockType.Keys)
                {
                    ListViewItem lvi = listViewEraseSectors.Items.Add(new ListViewItem(new string[] { usageNameHash[eo], string.Format("0x{0:X08}", hashBlockType[eo].m_address), string.Format("0x{0:X08}", hashBlockType[eo].m_size) }));
                    lvi.Tag = eo;
                    if (eo != EraseOptions.Firmware)
                    {
                        lvi.Checked = true;
                    }
                }
            }
        }
Пример #39
0
        static internal RuntimeValue Convert( Engine eng, WireProtocol.Commands.Debugging_Value[] array )
        {
            if(array == null || array.Length == 0) return null;

            return Convert( eng, array, 0 );
        }
Пример #40
0
        private void ConnectToDevice(string buildPath, string exePath, ArrayList referenceList)
        {
            TestSystem.IncludesDeviceTest = true;
            PortDefinition port = Utils.GetPort(m_device, m_transport, exePath);

            try
            {
                for (int retry = 0; retry < 3; retry++)
                {
                    m_engine = new Microsoft.SPOT.Debugger.Engine(port);
                    m_engine.StopDebuggerOnConnect = true;
                    m_engine.Start();

                    bool connected = false;

                    connected = m_engine.TryToConnect(200, 500, true, ConnectionSource.TinyCLR);

                    if (connected)
                    {
                        m_engine.PauseExecution();

                        if (!string.Equals(m_transport.ToLower(), "emulator"))
                        {
                            // Deploy the test files to the device.
                            Utils.DeployToDevice(buildPath, referenceList, m_engine, m_transport, m_isDevEnvironment, m_assemblyName);

                            // Connect to the device and execute the deployed test.
                            m_engine.RebootDevice(Microsoft.SPOT.Debugger.Engine.RebootOption.RebootClrWaitForDebugger);

                            // give the device some time to restart (especially for tcp/ip)
                            Thread.Sleep(500);

                            if (m_engine.PortDefinition is PortDefinition_Tcp)
                            {
                                Thread.Sleep(1000);
                            }

                            connected = false;

                            connected = m_engine.TryToConnect(200, 500, true, ConnectionSource.TinyCLR);
                        }


                        if (!connected)
                        {
                            DetachFromEngine();
                            throw new ApplicationException("Reboot Failed");
                        }

                        AttachToProcess();

                        m_engine.ThrowOnCommunicationFailure = true;
                        m_engine.OnMessage += new MessageEventHandler(OnMessage);
                        m_engine.OnCommand += new CommandEventHandler(OnCommand);
                        m_engine.OnNoise   += new NoiseEventHandler(OnNoise);

                        Console.WriteLine("\tExecuting the device test..");
                        m_initialTime = DateTime.Now;
                        m_engine.ResumeExecution();

                        m_deviceDone.WaitOne();
                        break;
                    }
                    else
                    {
                        DetachFromEngine();
                        //throw new ApplicationException("Connection failed");
                    }
                }
            }
            catch (Exception ex)
            {
                DetachFromEngine();
                throw new ApplicationException("Connection failed: " + ex.ToString());
            }
        }
Пример #41
0
        internal void CreateDeploymentData(BackgroundWorker backgroundWorker, DoWorkEventArgs doWorkEventArgs)
        {
            MFDevice device = doWorkEventArgs.Argument as MFDevice;

            _DBG.Engine eng = device.DbgEngine;

            Commands.Monitor_FlashSectorMap.Reply flashMap = eng.GetFlashSectorMap();

            //find deployment sectors.
            MemoryStream deploymentStream = new MemoryStream();

            //this duplicates LoadDeploymentAssemblies logic, as how to find assemblies in the deployment sectors
            int  iSectorStart = -1, iSectorEnd = 0;
            uint address, addressAssemblyStart, addressStart = 0, addressEnd = 0;
            int  iSector;

            //First, find out where the deployment sectors are
            for (iSector = 0; iSector < flashMap.m_map.Length; iSector++)
            {
                Commands.Monitor_FlashSectorMap.FlashSectorData flashSectorData = flashMap.m_map[iSector];
                if ((flashSectorData.m_flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_DEPLOYMENT)
                {
                    if (iSectorStart < 0)
                    {
                        iSectorStart = iSector;
                        addressStart = flashSectorData.m_address;
                    }

                    iSectorEnd = iSector;
                    addressEnd = flashSectorData.m_address + flashSectorData.m_size;
                }
            }

            if (iSectorStart < 0)
            {
                throw new ApplicationException("Could not find deployment sectors");
            }

            address = addressStart;
            iSector = iSectorStart;

            while (true)
            {
                if (backgroundWorker.WorkerReportsProgress)
                {
                    int progress = (int)(100.0 * (double)address / (double)addressEnd);
                    backgroundWorker.ReportProgress(progress);
                }

                //read assembly header
                uint   assemblyHeaderSize  = (uint)Marshal.SizeOf(typeof(CLR_RECORD_ASSEMBLY));
                byte[] assemblyHeaderBytes = null;
                byte[] assemblyDataBytes   = null;

                if (address + assemblyHeaderSize >= addressEnd)
                {
                    break;
                }

                addressAssemblyStart = address;

                if (!CreateDeploymentReadHelper(backgroundWorker, doWorkEventArgs, eng, ref address, addressStart, addressEnd, assemblyHeaderSize, out assemblyHeaderBytes))
                {
                    return;
                }

                GCHandle            gch            = GCHandle.Alloc(assemblyHeaderBytes, GCHandleType.Pinned);
                CLR_RECORD_ASSEMBLY assemblyHeader = (CLR_RECORD_ASSEMBLY)Marshal.PtrToStructure(gch.AddrOfPinnedObject(), typeof(CLR_RECORD_ASSEMBLY));
                gch.Free();

                //check if valid header
                //check marker
                bool fValidAssembly = assemblyHeader.marker == CLR_RECORD_ASSEMBLY.MARKER_ASSEMBLY_V1;

                if (fValidAssembly)
                {
                    //check header crc
                    uint crcHeader = assemblyHeader.headerCRC;

                    //clear headerCRC
                    int headerCRCOffset = 8;
                    int headerCRCSize   = 4;

                    Array.Clear(assemblyHeaderBytes, headerCRCOffset, headerCRCSize);

                    uint crc = _DBG.CRC.ComputeCRC(assemblyHeaderBytes, 0);

                    //Reset headerCRC
                    Array.Copy(BitConverter.GetBytes(crcHeader), 0, assemblyHeaderBytes, headerCRCOffset, headerCRCSize);

                    fValidAssembly = (crcHeader == crc);
                }

                if (fValidAssembly)
                {
                    uint assemblyTotalSize = assemblyHeader.startOfTables[CLR_RECORD_ASSEMBLY.TBL_EndOfAssembly];
                    uint assemblyDataSize  = assemblyTotalSize - assemblyHeaderSize;

                    if (address + assemblyDataSize >= addressEnd)
                    {
                        break;
                    }

                    //read body
                    if (!CreateDeploymentReadHelper(backgroundWorker, doWorkEventArgs, eng, ref address, addressStart, addressEnd, assemblyDataSize, out assemblyDataBytes))
                    {
                        return;
                    }

                    //check if valid body (crc)
                    uint crc = _DBG.CRC.ComputeCRC(assemblyDataBytes, 0);

                    fValidAssembly = (crc == assemblyHeader.assemblyCRC);
                }

                if (fValidAssembly)
                {
                    // add to compact stream
                    deploymentStream.Write(assemblyHeaderBytes, 0, assemblyHeaderBytes.Length);
                    deploymentStream.Write(assemblyDataBytes, 0, assemblyDataBytes.Length);

                    // make sure we are on 4 byte boundary
                    if (0 != (address % sizeof(UInt32)))
                    {
                        byte[] buff = new byte[sizeof(UInt32) - (address % sizeof(UInt32))];
                        deploymentStream.Write(buff, 0, buff.Length);
                        address += sizeof(UInt32) - (address % sizeof(UInt32));
                    }
                }
                else
                {
                    //if no, clear assemblyData, jump to next sector (if in middle of sector), or finish (if at beginning of sector)
                    while (iSector < iSectorEnd)
                    {
                        Commands.Monitor_FlashSectorMap.FlashSectorData flashSectorData = flashMap.m_map[iSector];

                        if (addressAssemblyStart >= flashSectorData.m_address && addressAssemblyStart < flashSectorData.m_address + flashSectorData.m_size)
                        {
                            // jump to next sector
                            address = flashSectorData.m_address + flashSectorData.m_size;

                            System.Diagnostics.Debug.Assert(address == flashMap.m_map[iSector + 1].m_address);

                            break;
                        }

                        iSector++;
                    }
                }
            }

            //Finished reading

            //convert to srec
            MFApplicationDeploymentData data = new MFApplicationDeploymentData();
            long deploymentLength            = deploymentStream.Seek(0, SeekOrigin.Current);

            MemoryStream streamSrec = new MemoryStream();

            deploymentStream.Seek(0, SeekOrigin.Begin);
            data.BinaryData = new byte[(int)deploymentLength];
            deploymentStream.Read(data.BinaryData, 0, (int)deploymentLength);
            deploymentStream.Seek(0, SeekOrigin.Begin);
            new BinToSrec().DoConversion(deploymentStream, streamSrec, flashMap.m_map[iSectorStart].m_address);

            //add zero bytes to all other deployment sectors?

            //Get bytes
            long pos = streamSrec.Seek(0, SeekOrigin.Current);

            data.HexData = new byte[pos];
            streamSrec.Seek(0, SeekOrigin.Begin);
            streamSrec.Read(data.HexData, 0, (int)pos);

            doWorkEventArgs.Result = data;
        }
Пример #42
0
        private void bwConnecter_DoWork(System.Object sender, DoWorkEventArgs e)
        {
            BackgroundConnectorArguments bca = (BackgroundConnectorArguments)e.Argument;

            _DBG.PortDefinition port = bca.connectPort;

            Debug.Assert(m_engine == null);

            e.Result = false;

#if USE_CONNECTION_MANAGER
            m_engine = m_port.DebugPortSupplier.Manager.Connect(port);
#else
            m_engine = new _DBG.Engine(port);
#endif

            m_killEmulator = false;

            lock (m_engine)
            {
                m_engine.StopDebuggerOnConnect = true;
                m_engine.OnCommand            += new _DBG.CommandEventHandler(OnWPCommand);
                m_engine.OnMessage            += new _DBG.MessageEventHandler(OnWPMessage);
                m_engine.Start();

                const int retries   = 50;
                bool      connected = false;
                for (int i = 0; connected == false && i < retries; i++)
                {
                    if (bwConnecter.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                    connected = m_engine.TryToConnect(1, 100, false, _DBG.ConnectionSource.TinyCLR);
                }

                if (connected)
                {
                    if (m_engine.Capabilities.Profiling == false)
                    {
                        throw new ApplicationException("This device is not running a version of TinyCLR that supports profiling.");
                    }

                    //Move IsDeviceInInitializeState(), IsDeviceInExitedState(), GetDeviceState(),EnsureProcessIsInInitializedState() to Debugger.dll?
                    uint executionMode = 0;
                    m_engine.SetExecutionMode(0, 0, out executionMode);
                    if (bca.reboot || (executionMode & _WP.Commands.Debugging_Execution_ChangeConditions.c_State_Mask) != _WP.Commands.Debugging_Execution_ChangeConditions.c_State_Initialize)
                    {
                        m_engine.RebootDevice(_DBG.Engine.RebootOption.RebootClrWaitForDebugger);
                        m_engine.TryToConnect(10, 1000);
                        m_engine.SetExecutionMode(0, 0, out executionMode);
                        Debug.Assert((executionMode & _WP.Commands.Debugging_Execution_ChangeConditions.c_State_Mask) == _WP.Commands.Debugging_Execution_ChangeConditions.c_State_Initialize);
                    }

                    m_engine.ThrowOnCommunicationFailure = true;
                    m_session = new _PRF.ProfilerSession(m_engine);
                    if (m_exporter != null)
                    {
                        m_exporter.Close();
                    }

                    switch (bca.exporter)
                    {
                    case BackgroundConnectorArguments.ExporterType.CLRProfiler:
                        m_exporter = new _PRF.Exporter_CLRProfiler(m_session, bca.outputFileName);
                        break;

#if DEBUG
                    case BackgroundConnectorArguments.ExporterType.OffProf:
                        m_exporter = new _PRF.Exporter_OffProf(m_session, bca.outputFileName);
                        break;
#endif
                    default:
                        throw new ArgumentException("Unsupported export format");
                    }
                    m_session.EnableProfiling();
                    e.Result = true;
                }
            }
            return;
        }
Пример #43
0
        /// <summary>
        /// Attempt to establish a connection with TinyBooter (with reboot if necessary)
        /// </summary>
        /// <returns>true connection was made, false otherwise</returns>
        public bool ConnectToTinyBooter()
        {
            bool ret = false;

            if (m_eng == null)
            {
                _DBG.PortDefinition pd = m_portTinyBooter;

                try
                {
                    if (m_eng == null)
                    {
                        m_eng = new _DBG.Engine(pd);

                        m_eng.OnNoise   += new _DBG.NoiseEventHandler(OnNoiseHandler);
                        m_eng.OnMessage += new _DBG.MessageEventHandler(OnMessage);

                        m_eng.Start();
                        m_eng.TryToConnect(5, 100, true, _DBG.ConnectionSource.Unknown);
                    }
                }
                catch
                {
                }
            }


            if (m_eng != null)
            {
                if (m_eng.ConnectionSource == _DBG.ConnectionSource.TinyBooter)
                {
                    return(true);
                }

                m_eng.RebootDevice(_DBG.Engine.RebootOption.EnterBootloader);

                // tinyBooter is only com port so
                if (m_port is _DBG.PortDefinition_Tcp)
                {
                    Disconnect();

                    m_port = m_portTinyBooter;

                    // digi takes forever to reset
                    if (!Connect(60000, true))
                    {
                        Console.WriteLine(Properties.Resources.ErrorUnableToConnectToTinyBooterSerial);
                        return(false);
                    }
                }
                bool fConnected = false;
                for (int i = 0; i < 40; i++)
                {
                    if (EventCancel.WaitOne(0, false))
                    {
                        throw new MFUserExitException();
                    }

                    if (fConnected = m_eng.TryToConnect(0, 500, true, _DBG.ConnectionSource.Unknown))
                    {
                        _WP.Commands.Monitor_Ping.Reply reply = m_eng.GetConnectionSource();
                        ret = (reply.m_source == _WP.Commands.Monitor_Ping.c_Ping_Source_TinyBooter);

                        break;
                    }
                }
                if (!fConnected)
                {
                    Console.WriteLine(Properties.Resources.ErrorUnableToConnectToTinyBooter);
                }
            }
            return(ret);
        }
Пример #44
0
 protected internal RuntimeValue_Array( Engine eng, WireProtocol.Commands.Debugging_Value handle ) : base( eng, handle )
 {
 }
Пример #45
0
            private bool RebootDevice(Engine.RebootOption option)
            {
                PortFilter[] args = { };
                switch (this.Transport.ToLower())
                {
                    case "emulator":
                        args = new PortFilter[] { PortFilter.Emulator };
                        break;
                    case "serial":
                        args = new PortFilter[] { PortFilter.Serial };
                        break;
                    case "tcpip":
                        args = new PortFilter[] { PortFilter.TcpIp };
                        break;
                    case "usb":
                        args = new PortFilter[] { PortFilter.Usb };
                        break;
                }

                ArrayList list = PortDefinition.Enumerate(args);
                PortDefinition port = null;
                foreach (object prt in list)
                {
                    port = (PortDefinition)prt;
                    if (port.DisplayName.ToLower().Contains(this.Device.ToLower()))
                    {
                        break;
                    }
                    else
                    {
                        port = null;
                    }
                }

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

                using (Engine engine = new Engine(port))
                {
                    engine.Start();
                    bool connect = false;

                    connect = engine.TryToConnect(200, 500, true, ConnectionSource.TinyCLR);

                    if (!connect)
                    {
                        return false;
                    }
                    engine.RebootDevice(option);
                }

                return true;
            }
Пример #46
0
        protected internal RuntimeValue_Reflection( Engine eng, WireProtocol.Commands.Debugging_Value handle ) : base( eng, handle )
        {
            m_rd = (ReflectionDefinition)System.Runtime.Serialization.FormatterServices.GetUninitializedObject( typeof(ReflectionDefinition) );

            m_eng.CreateConverter().Deserialize( m_rd, handle.m_builtinValue );
        }
 static public object GetObject(Engine eng, Type type, uint id, Type classToRemote)
 {
     return GetObject(eng, new EndPoint(type, id, eng), classToRemote);
 }
Пример #48
0
        internal bool Connect( int timeout_ms, bool tryConnect )
        {
            // to use user cancel event, so that cancel button is more responsive
            int retries = timeout_ms/100;
            int loops = 1;
            
            if (retries == 0) retries = 1;

            if (m_portTinyBooter != null && m_port.UniqueId != m_portTinyBooter.UniqueId)
            {
                retries /= 2;
                loops   =  2;
            }
            for (int i = 0; i < loops; i++)
            {
                _DBG.PortDefinition pd = i == 0 ? m_port : m_portTinyBooter;

                if (EventCancel.WaitOne(0, false)) throw new MFUserExitException();

                try
                {
                    if (m_eng == null)
                    {
                        m_eng = new _DBG.Engine(pd);

                        m_eng.OnNoise += new _DBG.NoiseEventHandler(OnNoiseHandler);
                        m_eng.OnMessage += new _DBG.MessageEventHandler(OnMessage);
                    }

                    if (!m_eng.IsConnected)
                    {
                        m_eng.Start();
                        if (tryConnect)
                        {
                            for (int j = retries; j > 0; j-=5)
                            {
                                if (m_eng.TryToConnect(5, 100, true, _DBG.ConnectionSource.Unknown))
                                {
                                    //UNLOCK DEVICE in secure way?
                                    m_eng.UnlockDevice(m_data);
                                    break;
                                }

                                if (EventCancel.WaitOne(0, false)) throw new MFUserExitException();
                            }
                            if (m_eng.IsConnected)
                            {
                                break;
                            }
                            else
                            {
                                Disconnect();
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                catch (MFUserExitException)
                {
                    Disconnect();
                    throw;
                }
                catch
                {
                    Disconnect();
                }
            }
            return (m_eng != null && (!tryConnect || m_eng.IsConnected));
        }
            internal EndPointProxy(Engine eng, EndPoint from, EndPoint to, Type type)
                : base(type)
            {
                from.Register();

                if (from.CheckDestination(to) == false)
                {
                    from.Deregister();

                    throw new ArgumentException("Cannot connect to device EndPoint");
                }

                m_eng = eng;
                m_from = from;
                m_to = to;
                m_type = type;
            }
Пример #50
0
        internal bool Disconnect()
        {
            if (m_eng != null)
            {
                m_eng.OnNoise   -= new _DBG.NoiseEventHandler(OnNoiseHandler);
                m_eng.OnMessage -= new _DBG.MessageEventHandler(OnMessage);

                m_eng.Stop();
                m_eng = null;
            }
            return true;
        }
            internal Request(Engine parent, WireProtocol.OutgoingMessage req, int retries, int timeout, CommandEventHandler callback)
            {
                if (retries < 0)
                {
                    throw new ArgumentException("Value cannot be negative", "retries");
                }

                if (timeout < 1 || timeout > 60 * 60 * 1000)
                {
                    throw new ArgumentException(String.Format("Value out of bounds: {0}", timeout), "timeout");
                }

                m_parent = parent;
                m_req = req;
                m_retries = retries;
                m_timeoutRetry = new TimeSpan(timeout * TimeSpan.TicksPerMillisecond);
                m_timeoutWait = new TimeSpan((retries == 0 ? 1 : 2 * retries) * timeout * TimeSpan.TicksPerMillisecond);
                m_callback = callback;

                if (callback == null)
                {
                    m_event = new ManualResetEvent(false);
                }
            }
Пример #52
0
        /// <summary>
        /// Attempt to establish a connection with TinyBooter (with reboot if necessary)
        /// </summary>
        /// <returns>true connection was made, false otherwise</returns>
        public bool ConnectToTinyBooter()
        {
            bool ret = false;

            if (m_eng == null)
            {
                _DBG.PortDefinition pd = m_portTinyBooter;

                try
                {
                    if (m_eng == null)
                    {
                        m_eng = new _DBG.Engine(pd);

                        m_eng.OnNoise += new _DBG.NoiseEventHandler(OnNoiseHandler);
                        m_eng.OnMessage += new _DBG.MessageEventHandler(OnMessage);

                        m_eng.Start();
                        m_eng.TryToConnect(5, 100, true, _DBG.ConnectionSource.Unknown);
                    }
                }
                catch
                {
                }
            }


            if (m_eng != null)
            {
                if (m_eng.ConnectionSource == _DBG.ConnectionSource.TinyBooter) return true;

                m_eng.RebootDevice(_DBG.Engine.RebootOption.EnterBootloader);

                // tinyBooter is only com port so
                if (m_port is _DBG.PortDefinition_Tcp)
                {
                    Disconnect();

                    m_port = m_portTinyBooter;

                    // digi takes forever to reset
                    if (!Connect(60000, true))
                    {
                        Console.WriteLine(Properties.Resources.ErrorUnableToConnectToTinyBooterSerial);
                        return false;
                    }
                }
                bool fConnected = false;
                for(int i = 0; i<40; i++)
                {
                    if (EventCancel.WaitOne(0, false)) throw new MFUserExitException();

                    if (fConnected = m_eng.TryToConnect(0, 500, true, _DBG.ConnectionSource.Unknown))
                    {
                        _WP.Commands.Monitor_Ping.Reply reply = m_eng.GetConnectionSource();
                        ret = (reply.m_source == _WP.Commands.Monitor_Ping.c_Ping_Source_TinyBooter);

                        break;
                    }
                }
                if(!fConnected)
                {
                    Console.WriteLine(Properties.Resources.ErrorUnableToConnectToTinyBooter);
                }
            }
            return ret;
        }
Пример #53
0
        private void buttonDeployMap_Click( object sender, EventArgs e )
        {
            bool bWasStarted = EnsureDebuggerConnection();

            Microsoft.SPOT.Debugger.WireProtocol.Commands.Monitor_DeploymentMap.Reply deployMap = m_eng.DeploymentMap();
            if( deployMap != null )
            {
                NewText( "Deployment Map\r\n" );
                for(int i=0; i<deployMap.m_count; i++ )
                {
                    NewText( "Assembly " + i.ToString() + ":\r\n" );
                    NewText( string.Format( "\tAddress: 0x{0:x}\r\n", deployMap.m_map[i].m_address ) );
                    NewText( string.Format( "\tCRC:     0x{0:x}\r\n", deployMap.m_map[i].m_CRC ) );
                    NewText( string.Format( "\tSize:    0x{0:x}\r\n", deployMap.m_map[i].m_size ) );
                }
                if( deployMap.m_count == 0 )
                {
                    NewText( "No assemblies in deployment sector\r\n" );
                }
            }
            else
            {
                NewText( "Nothing in deployment sector - or - deployment map not supported\r\n" );
            }
            if( !bWasStarted )
            {
                m_eng.Stop();
                m_eng = null;
            }
        }
Пример #54
0
        internal bool Connect(int timeout_ms, bool tryConnect)
        {
            // to use user cancel event, so that cancel button is more responsive
            int retries = timeout_ms / 100;
            int loops   = 1;

            if (retries == 0)
            {
                retries = 1;
            }

            if (m_portTinyBooter != null && m_port.UniqueId != m_portTinyBooter.UniqueId)
            {
                retries /= 2;
                loops    = 2;
            }
            for (int i = 0; i < loops; i++)
            {
                _DBG.PortDefinition pd = i == 0 ? m_port : m_portTinyBooter;

                if (EventCancel.WaitOne(0, false))
                {
                    throw new MFUserExitException();
                }

                try
                {
                    if (m_eng == null)
                    {
                        m_eng = new _DBG.Engine(pd);

                        m_eng.OnNoise   += new _DBG.NoiseEventHandler(OnNoiseHandler);
                        m_eng.OnMessage += new _DBG.MessageEventHandler(OnMessage);
                    }

                    if (!m_eng.IsConnected)
                    {
                        m_eng.Start();
                        if (tryConnect)
                        {
                            for (int j = retries; j > 0; j -= 5)
                            {
                                if (m_eng.TryToConnect(5, 100, true, _DBG.ConnectionSource.Unknown))
                                {
                                    //UNLOCK DEVICE in secure way?
                                    m_eng.UnlockDevice(m_data);
                                    break;
                                }

                                if (EventCancel.WaitOne(0, false))
                                {
                                    throw new MFUserExitException();
                                }
                            }
                            if (m_eng.IsConnected)
                            {
                                break;
                            }
                            else
                            {
                                Disconnect();
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                catch (MFUserExitException)
                {
                    Disconnect();
                    throw;
                }
                catch
                {
                    Disconnect();
                }
            }
            return(m_eng != null && (!tryConnect || m_eng.IsConnected));
        }
Пример #55
0
        private void buttonRebootAndStop_Click( object sender, EventArgs e )
        {
            bool bWasStarted = EnsureDebuggerConnection( );

            m_eng.RebootDevice(_DBG.Engine.RebootOption.EnterBootloader);

            if(!bWasStarted)
            {
                m_eng.Stop();
                m_eng = null;
            }
        }
Пример #56
0
        // Write the concatonated header and configuration data to the Flash config sector
        private void WriteConfig(string configName, byte[] data, bool staticSize, bool updateConfigSector)
        {
            _DBG.Engine engine = m_device.DbgEngine;

            if (!m_init)
            {
                InitializeConfigData();
            }

            // updating the config
            if (m_cfgHash.ContainsKey(configName))
            {
                ConfigIndexData cid = (ConfigIndexData)m_cfgHash[configName];

                // If old and new data are different sizes
                if (cid.Size != data.Length)
                {
                    // If data comes from a well defined structure, its size cannot vary
                    if (staticSize)
                    {
                        throw new MFInvalidConfigurationDataException();
                    }

                    uint   newNextIndex, oldNextIndex;
                    byte[] temp;
                    int    diff = 0;

                    // Figure out where any following configuration data will start
                    newNextIndex = (uint)(cid.Index + data.Length);
                    while (0 != (newNextIndex % 4))
                    {
                        newNextIndex++;        // Force a 4 byte boundary
                    }

                    // Figure out where any following configuration data previously started
                    oldNextIndex = (uint)(cid.Index + cid.Size);
                    while (0 != (oldNextIndex % 4))
                    {
                        oldNextIndex++;        // Force a 4 byte boundary
                    }


                    diff = (int)newNextIndex - (int)oldNextIndex;           // Find the adjusted difference in size between old and new config data
                    temp = new byte[m_lastCfgIndex + diff];                 // Create a new byte array to contain all the configuration data

                    Array.Copy(m_all_cfg_data, temp, cid.Index);            // Copy all preceding data to new array
                    Array.Copy(data, 0, temp, cid.Index, data.Length);      // Copy new configuration to new array
                    if (oldNextIndex < m_lastCfgIndex)                      // Copy all following data (if it exists) to new array
                    {
                        Array.Copy(m_all_cfg_data, oldNextIndex, temp, newNextIndex, (m_all_cfg_data.Length - oldNextIndex));
                    }

                    // Update the local copy of the configuration list
                    m_all_cfg_data  = temp;
                    m_lastCfgIndex += diff;
                }
                else
                {
                    // Copy the new configuration data on top of the old
                    Array.Copy(data, 0, m_all_cfg_data, cid.Index, data.Length);
                }
            }
            else        // adding a new configuration to the end of the current list
            {
                uint newLastIndex;

                if (m_lastCfgIndex == -1)
                {
                    throw new MFConfigurationSectorOutOfMemoryException();
                }

                // Find the new size of the whole configuration list
                newLastIndex = (uint)(m_lastCfgIndex + data.Length);

                while (0 != (newLastIndex % 4))
                {
                    newLastIndex++;        // Force a 4 byte boundary
                }

                byte[] temp = new byte[m_lastCfgIndex >= m_all_cfg_data.Length ? m_lastCfgIndex + data.Length : m_all_cfg_data.Length];

                Array.Copy(m_all_cfg_data, 0, temp, 0, m_all_cfg_data.Length);
                Array.Copy(data, 0, temp, m_lastCfgIndex, data.Length);

                // Update the local copy of the configuration list
                m_all_cfg_data = temp;
                m_lastCfgIndex = (int)newLastIndex;
            }

            if (!updateConfigSector)
            {
                return;
            }

            // Rewrite entire configuration list to Flash
            if (!engine.EraseMemory(m_cfg_sector.m_address, (uint)m_all_cfg_data.Length))
            {
                throw new MFConfigSectorEraseFailureException();
            }
            if (!engine.WriteMemory(m_cfg_sector.m_address, m_all_cfg_data))
            {
                throw new MFConfigSectorWriteFailureException();
            }

            // Rebuild hash table
            m_cfgHash.Clear();
            uint hal_config_block_size = 0;

            unsafe
            {
                hal_config_block_size = (uint)sizeof(HAL_CONFIG_BLOCK);
            }
            int index = (int)m_StaticConfig.ConfigurationLength;

            byte[]           headerData = new byte[hal_config_block_size];
            HAL_CONFIG_BLOCK cfg_header;

            while (index < m_lastCfgIndex)
            {
                // Read in next configuration header
                Array.Copy(m_all_cfg_data, index, headerData, 0, hal_config_block_size);
                cfg_header = (HAL_CONFIG_BLOCK)UnmarshalData(headerData, typeof(HAL_CONFIG_BLOCK));

                m_cfgHash[cfg_header.DriverNameString] = new ConfigIndexData(index, (int)(cfg_header.Size + hal_config_block_size));

                // Index of next configuration header must lie on a 4 byte boundary
                index += (int)(cfg_header.Size + hal_config_block_size);
                while (0 != (index % 4))
                {
                    index++;        // Force a 4 byte boundary
                }
            }

            // we need to perform signature check regardless of key update, in order for the device to write from ram buffer to flash
            if (!engine.CheckSignature(new byte[TINYBOOTER_KEY_CONFIG.c_KeySignatureLength], 0))
            {
                if (engine.ConnectionSource == Microsoft.SPOT.Debugger.ConnectionSource.TinyBooter)
                {
                    throw new MFConfigSectorWriteFailureException();
                }
            }

            if (engine.ConnectionSource == Microsoft.SPOT.Debugger.ConnectionSource.TinyBooter && m_fRestartClr)
            {
                engine.ExecuteMemory(c_EnumerateAndLaunchAddr);
            }
        }
Пример #57
0
 private void buttonPing_Click(object sender, EventArgs e)
 {
     bool bWasStarted = EnsureDebuggerConnection();
     _DBG.WireProtocol.Commands.Monitor_Ping.Reply reply;
     reply = m_eng.GetConnectionSource();
     if (reply != null)
     {
         switch (reply.m_source)
         {
             case _DBG.WireProtocol.Commands.Monitor_Ping.c_Ping_Source_TinyCLR:
                 NewText("Connected to TinyCLR\r\n");
                 break;
             case _DBG.WireProtocol.Commands.Monitor_Ping.c_Ping_Source_TinyBooter:
                 NewText("Connected to TinyBooter\r\n");
                 break;
             default:
                 NewText("Connected to unknown source\r\n");
                 break;
         }
     }
     else
     {
         NewText("No connection\r\n");
     }
     if (!bWasStarted)
     {
         m_eng.Stop();
         m_eng = null;
     }
 }
Пример #58
0
        void Stop()
        {
            if(m_worker != null)
            {
                m_worker.Abort();
                m_worker.Join ();
                m_worker = null;
            }

            if(m_fl != null)
            {
                m_fl.Stop();
                m_fl = null;
            }

            if(m_eng != null)
            {
                m_eng.Stop();
                m_eng = null;
            }
        }
Пример #59
0
        private void StartOrStop( bool fStart ) 
        {
            bool fButtonState;

            if(fStart)
            {
                if(m_eng != null) return;

                m_blocks      = new ArrayList();
                m_fWait       = checkBoxWait.Checked;
                m_fDisconnect = checkBoxDisconnect.Checked;

                listViewFiles.SelectedIndices.Clear();

                try
                {
                    _DBG.PortDefinition pd = GetSelectedPortDefinition();
                    
                    m_eng = new _DBG.Engine( pd );

                    m_eng.Silent = true;

                    m_eng.OnNoise   += new _DBG.NoiseEventHandler  ( OnNoise   );
                    m_eng.OnMessage += new _DBG.MessageEventHandler( OnMessage );

                    m_eng.Start();

                    if (m_eng.TryToConnect(5, 100))
                    {
                        if (m_fWait)
                        {
                            // if w are talking to the booter, have it to stop and wait for upload
                            // PortBooter will wait to secs no matter what
                            m_eng.RebootDevice(radioButtonPortBooter.Checked ? _DBG.Engine.RebootOption.EnterBootloader : _DBG.Engine.RebootOption.NormalReboot);
                        }
                    }
                    


                    foreach(ListViewItem item in this.listViewFiles.CheckedItems)
                    {
                        m_blocks.Add( item.Tag );
                    }

                    if(m_blocks.Count > 0)
                    {
                        if(radioButtonPortBooter.Checked)
                        {   
                            m_fl = new _DBG.PortBooter( m_eng );

                            m_fl.OnProgress += new _DBG.PortBooter.ProgressEventHandler( this.OnProgress );

                            m_fl.Start();

                            m_worker = new Thread( new ThreadStart( this.UploadWithPortBooter ) );
                        }
                        else
                        {
                            m_worker = new Thread( new ThreadStart( this.UploadWithTinyBooter ) );
                        }

                        m_worker.Start();
                    }

                    buttonAction.Text = "Stop";
                    richTextBox1.Focus();
                }
                catch(Exception ex)
                {
                    MessageBox.Show( ex.Message );
                    return;
                }

                fButtonState = false;
            }
            else
            {
                if(m_eng == null) return;

                Stop();

                buttonAction.Text = "Start";

                fButtonState = true;
            }

            buttonReload         .Enabled = fButtonState;
            buttonRemove         .Enabled = fButtonState;
            buttonRemoveAll      .Enabled = fButtonState;
            buttonBrowse         .Enabled = fButtonState;
            comboBoxPort         .Enabled = fButtonState;
            comboBoxBaud         .Enabled = fButtonState;
            listViewFiles        .Enabled = fButtonState;
        }
Пример #60
0
        bool Process(string[] args)
        {
            string port     = null;
            uint   baudrate = 0;
            bool   fWait    = true;
            int    i;

            if (args.Length == 0)
            {
                Usage();
                return(false);
            }

            for (i = 0; i < args.Length; i++)
            {
                string arg = args[i].ToLower();

                if (arg == "-port")
                {
                    port = args[++i]; continue;
                }
                if (arg == "-baudrate")
                {
                    baudrate = UInt32.Parse(args[++i]); continue;
                }
                if (arg == "-nowait")
                {
                    fWait = false; continue;
                }

                if (arg == "-com1")
                {
                    port = "COM1"; baudrate = 115200; continue;
                }
                if (arg == "-com2")
                {
                    port = "COM2"; baudrate = 115200; continue;
                }

                if (arg == "-write")
                {
                    try
                    {
                        string file = args[++i];

                        Console.WriteLine("Loading {0}...", file);

                        Microsoft.SPOT.Debugger.SRecordFile.Parse(file, m_blocks, null);

                        Console.WriteLine("Loaded.");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("{0}", e.ToString());
                        return(false);
                    }

                    continue;
                }

                if (arg == "-writeandexecute")
                {
                    try
                    {
                        string file = args[++i];

                        Console.WriteLine("Loading {0}...", file);

                        m_entrypoint = Microsoft.SPOT.Debugger.SRecordFile.Parse(file, m_blocks, null);

                        Console.WriteLine("Loaded.");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("{0}", e.ToString());
                        return(false);
                    }

                    continue;
                }

                if (arg == "-entrypoint")
                {
                    m_entrypoint = ParseHex(args[++i]);

                    continue;
                }

                Usage();
                return(false);
            }

            if (port == null || baudrate == 0)
            {
                Console.WriteLine("No serial port specified!");
                return(false);
            }

            m_eng = new _DBG.Engine(new Microsoft.SPOT.Debugger.PortDefinition_Serial(port, port, baudrate));

            m_eng.Silent = true;

            m_eng.OnMessage += new _DBG.MessageEventHandler(OnMessage);

            m_eng.Start();

            if (fWait)
            {
                if (m_eng.TryToConnect(5, 100))
                {
                    m_eng.RebootDevice();
                }
            }

            m_fl = new _DBG.PortBooter(m_eng);

            m_fl.OnProgress += new _DBG.PortBooter.ProgressEventHandler(this.OnProgress);

            m_fl.Start();

            if (fWait)
            {
                m_fl.WaitBanner(Int32.MaxValue, 2000);
            }

            DateTime start = DateTime.Now;

            m_fl.Program(m_blocks);

            Console.WriteLine("Execute: {0}", DateTime.Now - start);

            if (m_entrypoint != 0)
            {
                while (true)
                {
                    m_fl.Execute(m_entrypoint);

                    _DBG.PortBooter.Report r = m_fl.GetReport(2000);

                    if (r != null && r.type == _DBG.PortBooter.Report.State.EntryPoint)
                    {
                        break;
                    }
                }
            }

            m_fl.Stop();

            m_eng.Stop();

            return(true);
        }