Пример #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StackFrame" /> class.
        /// </summary>
        /// <param name="stackTrace">The stack trace.</param>
        /// <param name="frameContext">The frame context.</param>
        internal StackFrame(StackTrace stackTrace, ThreadContext frameContext)
        {
            StackTrace = stackTrace;
            FrameContext = frameContext;
            sourceFileNameAndLine = SimpleCache.Create(ReadSourceFileNameAndLine);
            functionNameAndDisplacement = SimpleCache.Create(ReadFunctionNameAndDisplacement);
            locals = SimpleCache.Create(GetLocals);
            arguments = SimpleCache.Create(GetArguments);
            clrStackFrame = SimpleCache.Create(() => Thread.ClrThread?.StackTrace.Where(f => f.InstructionPointer == InstructionOffset).FirstOrDefault());
            userTypeConvertedLocals = SimpleCache.Create(() =>
            {
                VariableCollection collection = Variable.CastVariableCollectionToUserType(locals.Value);

                GlobalCache.UserTypeCastedVariableCollections.Add(userTypeConvertedLocals);
                return collection;
            });
            userTypeConvertedArguments = SimpleCache.Create(() =>
            {
                VariableCollection collection = Variable.CastVariableCollectionToUserType(arguments.Value);

                GlobalCache.UserTypeCastedVariableCollections.Add(userTypeConvertedArguments);
                return collection;
            });
            module = SimpleCache.Create(() =>
            {
                var m = Process.GetModuleByInnerAddress(InstructionOffset);

                if (m == null && ClrStackFrame != null)
                    m = Process.ClrModuleCache[ClrStackFrame.Module];
                return m;
            });
        }
Пример #2
0
    public void SetAlarm(bool status)
    {
        StackTrace st = new StackTrace();
        print(st.GetFrame(1).GetMethod().Name);
        //print("ALARM SET");
        if (status)
        {
            foreach (Light l in lights)
            {
                l.intensity = 8;
                l.color = Color.red;
                if(l.name != "EnemyCamera")
                    l.GetComponent<AudioSource>().Play();

            }
        }
        else
        {
            foreach (Light l in lights)
            {
                if (l.name != "EnemyCamera")
                {
                    l.intensity = 1;
                    l.color = Color.white;
                    l.GetComponent<AudioSource>().Pause();
                }
                else
                {
                    l.color = Color.green;
                    l.intensity = 10;
                }
            }
        }
    }
Пример #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClrThread"/> class.
        /// </summary>
        /// <param name="thread">The thread.</param>
        /// <param name="clrThread">The CLR thread.</param>
        /// <param name="process">The process.</param>
        internal ClrThread(Thread thread, Microsoft.Diagnostics.Runtime.ClrThread clrThread, Process process)
            : base(thread != null ? thread.Id : uint.MaxValue, clrThread.OSThreadId, process)
        {
            ClrThread = clrThread;
            runtime = SimpleCache.Create(() => Process.ClrRuntimes.Single(r => r.ClrRuntime == clrThread.Runtime));
            appDomain = SimpleCache.Create(() => Runtime.AppDomains.Single(a => a.ClrAppDomain.Address == clrThread.AppDomain));
            clrStackTrace = SimpleCache.Create(() =>
            {
                StackTrace stackTrace = new StackTrace(this);
                uint frameNumber = 0;

                stackTrace.Frames = ClrThread.StackTrace.Where(f => f.Method != null).Select(f =>
                {
                    return new StackFrame(stackTrace, new ThreadContext(f.InstructionPointer, f.StackPointer, ulong.MaxValue))
                    {
                        FrameNumber = frameNumber++,
                        InstructionOffset = f.InstructionPointer,
                        StackOffset = f.StackPointer,
                        FrameOffset = ulong.MaxValue,
                        ReturnOffset = ulong.MaxValue,
                        ClrStackFrame = f,
                    };
                }).ToArray();
                return stackTrace;
            });
            lastThrownException = SimpleCache.Create(() => ClrThread.CurrentException != null ? new ClrException(this, ClrThread.CurrentException) : null);
        }
Пример #4
0
 private static string GetCallingMethod(StackTrace stack)
 {
     StackFrame frame = stack.GetFrame(0);
     string className = frame.GetMethod().DeclaringType.ToString();
     string functionName = frame.GetMethod().Name;
     return string.Format("{0}.{1}", className, functionName);
 }
Пример #5
0
        /// <summary>
        /// The object to lock.
        /// </summary>
        /// <param name="o">The object to lock.</param>
        /// <param name="timeout">The timeout.</param>
        /// <returns></returns>
        /// <exception cref="LockTimeoutException">
        /// </exception>
        public static TimedLock Lock(object o, TimeSpan timeout)
        {
            var tl = new TimedLock(o);

            if (!Monitor.TryEnter(o, timeout))
            {
            #if DEBUG
                GC.SuppressFinalize(tl._leakDetector);
                StackTrace blockingTrace;
                lock (Sentinel.StackTraces)
                {
                    blockingTrace = Sentinel.StackTraces[o] as StackTrace;
                }

                throw new LockTimeoutException(blockingTrace);
            #else
                throw new LockTimeoutException();
            #endif
            }
            #if DEBUG

            // Lock acquired. Store the stack trace.
            var trace = new StackTrace();
            lock (Sentinel.StackTraces)
            {
                Sentinel.StackTraces.Add(o, trace);
            }

            #endif
            return tl;
        }
Пример #6
0
 // Constructor
 public CallerInfo(StackTrace trace)
 {
     this = new CallerInfo();
     MethodName = trace.GetFrame(1).GetMethod().Name;
     ClassName = trace.GetFrame(1).GetMethod().ReflectedType.Name;
     FileName = trace.GetFrame(1).GetFileName();
     LineNumber = trace.GetFrame(1).GetFileLineNumber();
 }
Пример #7
0
			void RecursiveAddFilteredChildren (StackTrace trace)
			{
				if (Store.Options.Filters.Contains (trace.TopMethod.Class.Assembly.BaseName))
					foreach (StackTrace child in trace.CalledFrames)
						RecursiveAddFilteredChildren (child);
				else
					children.Add (new CallsNode (Store, this, trace));
			}
 public static void WriteString(string message)
 {
     OpenLogFile();
     string caller = new StackTrace().GetFrame(1).GetMethod().Name;
     sw.WriteLine("{0:G} {1}:: {2}\n", System.DateTime.Now, caller, message);
     logUsed = true;
     CloseLogFile();
 }
Пример #9
0
    public static void log(string msg, params object[] objs)
    {
        StackTrace st = new StackTrace();
        StackFrame sf = st.GetFrame(1);

        Console.Write("[{0}({1})] ", sf.GetFileName(), sf.GetFileLineNumber());
        Console.WriteLine(msg, objs);
    }
Пример #10
0
 public TestMessage(string m, StackTrace t, Exception e)
 {
     message = m;
     if(t != null)
       trace = FilterStackTrace(t);
     exception = e;
     FilterStackTrace(t);
 }
Пример #11
0
    public static void PrintMethodName()
    {
        StackTrace st = new StackTrace ();
        StackFrame sf = st.GetFrame (1);

        MethodBase currentMethodName = sf.GetMethod ();
        UnityEngine.Debug.Log ("I'm in "+currentMethodName);
    }
Пример #12
0
		/// <summary>
		/// Returns the <see cref="MethodBase"/> object identiying the caller of the current method.
		/// </summary>
		/// <returns>The MethodBase object of the caller of the current method.</returns>
		public static MethodBase CallingMethod()
		{
			var stack = new StackTrace();
			var frame = stack == null ? null : stack.GetFrame( 2 );
			var method = frame == null ? null : frame.GetMethod();

			return method;
		}
Пример #13
0
		/// <summary>
		/// Returns a string in the form "Type.Method" identifying the caller of the current method.
		/// </summary>
		/// <returns>A string identifying the caller of the current method.</returns>
		public static string CalledFrom()
		{
			var stack = new StackTrace();
			var frame = stack == null ? null : stack.GetFrame( 2 );
			var method = frame == null ? null : frame.GetMethod();

			if( method == null ) return "n/a";
			return string.Format( "{0}.{1}", method.DeclaringType.Name, method.Name );
		}
Пример #14
0
    public static void Assert(bool condition, string exprTag)
    {
        if (!condition)
		{
			StackTrace st = new StackTrace(new StackFrame(true));
			StackFrame sf = st.GetFrame(1);
			throw new Exception("Assertion( " + exprTag + " ): File '" + sf.GetFileName() + "', Line " + sf.GetFileLineNumber() + ".");
		}
    }
Пример #15
0
    static void _Log(string message, LOG_TYPE log_type)
    {
        var st = new StackTrace(true);
        var sf = st.GetFrame(2);

        var fpath = sf.GetFileName();
        var fline = sf.GetFileLineNumber();

        XCon.Inst.Log(new LogData{message= message, fpath= fpath, fline= fline, log_type= log_type});
    }
Пример #16
0
	public static void Assert(bool condition)
	{
		if (!condition)
		{
			StackTrace st = new StackTrace(new StackFrame(true));
			StackFrame sf = st.GetFrame(1);
			UnityEngine.Debug.LogError("Assertion( " + sf.ToString() + " ): File '" + sf.GetFileName() + "', Line " + sf.GetFileLineNumber() + ".");
			throw new Exception();
		}
	}
		public static void ResolveCallback(IAsyncResult ar)
		{
		    Console.WriteLine("ResolveCallback()");
		    StackTrace st = new StackTrace();
		    frame_count = st.FrameCount;
	            for(int i = 0; i < st.FrameCount; i++) {
	                StackFrame sf = st.GetFrame(i);
        	        Console.WriteLine("method: {0}", sf.GetMethod());
	            }
        	    Console.WriteLine("ResolveCallback() complete");
		}
Пример #18
0
    public static void Main()
    {
        StackTrace stackTrace = new StackTrace();           // get call stack
        StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

        // write call stack method names
        foreach (StackFrame stackFrame in stackFrames)
        {
          Console.WriteLine(stackFrame.GetMethod().Name);   // write method name
        }
    }
Пример #19
0
    public static GameObject InstantiatePrefab(GameObject prefab, Vector3 location, Quaternion rotation)
    {
        StackTrace st = new StackTrace(true);

        GameObject obj = Instantiate(prefab,location,rotation) as GameObject;

        objects.Add(obj, st.GetFrame(1));

        obj.AddComponent<FancyGizmos>();

        return obj;
    }
  private static int ExecuteScript(string script, string arguments,
      out string output)
  {
    StackFrame sf = new StackFrame(true);
    StackTrace st = new StackTrace(sf);

    sf = st.GetFrame(0);
    string dir = Path.GetDirectoryName(sf.GetFileName());
    string fileName = Path.Combine(dir, script);

    AddExecutablePermissionToScript(fileName);
    return Execute(fileName, arguments, out output);
  }
Пример #21
0
 public void LogCallMethod(bool isStart)
 {
     var stackTrace = new StackTrace();
     StackFrame stackFrame = stackTrace.GetFrame(1);
     MethodBase methodBase = stackFrame.GetMethod();
     if (isStart)
     {
         SiAuto.Main.EnterMethod(this, methodBase.Name);
     }
     else
     {
         SiAuto.Main.LeaveMethod(this, methodBase.Name);
     }
 }
Пример #22
0
    /// <summary>
    ///     Writes event to log file specified above.
    /// </summary>
    /// <param name="output"></param>
    public static void write(string output)
    {
        if (logToFile) {
            StackTrace st = new StackTrace (true);
            // TODO: Colan commented it out because it isn't used
            int lineNumber = st.GetFrame (1).GetFileLineNumber ();

            // Output format:  "(Time delta from program start in format m:ss.sss) :: (Log message)"
            writer.WriteLine (string.Format ("{0:00}:{1:00.000}", Time.realtimeSinceStartup / 60, Time.realtimeSinceStartup % 60f) + " :: \"" + st.GetFrame (1).GetMethod ().ReflectedType.Name + "\" (Line: " + lineNumber + ") :: " + output);

            // Flushes buffer to force a write
            writer.Flush ();
        }
    }
Пример #23
0
		public static string GetStackTrace(string indent)
		{
#if SILVERLIGHT
			var trace = new System.Diagnostics.StackTrace().ToString();
#elif PORTABLE
			var trace = new StackTrace().ToString();
#else
			var skipCount = new System.Diagnostics.StackTrace().GetFrames().TakeWhile(frame => frame.GetMethod().DeclaringType.Assembly == typeof(DebugView).Assembly).Count();
			var trace = new System.Diagnostics.StackTrace(skipCount, true).ToString();
#endif

			return "\n".Join(trace
					.Split('\n')
					.Select(p => indent + p.Trim()));
		}
	private static bool GetProtectionDomains(List<java.security.ProtectionDomain> array, [email protected] callerID, StackTrace stack)
	{
		// first we have to skip all AccessController related frames, because we can be called from a doPrivileged implementation (not the privileged action)
		// in which case we should ignore the doPrivileged frame
		int skip = 0;
		for (; skip < stack.FrameCount; skip++)
		{
			Type type  = stack.GetFrame(skip).GetMethod().DeclaringType;
			if (type != typeof(Java_java_security_AccessController) && type != typeof(java.security.AccessController))
			{
				break;
			}
		}
		java.security.ProtectionDomain previous_protection_domain = null;
		for (int i = skip; i < stack.FrameCount; i++)
		{
			bool is_privileged = false;
			java.security.ProtectionDomain protection_domain;
			MethodBase method = stack.GetFrame(i).GetMethod();
			if (method.DeclaringType == typeof(java.security.AccessController)
				&& method.Name == "doPrivileged")
			{
				is_privileged = true;
				java.lang.Class caller = callerID.getCallerClass();
				protection_domain = caller == null ? null : Java_java_lang_Class.getProtectionDomain0(caller);
			}
			else if (Java_sun_reflect_Reflection.IsHideFromStackWalk(method))
			{
				continue;
			}
			else
			{
				protection_domain = GetProtectionDomainFromType(method.DeclaringType);
			}

			if (previous_protection_domain != protection_domain && protection_domain != null)
			{
				previous_protection_domain = protection_domain;
				array.Add(protection_domain);
			}

			if (is_privileged)
			{
				return true;
			}
		}
		return false;
	}
Пример #25
0
    public static void CallStack()
    {
        //	This method reports the callstack (not including the current class).

        StackTrace st = new StackTrace(true);
        Int32 StackCount = st.FrameCount;

        for (Int32 StackNo = 2; StackNo < StackCount; StackNo++)
        {
            StackFrame sf = st.GetFrame(StackNo);
            string Caller = string.Format("{0} (line {1})",
                sf.GetMethod().DeclaringType.FullName,
                sf.GetFileLineNumber());

            Debug.WriteLine(string.Format("{0}: {1}", ClassTimeAndDate.HhMmSs(DateTime.Now), Caller));
        }
    }
Пример #26
0
        public void Abort()
        {
            lock (this.ThisLock)
            {
                if (this.State == LifetimeState.Closed || this.aborted)
                    return;
#if DEBUG_EXPENSIVE
                if (closeStack == null)
                    closeStack = new StackTrace();
#endif
                this.aborted = true;
                this.state = LifetimeState.Closing;
            }

            this.OnAbort();
            this.state = LifetimeState.Closed;
        }
Пример #27
0
    private static void TriggerAssert(string message)
    {
        var myTrace = new StackTrace(true);
        var myFrame = myTrace.GetFrame(2);

        var assertMsg = "Assert Hit! \n\n" + message + "\n\n" + "Filename: " + myFrame.GetFileName() + "\nMethod: " + myFrame.GetMethod() +
            "\nLine: " + myFrame.GetFileLineNumber();

        #if UNITY_EDITOR
        switch (_handleMethod)
        {
            case AssertHandleMethod.LogAndContinue:
                Debug.LogError(assertMsg);
                break;

            case AssertHandleMethod.MessageBox:

                if (!_shouldStop)
                {
                    var choice = EditorUtility.DisplayDialogComplex("Assert Hit!", assertMsg,
                                                                    "Go To", "Ignore", "Stop");

                    Debug.LogError(assertMsg);
                    if (choice == 0 || choice == 2)
                    {
                        EditorApplication.isPlaying = false;
                        _shouldStop = true;
                    }

                    if (choice == 0)
                    {
                        InternalEditorUtility.OpenFileAtLineExternal(myFrame.GetFileName(), myFrame.GetFileLineNumber());
                    }
                }

                break;

            case AssertHandleMethod.Exception:
                throw new AssertException(assertMsg);

            default:
                Util.Assert(false);
                break;
        }
        #endif
    }
Пример #28
0
        internal static void Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
        {
            if (targets == null)
            {
                return;
            }

#if !NET_CF
            StackTraceUsage stu = targets.GetStackTraceUsage();

            if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
            {
                StackTrace stackTrace;
#if !SILVERLIGHT
                stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
#else
                stackTrace = new StackTrace();
#endif

                int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType);

                logEvent.SetStackTrace(stackTrace, firstUserFrame);
            }
#endif

            int originalThreadId = Thread.CurrentThread.ManagedThreadId;
            AsyncContinuation exceptionHandler = ex =>
                {
                    if (ex != null)
                    {
                        if (factory.ThrowExceptions && Thread.CurrentThread.ManagedThreadId == originalThreadId)
                        {
                            throw new NLogRuntimeException("Exception occurred in NLog", ex);
                        }
                    }
                };

            for (var t = targets; t != null; t = t.NextInChain)
            {
                if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
                {
                    break;
                }
            }
        }
Пример #29
0
    private void InserirErro(Exception e)
    {
        string sDiretorio = ConfigurationSettings.AppSettings["LogDirectory"].ToString();

        if (!Directory.Exists(@sDiretorio))
            Directory.CreateDirectory(@sDiretorio);

        StackTrace stacktrace = new StackTrace();
        StackFrame[] stackframes = stacktrace.GetFrames();

        string Classe = stacktrace.GetFrame(1).GetMethod().ReflectedType.Name;
        string Metodo = stacktrace.GetFrame(1).GetMethod().Name;

        StreamWriter oSw = File.AppendText(@sDiretorio + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
        oSw.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm.ss") + " > Class{ " + Classe + " } : Listar{ " + Metodo + " } - Message{ " + e.Message + " }");
        oSw.Flush();
        oSw.Close();
        oSw = null;
    }
Пример #30
0
    /// <summary>
    /// Performs a stack trace to see where things went wrong
    /// for error reporting.
    /// </summary>
    public static string GetErrorLocation(int level = 1)
    {
        StackTrace stackTrace = new StackTrace();
        string result = "";
        string declaringType = "";

        for (int v = stackTrace.FrameCount - 1; v > level; v--)
        {
            if (v < stackTrace.FrameCount - 1)
                result += " --> ";
            StackFrame stackFrame = stackTrace.GetFrame(v);
            if (stackFrame.GetMethod().DeclaringType.ToString() == declaringType)
                result = "";	// only report the last called method within every class
            declaringType = stackFrame.GetMethod().DeclaringType.ToString();
            result += declaringType + ":" + stackFrame.GetMethod().Name;
        }

        return result;
    }