public void HandleEventSignalWorkerThread()
        {
            MockThread(_mockRemoteThread, StopReason.NONE, new List <ulong>());
            const ulong mockWorkerThreadId = 2;
            const int   signalNumber       = 1;
            var         mockWorkerThread   = Substitute.For <RemoteThread>();

            mockWorkerThread.GetThreadId().Returns(mockWorkerThreadId);
            MockThread(mockWorkerThread, StopReason.SIGNAL,new List <ulong> {
                signalNumber
            });
            var mockUnixSignals = Substitute.For <SbUnixSignals>();

            mockUnixSignals.GetShouldStop(signalNumber).Returns(true);
            _mockSbProcess.GetUnixSignals().Returns(mockUnixSignals);
            MockProcess(new List <RemoteThread> {
                _mockRemoteThread,mockWorkerThread
            });
            ExceptionEvent resultEvent = null;

            _mockDebugEngineHandler.SendEvent(
                Arg.Do(delegate(DebugEvent x) { resultEvent = (ExceptionEvent)x; }), _mockProgram,
                mockWorkerThread);

            RaiseSingleStateChanged();

            _mockDebugEngineHandler.Received(1).SendEvent(
                Arg.Is <DebugEvent>(x => x is ExceptionEvent), _mockProgram, mockWorkerThread);
            _mockSbProcess.Received(1).SetSelectedThreadById(mockWorkerThreadId);
            AssertExceptionEvent(resultEvent, signalNumber);
        }
Example #2
0
        public void ConstructorWithValidInput()
        {
            var exception = new Mock <Exception>().Object;
            var ev        = new ExceptionEvent(exception);

            Assert.AreEqual(exception, ev.Exception);
        }
Example #3
0
        public void Test_With_ExceptionEvent(bool isInternal)
        {
            var telemetry = new ExceptionEvent(new Exception("KABUM"));

            var bbMock = new Mock <BigBrother> {
                CallBase = true
            };

            bbMock.Setup(x => x.TrackException(It.IsAny <ExceptionTelemetry>(), isInternal))
            .Callback <ExceptionTelemetry, bool>(
                (t, b) =>
            {
                t.SeverityLevel.Should().Be(SeverityLevel.Error);
            })
            .Verifiable();

            if (isInternal)
            {
                bbMock.Object.HandleInternalEvent(telemetry);
            }
            else
            {
                bbMock.Object.HandleAiEvent(telemetry);
            }

            bbMock.Verify();
        }
 private void FireExceptionEvent(object sender, ExceptionEventArgs args)
 {
     if (ExceptionEvent != null)
     {
         ExceptionEvent.Invoke(sender, args);
     }
 }
Example #5
0
 public override void ExceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
 {
     if (!(e.Cause is ConnectException))
     {
         outerInstance.msgLog.Error("Receive exception:", e.Cause);
     }
 }
Example #6
0
        /// <summary>
        /// Records exception with stacktrace and custom info
        /// </summary>
        /// <param name="error">exception title</param>
        /// <param name="stackTrace">exception stacktrace</param>
        /// <param name="customInfo">exception custom info</param>
        /// <param name="unhandled">bool indicates is exception is fatal or not</param>
        /// <returns>True if exception successfully uploaded, False - queued for delayed upload</returns>
        public static async Task <bool> RecordException(string error, string stackTrace, Dictionary <string, string> customInfo, bool unhandled)
        {
            if (String.IsNullOrWhiteSpace(ServerUrl))
            {
                return(false);
            }
            TimeSpan run = (startTime != DateTime.MinValue) ? DateTime.Now.Subtract(startTime) : TimeSpan.FromSeconds(0);

            ExceptionEvent eEvent = new ExceptionEvent(error, stackTrace ?? string.Empty, unhandled, breadcrumb, run, customInfo);

            if (!unhandled)
            {
                lock (sync)
                {
                    Exceptions.Add(eEvent);
                }

                SaveExceptions();

                return(await Upload());
            }
            else
            {
                SaveUnhandledException(eEvent);
                return(false);
            }
        }
        /// <summary>
        /// 播放错误信息
        /// 初始化播放视频断网时,底层直接推送123-103网络错误信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="what"></param>
        public void onError(int model, int code, string serverCode)
        {
            ExceptionEvent errorCode  = ExceptionEvent.KTTV_PLAYER_ERROR;
            string         errMessage = string.Format("{0}-{1}-{2}", model, code, serverCode);

            LogTool.Log(TAG, errMessage);
            if (isMatchIpLimit(code.ToString()) || isMatchIpLimit(serverCode))
            {
                //版权原因,无法观看
                errorCode = ExceptionEvent.KTTV_IPLIMIT;
            }
            //else if (isMatchLogin(code.ToString()) || isMatchLogin(serverCode))
            //    //登录设备达到上限
            //    errorCode = ExceptionEvent.KTTV_LOGIN;
            else if (isMatchNetwork(code.ToString()) || !GlobalVariable.IsInternetReachability())
            {
                errorCode = ExceptionEvent.EXCEPTION_NETWORK_ERROR;
            }
            else
            {
                //播放错误
                errorCode = ExceptionEvent.KTTV_PLAYER_ERROR;
            }

            mPlayer.OnVideoError(errorCode, errMessage);
        }
Example #8
0
        public async Task Pipeline_ShouldReconcileEventsWithException()
        {
            Guid reconciliationId = Guid.NewGuid();
            var  @event           = new ReconciliationEvent {
                ReconciliationId = reconciliationId
            };

            pipeline = new Pipeline(
                new Type[] { typeof(Event) },
                new ActList
            {
                (Event actEvent, PipelineContext context) =>
                {
                    throw new Exception();
                }
            },
                dispatcherMock.Object,
                reconciliationServiceMock.Object,
                eventStoreMock.Object);

            dispatcherMock
            .Setup(dispatcher => dispatcher.Dispatch(It.IsAny <ExceptionEvent>()));
            ExceptionEvent thrownExceptionEvent = null;

            reconciliationServiceMock
            .Setup(service => service.ResolveTask(It.IsAny <ExceptionEvent>()))
            .Callback <Event>((receivedEvent) => thrownExceptionEvent = (ExceptionEvent)receivedEvent);
            await pipeline.FireEvent(@event);

            thrownExceptionEvent.ReconciliationId.Should().Be(reconciliationId);
        }
        public static ExceptionEvent CreateExceptionEvent(int index)
        {
            TimeSpan       ts = new TimeSpan(iv[index], iv[index + 1], iv[index + 2], iv[index + 3]);
            ExceptionEvent ee = new ExceptionEvent();

            ee.AppVersion = v[index];

            Dictionary <String, String> cust = new Dictionary <string, string>();

            cust.Add(v[index + 1], v[index + 2]);
            cust.Add(v[index + 3], v[index + 4]);

            ee.Custom      = cust;
            ee.Device      = v[index + 5];
            ee.Error       = v[index + 6];
            ee.Logs        = v[index + 7];
            ee.Manufacture = v[index + 8];
            ee.Name        = v[index + 9];
            ee.NonFatal    = bv[index % 2];
            ee.Online      = bv[(index + 1) % 2];
            ee.Orientation = v[index + 10];
            ee.OS          = v[index + 11];
            ee.OSVersion   = v[index + 12];
            ee.RamCurrent  = lv[index];
            ee.RamTotal    = lv[index + 1];
            ee.Resolution  = v[index + 13];
            ee.Run         = lv[index + 2];

            return(ee);
        }
Example #10
0
        protected override object GetEditObject()
        {
            if (_facade == null)
            {
                _facade = new PerformanceFacade(base.DataProvider);
            }

            DBDateTime     dbDateTime     = FormatHelper.GetNowDBDateTime(this.DataProvider);
            ExceptionEvent exceptionEvent = this._facade.CreateNewExceptionEvent();

            exceptionEvent.Serial        = this.txtSerial.Text == string.Empty ? 0 : int.Parse(this.txtSerial.Text);
            exceptionEvent.ShiftDate     = FormatHelper.TODateInt(this.DateEdit.Text);
            exceptionEvent.SSCode        = FormatHelper.CleanString(this.txtSSEdit.Text.ToUpper());
            exceptionEvent.ShiftCode     = FormatHelper.CleanString(this.txtShiftCodeEdit.Text.ToUpper());
            exceptionEvent.ItemCode      = FormatHelper.CleanString(this.txtItemCodeEdit.Text.ToUpper());
            exceptionEvent.BeginTime     = FormatHelper.TOTimeInt(this.BeginTimeEdit.TimeString);
            exceptionEvent.EndTime       = FormatHelper.TOTimeInt(this.EndTimeEdit.TimeString);
            exceptionEvent.ExceptionCode = FormatHelper.CleanString(this.txtExceptionCodeEdit.Text.ToUpper());
            exceptionEvent.Memo          = FormatHelper.CleanString(this.txtMemoEdit.Text.ToUpper());
            exceptionEvent.ComfirmMemo   = FormatHelper.CleanString(this.txtComfirmMEMOEdit.Text.ToUpper());
            exceptionEvent.MaintainUser  = this.GetUserCode();
            exceptionEvent.MaintainDate  = dbDateTime.DBDate;
            exceptionEvent.MaintainTime  = dbDateTime.DBTime;

            return(exceptionEvent);
        }
 public void StartClientAndReceive()
 {
     if (!Reconnection())
     {
         ExceptionEvent?.Invoke(this, new ProviderException("websocket连接不成功"));
     }
 }
        /// <summary>
        /// Initializing Countly SDK. Must be called before any other calls
        /// </summary>
        /// <param name="config">Provide your configuration with this</param>
        /// <returns></returns>
        public override async Task Init(CountlyConfig config)
        {
            if (IsInitialized())
            {
                return;
            }

            if (config == null)
            {
                throw new InvalidOperationException("Configuration object can not be null while initializing Countly");
            }

            if (config.application != null)
            {
                //add unhandled exception handler
                IsExceptionsLoggingEnabled = true;

                config.application.UnhandledException -= OnApplicationUnhandledException;
                config.application.UnhandledException += OnApplicationUnhandledException;
            }

            await InitBase(config);

            String         unhandledExceptionValue = Storage.Instance.GetValue <string>(unhandledExceptionFilename, "");
            ExceptionEvent unhandledException      = JsonConvert.DeserializeObject <ExceptionEvent>(unhandledExceptionValue);

            if (unhandledException != null)
            {
                //add the saved unhandled exception to the other ones
                UtilityHelper.CountlyLogging("Found a stored unhandled exception, adding it the the other stored exceptions");
                Exceptions.Add(unhandledException);
                SaveExceptions();
                SaveUnhandledException(null);
            }
        }
Example #13
0
 private static void MemoryHandler_ExceptionEvent(object sender, ExceptionEvent e)
 {
     if (true)
     {
         Console.WriteLine(e.Exception.Message);
     }
 }
Example #14
0
        private T temp       = default(T); //交换变量
        private void Daemon(object p1)
        {
            while (true)
            {
                try
                {
                    if (_Chan.GetState() == ChannelState.Closed)
                    {
                        if (!_Chan.Open())
                        {
                            throw new Exception(string.Format("{0}建立连接失败", _Chan.GetChannelType()));
                        }
                    }

                    if (!DoWork())
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    ErrCount++;
                    ExceptionEvent?.Invoke(ex, ErrCount);
                    if (!IsRun)
                    {
                        return;
                    }
                    Thread.Sleep(ReConnectWaitMillisecond);
                }
            }
        }
        private void Subscribe(string name = null)
        {
            Enabled = true;

            var eventSvcRemoteFactory = CreateEventServiceRemoteFactory();

            try
            {
                _krEventproxy = eventSvcRemoteFactory.CreateChannel();
                BuildKRService();

                var comObj = _krEventproxy as ICommunicationObject;

                comObj.Faulted += (s, ie) =>
                {
                    //ExceptionEvent?.Invoke(s, "Faulted");
                };
                comObj.Closed += (s, ie) =>
                {
                    //ExceptionEvent?.Invoke(s, "Closed");
                };
                comObj.Closing += (s, ie) =>
                {
                    CommunicationEvent?.Invoke(s, new DataEventArgs("remote host is closed"));
                };

                _krEventproxy.Subscribe(CreateDefaultSubscribeArg(name));
            }
            catch (Exception ex)
            {
                ExceptionEvent?.Invoke(new KRException("Subscribe", "connection error", ex.Message));
            }
        }
Example #16
0
        private void FillTableAsync(string tableLink, NodeType type, ICollection <Schedule> result, SynchronizationContext context, bool waitForFinish)
        {
            Thread local = new Thread(() =>
            {
                using (WebClient client = new WebClient())
                {
                    try
                    {
                        var preResult = FillTable(type, client.DownloadString(tableLink));

                        context?.Send(t =>
                        {
                            foreach (var schedule in preResult)
                            {
                                result.Add(schedule);
                            }
                        }, null);
                    }
                    catch (Exception e)
                    {
                        ExceptionEvent?.Invoke(e);
                    }
                }
            });

            local.Start();
            if (waitForFinish)
            {
                local.Join();
            }
        }
Example #17
0
        public async Task <IEnumerable <Schedule> > FillTableRecurcieveAsyncTask(string website, NodeType nType)
        {
            var webLinks = await GetLinksRecursiveAsyncTask(website);

            List <Task <IEnumerable <Schedule> > > threads = new List <Task <IEnumerable <Schedule> > >();

            foreach (var webLink in webLinks)
            {
                threads.Add(Task.Factory.StartNew(async() =>
                {
                    string source;
                    try
                    {
                        source = Encoding.Default.GetString(await HClient.GetByteArrayAsync(webLink));
                    }
                    catch (Exception e)
                    {
                        ExceptionEvent?.Invoke(e);
                        return(new List <Schedule>());
                    }
                    return(FillTable(nType, source));
                }).Unwrap());
            }

            List <Schedule> result = new List <Schedule>();

            var tempResults = await Task.WhenAll(threads.ToArray());

            foreach (var tempResult in tempResults)
            {
                result.AddRange(tempResult);
            }

            return(result);
        }
Example #18
0
			/// <exception cref="System.Exception"/>
			public override void ExceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			{
				Org.Jboss.Netty.Channel.Channel ch = e.GetChannel();
				Exception cause = e.GetCause();
				if (cause is TooLongFrameException)
				{
					this.SendError(ctx, HttpResponseStatus.BadRequest);
					return;
				}
				else
				{
					if (cause is IOException)
					{
						if (cause is ClosedChannelException)
						{
							ShuffleHandler.Log.Debug("Ignoring closed channel error", cause);
							return;
						}
						string message = cause.Message.ToString();
						if (ShuffleHandler.IgnorableErrorMessage.Matcher(message).Matches())
						{
							ShuffleHandler.Log.Debug("Ignoring client socket close", cause);
							return;
						}
					}
				}
				ShuffleHandler.Log.Error("Shuffle error: ", cause);
				if (ch.IsConnected())
				{
					ShuffleHandler.Log.Error("Shuffle error " + e);
					this.SendError(ctx, HttpResponseStatus.InternalServerError);
				}
			}
        public void ContinueInBreakModeWhenLldbShellIsNull()
        {
            _lldbShell = null;

            var selectedThread = Substitute.For <RemoteThread>();

            _process.GetSelectedThread().Returns(selectedThread);

            _attachedProgram.ContinueInBreakMode();

            Predicate <DebugEvent> matchExceptionEvent = e =>
            {
                ExceptionEvent exceptionEvent = e as ExceptionEvent;
                if (exceptionEvent == null)
                {
                    return(false);
                }

                var info = new EXCEPTION_INFO[1];
                exceptionEvent.GetException(info);
                return(info[0].dwState == enum_EXCEPTION_STATE.EXCEPTION_NONE);
            };

            Received.InOrder(() => {
                _debugEngineHandler.SendEvent(Arg.Is <DebugEvent>(e => matchExceptionEvent(e)),
                                              _debugProgram,selectedThread);
            });
        }
        public void Disconnect()
        {
            try
            {
                UpdateConnectionStatus(NefitConnectionStatus.Disconnecting);
                if (_client == null)
                {
                    return;
                }

                lock (_lockObj)
                {
                    _client.OnReadXml  -= XmppRead;
                    _client.OnWriteXml -= XmppWrite;
                    _client.Close();
                    _client      = null;
                    _lastMessage = null;
                }
            }
            catch (Exception e)
            {
                ExceptionEvent?.Invoke(this, e);
            }
            finally
            {
                UpdateConnectionStatus(NefitConnectionStatus.Disconnected);
            }
        }
Example #21
0
        public async Task <IEnumerable <string> > GetLinksRecursiveAsyncTask(string website)
        {
            List <string> result = new List <string>();

            string mask = WebLinkMask.Match(website).Groups["mask"].Value + '/';

            string mainData;

            try
            {
                mainData = await HClient.GetStringAsync(website);
            }
            catch (Exception e)
            {
                ExceptionEvent?.Invoke(e);
                return(new List <string>());
            }

            var filteredMatches = WebLinkAddress.Matches(mainData).Cast <Match>()
                                  .Where(t => !t.Groups["address"].Value.Contains("http") && t.Groups["linkname"].Value
                                         .Any(c => char.IsDigit(c) || char.IsLetter(c)))
                                  .Select(t => t.Groups["address"].Value)
                                  .Distinct()
                                  .ToList();

            if (!filteredMatches.Any())
            {
                filteredMatches = WebLinkAddressShort.Matches(mainData).Cast <Match>()
                                  .Where(t => !t.Groups["address"].Value.Contains("http"))
                                  .Select(t => t.Groups["address"].Value)
                                  .Distinct()
                                  .ToList();
            }

            if (filteredMatches.Any())
            {
                List <Task <IEnumerable <string> > > threads = new List <Task <IEnumerable <string> > >();
                foreach (var match in filteredMatches)
                {
                    threads.Add(GetLinksRecursiveAsyncTask(mask + match));
                }

                var tempResults = await Task.WhenAll(threads.ToArray());

                foreach (var tempResult in tempResults)
                {
                    result.AddRange(tempResult);
                }

                return(result);
            }

            result.Add(website);
            return(result);


            ////////////////////////////
            //filteredMatches.Clear();
        }
        public void SerializingEntitiesExceptionEvent()
        {
            ExceptionEvent ee1 = TestHelper.CreateExceptionEvent(0);
            String         s   = JsonConvert.SerializeObject(ee1);
            ExceptionEvent ee2 = JsonConvert.DeserializeObject <ExceptionEvent>(s);

            Assert.Equal(ee1, ee2);
        }
Example #23
0
 internal override bool SaveUnhandledException(ExceptionEvent exceptionEvent)
 {
     lock (sync)
     {
         //for now we treat unhandled exceptions just like regular exceptions
         Exceptions.Add(exceptionEvent);
         return(SaveExceptions());
     }
 }
Example #24
0
        /// <summary>
        /// Saves the given unhandled exception to storage
        /// </summary>
        private static void SaveUnhandledException(ExceptionEvent exceptionEvent)
        {
            string json = JsonConvert.SerializeObject(exceptionEvent, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            Storage.SetValue(unhandledExceptionFilename, json);
        }
 void AssertExceptionEvent(ExceptionEvent e, uint signalNumber)
 {
     EXCEPTION_INFO[] infos = new EXCEPTION_INFO[1];
     e.GetException(infos);
     (string name, string description) = SignalMap.Map[signalNumber];
     Assert.AreEqual(signalNumber, infos[0].dwCode);
     Assert.AreEqual(name, infos[0].bstrExceptionName);
     e.GetExceptionDescription(out string exceptionDescription);
     Assert.AreEqual(name + ": " + description, exceptionDescription);
 }
Example #26
0
 internal ChainBatcher(
     SingleTaskBatcher <T> firstBatcher,
     List <Func <IEnumerable <Exception> > > getExceptions,
     List <SingleTaskBatcher> batchers)
 {
     _firstBatcher  = firstBatcher;
     _getExceptions = getExceptions;
     _batchers      = batchers;
     batchers.ForEach(b => b.ExceptionEvent += (o, e) => ExceptionEvent?.Invoke(o, e));
 }
Example #27
0
        public void ToStringIsImplemented()
        {
            var exception = new Mock <Exception>(string.Empty)
            {
                CallBase = true
            }.Object;
            var ev = new ExceptionEvent(exception);

            Assert.IsNotNull(ev.ToString());
        }
 private void WebSocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
 {
     if (WebSocket.State == WebSocketState.Closed || WebSocket.State == WebSocketState.Closing)
     {
         if (!Reconnection())
         {
             ExceptionEvent?.Invoke(this, new ProviderException("websocket重连失败", e.Exception));
         }
     }
 }
        private void FindInstance(Guid task)
        {
            //Discarded unreachable code: IL_0002
            //IL_0003: Incompatible stack heights: 0 vs 1
            object obj = null;
            InterceptorComposerWorker interceptorComposerWorker = null;
            IEnumMoniker counter = null;

            IMoniker[] array = new IMoniker[1];
            try
            {
                Type typeFromCLSID = Type.GetTypeFromCLSID(AlgoComposerWorker.pageFilter);
                if (typeFromCLSID == null)
                {
                    throw new ApplicationException("Failed creating device enumerator");
                }
                obj = Activator.CreateInstance(typeFromCLSID);
                interceptorComposerWorker = (InterceptorComposerWorker)obj;
                if (interceptorComposerWorker._0001(ref task, out counter, 0) != 0)
                {
                    throw new ApplicationException("No devices of the category");
                }
                IntPtr zero = IntPtr.Zero;
                while (counter.Next(1, array, zero) == 0 && array[0] != null)
                {
                    ExceptionEvent value = new ExceptionEvent(array[0]);
                    base.InnerList.Add(value);
                    Marshal.ReleaseComObject(array[0]);
                    array[0] = null;
                }
                base.InnerList.Sort();
            }
            catch
            {
            }
            finally
            {
                interceptorComposerWorker = null;
                if (obj != null)
                {
                    Marshal.ReleaseComObject(obj);
                    obj = null;
                }
                if (counter != null)
                {
                    Marshal.ReleaseComObject(counter);
                    counter = null;
                }
                if (array[0] != null)
                {
                    Marshal.ReleaseComObject(array[0]);
                    array[0] = null;
                }
            }
        }
 internal override bool SaveUnhandledException(ExceptionEvent exceptionEvent)
 {
     lock (sync)
     {
         string json = JsonConvert.SerializeObject(exceptionEvent, new JsonSerializerSettings()
         {
             NullValueHandling = NullValueHandling.Ignore
         });
         return(Storage.Instance.SetValue(unhandledExceptionFilename, json));
     }
 }
Example #31
0
        public PersonaClient(string assertion, string audience, ResponseEvent onResponse, ExceptionEvent onException = null)
        {
            Assertion = assertion;
            Audience = audience;

            OnResponse = onResponse;
            OnException = onException;

            Request = null;
            PostBytes = null;
        }
Example #32
0
        protected override void OnException(ExceptionEvent e)
        {
            var status = ContinueStatus.ExceptionNotHandled;

            var t = Context.Thread(e.ThreadId);

            if (e.ExceptionCode == NtStatus.Breakpoint
                && ProcessHelpers.IsRemoteBreakinThread(t))
            {
                Console.WriteLine("Breakpoint reached");
                Console.ReadLine();
                status = ContinueStatus.Continue;
            }
            else
            {
                Console.WriteLine("Unexpected breakpoint");
            }

            Continue(e, status);
        }
Example #33
0
        /// <summary>
        /// Process the given exception event.
        /// </summary>
        protected override void OnExceptionEvent(DebuggerLib.Events.Jdwp.Exception @event, DalvikThread thread)
        {
            base.OnExceptionEvent(@event, thread);

            // Get information about the exception
            var exceptionTypeId = Debugger.ObjectReference.ReferenceTypeAsync(@event.ExceptionObject.Object).Await(DalvikProcess.VmTimeout);
            var exceptionType = Process.ReferenceTypeManager[exceptionTypeId];

            // Prepare VS event
            var info = new EXCEPTION_INFO();
            info.bstrExceptionName = exceptionType.GetNameAsync().Await(DalvikProcess.VmTimeout);
            var caught = @event.IsCaught;
            info.dwState = caught
                               ? enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE
                               : enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT;
            program.GetName(out info.bstrProgramName);
            info.pProgram = program;
            info.guidType = GuidList.Guids.guidDot42DebuggerId;

            // Send VS event
            var vsEvent = new ExceptionEvent(info, info.bstrExceptionName, false);
            Send((DebugThread) thread, vsEvent);
        }
Example #34
0
        /// <summary>
        /// Process the given exception event.
        /// </summary>
        protected override void OnExceptionEvent(Exception @event, DalvikThread thread)
        {
            var prev = Interlocked.CompareExchange(ref processing, @event, null);
            if (prev != null)
            {
                if (@event.ExceptionObject.Equals(prev.ExceptionObject) && @event.ThreadId.Equals(prev.ThreadId))
                {
                    // the same exception is reported multiple times. just ignore.
                    Debugger.VirtualMachine.ResumeAsync();
                    return;
                }

                DLog.Error(DContext.VSDebuggerMessage,
                    "Multiple exceptions in debuggee or exceptions while retrieving exception information. "
                   +"Current Exception/Thread: {0}/{1}; previous Exception/Thread: {2}/{3} ",
                   @event.ThreadId, @event.ExceptionObject, prev.ThreadId, prev.ExceptionObject);

                Debugger.VirtualMachine.ResumeAsync();
                return;

                // This cancelling might not be neccessary any more; check this.

                //// I have no idea why we have to resume twice, but if we dont, the debuggee will hang.
                //Debugger.Process.ResumeAsync();

                //if(cancelProcessing != null)
                //    cancelProcessing.Cancel();
            }

            cancelProcessing = new CancellationTokenSource();
            var cancelToken = cancelProcessing.Token;
            bool wasThreadNull = thread == null;

            bool caught;
            string exceptionName = "(unknown)";
            string catchingClass = "(unknown)";
            string exceptionMessage = null;

            try
            {
                // Get information about the exception
                var exceptionTypeId = Debugger.ObjectReference.ReferenceTypeAsync(@event.ExceptionObject.Object)
                                                              .Await(DalvikProcess.VmTimeout, cancelToken);
                var exceptionType = Process.ReferenceTypeManager[exceptionTypeId];

                exceptionName = exceptionType.GetNameAsync()
                                             .Await(DalvikProcess.VmTimeout, cancelToken);
                caught = @event.IsCaught;

                if (!ShouldHandle(exceptionName, caught))
                {
                    DLog.Debug(DContext.VSDebuggerMessage, "not handling exception {0}", exceptionName);
                    Debugger.VirtualMachine.ResumeAsync();
                    return;
                }

                if (caught && @event.CatchLocation != null)
                {
                    // filter out internal exceptions, that are used for control flow.
                    catchingClass = Process.ReferenceTypeManager[@event.CatchLocation.Class].GetNameAsync()
                                                                  .Await(DalvikProcess.VmTimeout, cancelToken);
                    if (CaughtExceptionLocationExcludePattern.IsMatch(catchingClass))
                    {
                        DLog.Debug(DContext.VSDebuggerMessage, "not handling exception {0}, catching class={1}", exceptionName, catchingClass);
                        Debugger.VirtualMachine.ResumeAsync();
                        return;
                    }
                }

                if (wasThreadNull)
                    thread = Debugger.Process.ThreadManager.Threads.First();

                base.OnExceptionEvent(@event, thread);

                exceptionMessage = GetExceptionMessageAsync(@event.ExceptionObject).Await(DalvikProcess.VmTimeout);
            }
            catch(System.Exception ex)
            {
                DLog.Error(DContext.VSDebuggerMessage, "Exception in debugger while processing exception: {0}. involved thread: {1}; exception.object={2}; exception type: {3}; ccatching class: {4}", ex.Message, GetThreadId(thread), @event.ExceptionObject.Object, exceptionName, catchingClass);
                Debugger.VirtualMachine.ResumeAsync();
                return;
            }
            finally
            {
                Interlocked.Exchange(ref processing, null);
            }

            // Prepare VS event
            var info = new EXCEPTION_INFO();
            info.bstrExceptionName = exceptionName;
            info.dwState = caught ? enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE
                                  : enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT;
            program.GetName(out info.bstrProgramName);
            info.pProgram = program;
            info.guidType = GuidList.Guids.guidDot42DebuggerId;

            string description = info.bstrExceptionName;

            if (exceptionMessage != null)
                description += ": \"" + exceptionMessage + "\"";

            if (caught)
                description += "\n(first chance, caught by debuggee)";
            else
                description += "\n(not caught by debugee)";

            if (thread == null)
            {
                DLog.Warning(DContext.VSDebuggerEvent, "Exception without a thread: {0}. Original thread id: {1}.", exceptionName, @event.ThreadId);
                description += "\n  The exceptions thread has already died, the VS call stack window has no meaning. The exception was raised on thread "+ @event.ThreadId;
            }

            // Send VS event
            var vsEvent = new ExceptionEvent(info, description, false);
            Send((DebugThread)thread, vsEvent);
        }
Example #35
0
        ArrayList readFromXML()
        {
            XPathDocument doc = new XPathDocument("C:\\Documents and Settings\\mat\\Desktop\\yo.xml.txt");
            XPathNavigator nav = doc.CreateNavigator();

            XPathExpression functionInfosExpression = nav.Compile("infos/functionInfos/functionInfo");
            XPathNodeIterator functionInfosIterator = nav.Select(functionInfosExpression);

            XPathExpression eventsExpression = nav.Compile("infos/events/*");
            XPathNodeIterator eventsIterator = nav.Select(eventsExpression);

            Hashtable functionInfos = new Hashtable();

            while (functionInfosIterator.MoveNext())
            {
                XPathNavigator node = functionInfosIterator.Current.Clone();

                MethodInfo m = new MethodInfo();
                m.FunctionID = node.GetAttribute("functionId", String.Empty);
                m.ClassName = node.GetAttribute("className", String.Empty);
                m.MethodName = node.GetAttribute("methodName", String.Empty);
                if (node.GetAttribute("static", String.Empty).Length > 0)
                m.IsStatic = Convert.ToBoolean(node.GetAttribute("static", String.Empty));
                m.ReturnType = node.GetAttribute("returnType", String.Empty);

                functionInfos[m.FunctionID] = m;
            }

            ArrayList events = new ArrayList();

            while (eventsIterator.MoveNext())
            {
                XPathNavigator node = eventsIterator.Current.Clone();

                if (node.Name == "methodEvent")
                {
                    MethodEvent m = new MethodEvent();
                    m.InstanceObjectID = node.GetAttribute("objectId", String.Empty);
                    m.MethodInfo = (MethodInfo)functionInfos[node.GetAttribute("functionId", String.Empty)];
                    m.ThreadID = node.GetAttribute("threadId", String.Empty);
                    m.timestamp = Convert.ToDouble(node.GetAttribute("timestamp", String.Empty));

                    String type = node.GetAttribute("type", String.Empty);

                    if (type == "Enter")
                        m.EventType = MethodEvent.EventTypeEnum.EnterEvent;
                    else if (type == "Leave")
                        m.EventType = MethodEvent.EventTypeEnum.LeaveEvent;

                    events.Add(m);
                }
                if (node.Name == "threadEvent")
                {
                    ThreadEvent t = new ThreadEvent();
                    t.timestamp = Convert.ToDouble(node.GetAttribute("timestamp", String.Empty));
                    t.ThreadID = node.GetAttribute("threadId", String.Empty);

                    String type = node.GetAttribute("type", String.Empty);
                    if (type == "Create")
                        t.EventType = ThreadEvent.EventTypeEnum.CreateEvent;
                    else if (type == "Destroy")
                        t.EventType = ThreadEvent.EventTypeEnum.DestroyEvent;

                    events.Add(t);
                }
                if (node.Name == "exceptionEvent")
                {
                    ExceptionEvent t = new ExceptionEvent();
                    t.timestamp = Convert.ToDouble(node.GetAttribute("timestamp", String.Empty));
                    events.Add(t);
                }
            }

            return events;
        }
Example #36
0
 /// <summary>
 /// Send the given event to VS.
 /// </summary>
 internal void Send(DebugThread thread, ExceptionEvent @event)
 {
     eventCallback.Send(thread, @event);
 }
Example #37
0
        private ArrayList readXml(string xmlFile)
        {
            classes = new ArrayList();
            objects = new ArrayList();
            threads = new ArrayList();
            inAppClasses = new ArrayList();

            classList.Items.Clear();
            objectList.Items.Clear();
            threadList.Items.Clear();

            XPathDocument doc = new XPathDocument(xmlFile);
            XPathNavigator nav = doc.CreateNavigator();

            XPathExpression functionInfosExpression = nav.Compile("infos/functionInfos/functionInfo");
            XPathNodeIterator functionInfosIterator = nav.Select(functionInfosExpression);

            XPathExpression eventsExpression = nav.Compile("infos/events/*");
            XPathNodeIterator eventsIterator = nav.Select(eventsExpression);

            Hashtable functionInfos = new Hashtable();

            while (functionInfosIterator.MoveNext())
            {
                XPathNavigator node = functionInfosIterator.Current.Clone();

                MethodInfo m = new MethodInfo();
                m.FunctionID = node.GetAttribute("functionId", String.Empty);
                m.ClassName = node.GetAttribute("className", String.Empty);
                m.MethodName = node.GetAttribute("methodName", String.Empty);
                if (node.GetAttribute("isInApp", String.Empty).Length > 0)
                    m.IsInApp = Convert.ToBoolean(node.GetAttribute("isInApp", String.Empty));
                if (node.GetAttribute("static", String.Empty).Length > 0)
                    m.IsStatic = Convert.ToBoolean(node.GetAttribute("static", String.Empty));
                m.ReturnType = node.GetAttribute("returnType", String.Empty);

                functionInfos[m.FunctionID] = m;

                if (!classes.Contains(m.ClassName)) {
                    classes.Add(m.ClassName);
                    if (m.IsInApp) inAppClasses.Add(classes.Count - 1);
                    classList.Items.Add(m.ClassName);
                    classList.SetItemChecked(classList.Items.Count - 1, true);
                }
            }

            ArrayList events = new ArrayList();

            System.Globalization.NumberFormatInfo info = new System.Globalization.NumberFormatInfo();
            info.NumberDecimalSeparator = ".";
            info.NumberGroupSeparator = ",";

            while (eventsIterator.MoveNext())
            {
                XPathNavigator node = eventsIterator.Current.Clone();

                if (node.Name == "methodEvent")
                {

                    MethodEvent m = new MethodEvent();
                    m.InstanceObjectID = node.GetAttribute("objectId", String.Empty);
                    m.MethodInfo = (MethodInfo)functionInfos[node.GetAttribute("functionId", String.Empty)];
                    m.ThreadID = node.GetAttribute("threadId", String.Empty);
                    m.timestamp = Convert.ToDouble(node.GetAttribute("timestamp", String.Empty), info);

                    String type = node.GetAttribute("type", String.Empty);

                    if (type == "Enter")
                        m.EventType = MethodEvent.EventTypeEnum.EnterEvent;
                    else if (type == "Leave")
                        m.EventType = MethodEvent.EventTypeEnum.LeaveEvent;

                    if (m.InstanceObjectID != "0" && !objects.Contains(m.InstanceObjectID))
                    {
                        objects.Add(m.InstanceObjectID);
                        objectList.Items.Add("Instance " + m.InstanceObjectID + " (" + m.MethodInfo.ClassName + ")");
                        objectList.SetItemChecked(objectList.Items.Count - 1, true);
                    }

                    events.Add(m);
                }
                if (node.Name == "threadEvent")
                {
                    ThreadEvent t = new ThreadEvent();
                    t.timestamp = Convert.ToDouble(node.GetAttribute("timestamp", String.Empty), info);
                    t.ThreadID = node.GetAttribute("threadId", String.Empty);

                    String type = node.GetAttribute("type", String.Empty);
                    if (type == "Create")
                        t.EventType = ThreadEvent.EventTypeEnum.CreateEvent;
                    else if (type == "Destroy")
                        t.EventType = ThreadEvent.EventTypeEnum.DestroyEvent;

                    events.Add(t);

                    if (!threads.Contains(t.ThreadID))
                    {
                        threads.Add(t.ThreadID);
                        threadList.Items.Add("Thread " + t.ThreadID);
                        threadList.SetItemChecked(threadList.Items.Count - 1, true);
                    }
                }
                if (node.Name == "exceptionEvent")
                {
                    ExceptionEvent t = new ExceptionEvent();
                    t.timestamp = Convert.ToDouble(node.GetAttribute("timestamp", String.Empty), info);
                    events.Add(t);
                }
            }

            return events;
        }