GetILOffset() public method

public GetILOffset ( ) : int
return int
        private static bool FormatFileName(bool displayFilenames, StackFrame frame, StringBuilder stringBuilder)
        {
            if (displayFilenames && frame.GetILOffset() != -1)
            {
                string text = null;
                try
                {
                    text = frame.GetFileName();
                }
                catch (NotSupportedException)
                {
                    displayFilenames = false;
                }
                catch (SecurityException)
                {
                    displayFilenames = false;
                }

                if (text != null)
                {
                    stringBuilder.Append(' ');
                    stringBuilder.AppendFormat(CultureInfo.InvariantCulture, LineFormat, text,
                                               frame.GetFileLineNumber());
                }
            }

            return(displayFilenames);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ExceptionFrame"/> class.
        /// </summary>
        /// <param name="frame">The <see cref="StackFrame"/>.</param>
        public ExceptionFrame(StackFrame frame)
        {
            if (frame == null)
                return;

            int lineNo = frame.GetFileLineNumber();

            if (lineNo == 0)
            {
                //The pdb files aren't currently available
                lineNo = frame.GetILOffset();
            }

            var method = frame.GetMethod();
            if (method != null)
            {
                Module = (method.DeclaringType != null) ? method.DeclaringType.FullName : null;
                Function = method.Name;
                Source = method.ToString();
            }
            else
            {
                // on some platforms (e.g. on mono), StackFrame.GetMethod() may return null
                // e.g. for this stack frame:
                //   at (wrapper dynamic-method) System.Object:lambda_method (System.Runtime.CompilerServices.Closure,object,object))

                Module = "(unknown)";
                Function = "(unknown)";
                Source = "(unknown)";
            }

            Filename = frame.GetFileName();
            LineNumber = lineNo;
            ColumnNumber = frame.GetFileColumnNumber();
        }
            private StackFrameInfo(StackFrame frame)
            {
                SetStackMeta(frame);

                if (frame.GetILOffset() == -1)
                {
                    return;
                }

                string filename = null;
                try
                {
                    filename = frame.GetFileName();
                    if (filename != null)
                    {
                        LineNumber = frame.GetFileLineNumber();
                    }
                }
                catch (SecurityException)
                {

                }

                FileName = filename;
            }
 public static string StackFrameToString(StackFrame stackFrame)
 {
     StringBuilder sb = new StringBuilder();
     int intParam; MemberInfo mi = stackFrame.GetMethod();
     sb.Append("   ");
     sb.Append(mi.DeclaringType.Namespace);
     sb.Append(".");
     sb.Append(mi.DeclaringType.Name);
     sb.Append(".");
     sb.Append(mi.Name);
     // -- build method params           
     sb.Append("(");
     intParam = 0;
     foreach (ParameterInfo param in stackFrame.GetMethod().GetParameters())
     {
         intParam += 1;
         sb.Append(param.Name);
         sb.Append(" As ");
         sb.Append(param.ParameterType.Name);
     }
     sb.Append(")");
     sb.Append(Environment.NewLine);
     // -- if source code is available, append location info           
     sb.Append("       ");
     if (string.IsNullOrEmpty(stackFrame.GetFileName()))
     {
         sb.Append("(unknown file)");
         //-- native code offset is always available               
         sb.Append(": N ");
         sb.Append(string.Format("{0:#00000}", stackFrame.GetNativeOffset()));
     }
     else
     {
         sb.Append(Path.GetFileName(stackFrame.GetFileName()));
         sb.Append(": line ");
         sb.Append(string.Format("{0:#0000}", stackFrame.GetFileLineNumber()));
         sb.Append(", col ");
         sb.Append(string.Format("{0:#00}", stackFrame.GetFileColumnNumber()));
         if (stackFrame.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
         {
             sb.Append(", IL ");
             sb.Append(string.Format("{0:#0000}", stackFrame.GetILOffset()));
         }
     }
     sb.Append(Environment.NewLine);
     return sb.ToString();
 }
Beispiel #5
0
		public void FileName_LineNumber_ColumnNumber ()
		{
			StackFrame sf = new StackFrame (String.Empty, Int32.MinValue, Int32.MaxValue);
			Assert.AreEqual (Int32.MinValue, sf.GetFileLineNumber (), "GetFileLineNumber");
			Assert.AreEqual (Int32.MaxValue, sf.GetFileColumnNumber (), "GetFileColumnNumber");
			Assert.IsTrue (sf.GetILOffset () >= 0, "GetILOffset");
			Assert.IsTrue (sf.GetNativeOffset () > 0, "GetNativeOffset");
			Assert.AreEqual ("FileName_LineNumber_ColumnNumber", sf.GetMethod ().Name, "GetMethod");
		}
Beispiel #6
0
		public void Default ()
		{
			StackFrame sf = new StackFrame ();
			Assert.AreEqual (0, sf.GetFileLineNumber (), "GetFileLineNumber");
			Assert.AreEqual (0, sf.GetFileColumnNumber (), "GetFileColumnNumber");
			Assert.IsTrue (sf.GetILOffset () >= 0, "GetILOffset");
			Assert.IsTrue (sf.GetNativeOffset () >= 0, "GetNativeOffset");
			Assert.AreEqual ("Default", sf.GetMethod ().Name, "GetMethod");
		}
 /// <summary>
 /// Creates a new instance of the <see cref="WcfRawJson.ErrorHandling.FaultStackFrame"/> 
 /// class from an existing <see cref="System.Diagnostics.StackFrame"/>.
 /// </summary>
 /// <param name="frame">
 /// The <see cref="System.Diagnostics.StackFrame"/> object from which to derive this
 /// <see cref="WcfRawJson.ErrorHandling.StackFrame"/>
 /// </param>
 public FaultStackFrame(StackFrame frame)
 {
     this.FileColumnNumber = frame.GetFileColumnNumber();
     this.FileLineNumber = frame.GetFileLineNumber();
     this.FileName = frame.GetFileName();
     this.ILOffset = frame.GetILOffset();
     this.Method = frame.GetMethod().ToString();
     this.NativeOffset = frame.GetNativeOffset();
     this.Description = frame.ToString();
 }
Beispiel #8
0
        public CallSite(StackFrame frame)
        {
            Line = frame.GetFileLineNumber();
            File = frame.GetFileName();
            ILOffset = frame.GetILOffset();

            var method = frame.GetMethod();

            if (method != null)
                Method = new MethodInfo(method);
        }
Beispiel #9
0
		// avoid replication of tests on all constructors (this is no 
		// problem because the stack is already set correctly). The 
		// goal is to call every property and methods to see if they
		// have any* security requirements (*except for LinkDemand and
		// InheritanceDemand).
		private void Check (StackFrame sf, bool checkFile)
		{
			int cn = sf.GetFileColumnNumber ();
			int ln = sf.GetFileLineNumber ();
			int il = sf.GetILOffset ();
			int no = sf.GetNativeOffset ();

			Assert.IsNotNull (sf.GetMethod (), "GetMethod");

			if (checkFile) {
				string fn = sf.GetFileName ();
			}
		}
Beispiel #10
0
        public static string FormatLocation(StackFrame frame)
        {
            StringBuilder location = new StringBuilder();

            location.Append(frame.GetMethod().DeclaringType.ToString());
            location.Append("=>");
            location.Append(frame.GetMethod().ToString());
            location.Append(" [");
            location.Append(frame.GetILOffset());
            location.Append(":");
            location.Append(frame.GetNativeOffset());
            location.Append("]");

            return location.ToString();
        }
Beispiel #11
0
        public static StackFrame Create(System.Diagnostics.StackFrame frame)
        {
            if (frame == null)
            {
                return(null);
            }

            string      fileName      = null;
            bool        isTaskAwaiter = false;
            ITypeMember member        = null;

            try {
                fileName = frame.GetFileName();
            } catch (SecurityException) {
                // CAS check failure
            }

            var method = frame.GetMethod();

            if (method != null)
            {
                isTaskAwaiter = method.DeclaringType.IsTaskAwaiter() ||
                                method.DeclaringType.DeclaringType.IsTaskAwaiter();

                var property = GetPropertyForMethodAccessor(method);
                if (property != null)
                {
                    member = Property.Create(property);
                }
                else
                {
                    member = Method.Create(method);
                }
            }

            return(new StackFrame(
                       fileName,
                       frame.GetFileLineNumber(),
                       frame.GetFileColumnNumber(),
                       frame.GetILOffset(),
                       frame.GetNativeOffset(),
                       frame.GetMethodAddress(),
                       frame.GetMethodIndex(),
                       isTaskAwaiter,
                       ParseInternalMethodName(frame.GetInternalMethodName()),
                       member));
        }
Beispiel #12
0
        public void TraceCallers(int Depth)
        {
            if (_switch.Enabled)
            {
                System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1);
                if (Depth < 0)
                    Depth = st.FrameCount;

                Indent();

                for (int i=0; i < st.FrameCount && i < Depth; i++)
                {
                    System.Diagnostics.StackFrame sf = st.GetFrame(i);
                    Trace(sf.GetMethod()+"+"+sf.GetILOffset().ToString(System.Globalization.CultureInfo.InvariantCulture));
                }

                Unindent();
            }

        }
Beispiel #13
0
        public override bool Equals(Object obj)
        {
            if ((obj == null) || (!(obj is StackFrame)))
            {
                return(false);
            }

            StackFrame rhs = (StackFrame)obj;

            if (!ObjectsEqual(GetMethod(), rhs.GetMethod()))
            {
                return(false);
            }

            if (!ObjectsEqual(GetFileName(), rhs.GetFileName()))
            {
                return(false);
            }

            if (GetFileLineNumber() != rhs.GetFileLineNumber())
            {
                return(false);
            }

            if (GetFileColumnNumber() != rhs.GetFileColumnNumber())
            {
                return(false);
            }

            if (GetILOffset() != rhs.GetILOffset())
            {
                return(false);
            }

            if (GetNativeOffset() != rhs.GetNativeOffset())
            {
                return(false);
            }

            return(true);
        }
Beispiel #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExceptionFrame"/> class.
        /// </summary>
        /// <param name="frame">The <see cref="StackFrame"/>.</param>
        public ExceptionFrame(StackFrame frame)
        {
            if (frame == null)
                return;

            int lineNo = frame.GetFileLineNumber();

            if (lineNo == 0)
            {
                //The pdb files aren't currently available
                lineNo = frame.GetILOffset();
            }

            var method = frame.GetMethod();
            Filename = frame.GetFileName();
            Module = (method.DeclaringType != null) ? method.DeclaringType.FullName : null;
            Function = method.Name;
            Source = method.ToString();
            LineNumber = lineNo;
            ColumnNumber = frame.GetFileColumnNumber();
        }
        private static ExceptionFrame BuildExceptionFrame(StackFrame frame)
        {
            int lineNo = frame.GetFileLineNumber();

            if (lineNo == 0)
            {
                //The pdb files aren't currently available
                lineNo = frame.GetILOffset();
            }

            var method = frame.GetMethod();
            return new ExceptionFrame()
            {
                Filename = frame.GetFileName(),
                Module = (method.DeclaringType != null) ? method.DeclaringType.FullName : null,
                Function = method.Name,
                Source = method.ToString(),
                LineNumber = lineNo,
                ColumnNumber = frame.GetFileColumnNumber()
            };
        }
Beispiel #16
0
        public void TraceCallers(int Depth)
        {
#if DEBUG
            if (_switch.Enabled)
            {
                System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1);
                if (Depth < 0)
                {
                    Depth = st.FrameCount;
                }

                Indent();

                for (int i = 0; i < st.FrameCount && i < Depth; i++)
                {
                    System.Diagnostics.StackFrame sf = st.GetFrame(i);
                    Trace(sf.GetMethod() + "+" + sf.GetILOffset().ToString());
                }

                Unindent();
            }
#endif
        }
Beispiel #17
0
        /// <summary>
        /// Initialises a new instance of the FieldLogStackFrame class.
        /// </summary>
        /// <param name="stackFrame">The StackFrame instance.</param>
        public FieldLogStackFrame(StackFrame stackFrame)
        {
            MethodBase method = stackFrame.GetMethod();

            if (method.DeclaringType != null)
            {
                Module = method.DeclaringType.Module.FullyQualifiedName;
                Token = method.MetadataToken;
                ILOffset = stackFrame.GetILOffset();
                TypeName = FormatTypeName(method.DeclaringType);
            }
            MethodName = method.Name;

            // TODO: Include 'extern' indicator from the following tests (needs new file format)
            //bool isPInvoke = (method.Attributes & MethodAttributes.PinvokeImpl) != 0;
            //bool isInternalCall = (method.GetMethodImplementationFlags() & MethodImplAttributes.InternalCall) != 0;

            MethodInfo methodInfo = method as MethodInfo;
            StringBuilder sigSb = new StringBuilder();
            if (methodInfo != null)
            {
                sigSb.Append(FormatTypeName(methodInfo.ReturnType));
            }
            else
            {
                sigSb.Append("void");   // Dummy return value for constructors
            }
            ParameterInfo[] parameters = method.GetParameters();
            sigSb.Append("(");
            for (int i = 0; i < parameters.Length; i++)
            {
                if (i > 0)
                {
                    sigSb.Append(", ");
                }
                sigSb.Append(FormatTypeName(parameters[i].ParameterType));
            }
            sigSb.Append(")");
            MethodSignature = sigSb.ToString();

            FileName = stackFrame.GetFileName();
            Line = stackFrame.GetFileLineNumber();
            Column = stackFrame.GetFileColumnNumber();

            Size = (Module != null ? Module.Length * 2 : 0) +
                (TypeName != null ? TypeName.Length * 2 : 0) +
                (MethodName != null ? MethodName.Length * 2 : 0) +
                (MethodSignature != null ? MethodSignature.Length * 2 : 0) +
                (FileName != null ? FileName.Length * 2 : 0) +
                4 + 4;
        }
Beispiel #18
0
        /// <summary>
        /// Builds a readable representation of the stack trace, specifying
        /// the format for backwards compatibility.
        /// </summary>
        internal string ToString(TraceFormat traceFormat)
        {
            string word_At       = SR.Word_At;
            string inFileLineNum = SR.StackTrace_InFileLineNumber;

            bool          fFirstFrame = true;
            StringBuilder sb          = new StringBuilder(255);

            for (int iFrameIndex = 0; iFrameIndex < _numOfFrames; iFrameIndex++)
            {
                StackFrame sf = GetFrame(iFrameIndex);
                MethodBase mb = sf.GetMethod();
                if (mb != null && (ShowInStackTrace(mb) ||
                                   (iFrameIndex == _numOfFrames - 1))) // Don't filter last frame
                {
                    // We want a newline at the end of every line except for the last
                    if (fFirstFrame)
                    {
                        fFirstFrame = false;
                    }
                    else
                    {
                        sb.Append(Environment.NewLine);
                    }

                    sb.AppendFormat(CultureInfo.InvariantCulture, "   {0} ", word_At);

                    bool   isAsync       = false;
                    Type   declaringType = mb.DeclaringType;
                    string methodName    = mb.Name;
                    bool   methodChanged = false;
                    if (declaringType != null && declaringType.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false))
                    {
                        isAsync = typeof(IAsyncStateMachine).IsAssignableFrom(declaringType);
                        if (isAsync || typeof(IEnumerator).IsAssignableFrom(declaringType))
                        {
                            methodChanged = TryResolveStateMachineMethod(ref mb, out declaringType);
                        }
                    }

                    // if there is a type (non global method) print it
                    // ResolveStateMachineMethod may have set declaringType to null
                    if (declaringType != null)
                    {
                        // Append t.FullName, replacing '+' with '.'
                        string fullName = declaringType.FullName;
                        for (int i = 0; i < fullName.Length; i++)
                        {
                            char ch = fullName[i];
                            sb.Append(ch == '+' ? '.' : ch);
                        }
                        sb.Append('.');
                    }
                    sb.Append(mb.Name);

                    // deal with the generic portion of the method
                    if (mb is MethodInfo mi && mi.IsGenericMethod)
                    {
                        Type[] typars = mi.GetGenericArguments();
                        sb.Append('[');
                        int  k             = 0;
                        bool fFirstTyParam = true;
                        while (k < typars.Length)
                        {
                            if (fFirstTyParam == false)
                            {
                                sb.Append(',');
                            }
                            else
                            {
                                fFirstTyParam = false;
                            }

                            sb.Append(typars[k].Name);
                            k++;
                        }
                        sb.Append(']');
                    }

                    ParameterInfo[] pi = null;
                    try
                    {
                        pi = mb.GetParameters();
                    }
                    catch
                    {
                        // The parameter info cannot be loaded, so we don't
                        // append the parameter list.
                    }
                    if (pi != null)
                    {
                        // arguments printing
                        sb.Append('(');
                        bool fFirstParam = true;
                        for (int j = 0; j < pi.Length; j++)
                        {
                            if (fFirstParam == false)
                            {
                                sb.Append(", ");
                            }
                            else
                            {
                                fFirstParam = false;
                            }

                            string typeName = "<UnknownType>";
                            if (pi[j].ParameterType != null)
                            {
                                typeName = pi[j].ParameterType.Name;
                            }
                            sb.Append(typeName);
                            sb.Append(' ');
                            sb.Append(pi[j].Name);
                        }
                        sb.Append(')');
                    }

                    if (methodChanged)
                    {
                        // Append original method name e.g. +MoveNext()
                        sb.Append('+');
                        sb.Append(methodName);
                        sb.Append('(').Append(')');
                    }

                    // source location printing
                    if (sf.GetILOffset() != -1)
                    {
                        // If we don't have a PDB or PDB-reading is disabled for the module,
                        // then the file name will be null.
                        string fileName = sf.GetFileName();

                        if (fileName != null)
                        {
                            // tack on " in c:\tmp\MyFile.cs:line 5"
                            sb.Append(' ');
                            sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber());
                        }
                    }

                    if (sf.GetIsLastFrameFromForeignExceptionStackTrace() &&
                        !isAsync) // Skip EDI boundary for async
                    {
                        sb.Append(Environment.NewLine);
                        sb.Append(SR.Exception_EndStackTraceFromPreviousThrow);
                    }
                }
            }

            if (traceFormat == TraceFormat.TrailingNewLine)
            {
                sb.Append(Environment.NewLine);
            }

            return(sb.ToString());
        }
Beispiel #19
0
        internal string ToString(TraceFormat traceFormat)
        {
            string resourceString = "at";
            string format         = "in {0}:line {1}";

            if (traceFormat != TraceFormat.NoResourceLookup)
            {
                resourceString = Environment.GetResourceString("Word_At");
                format         = Environment.GetResourceString("StackTrace_InFileLineNumber");
            }
            bool          flag    = true;
            StringBuilder builder = new StringBuilder(0xff);

            for (int i = 0; i < this.m_iNumOfFrames; i++)
            {
                StackFrame frame  = this.GetFrame(i);
                MethodBase method = frame.GetMethod();
                if (method != null)
                {
                    if (flag)
                    {
                        flag = false;
                    }
                    else
                    {
                        builder.Append(Environment.NewLine);
                    }
                    builder.AppendFormat(CultureInfo.InvariantCulture, "   {0} ", new object[] { resourceString });
                    Type declaringType = method.DeclaringType;
                    if (declaringType != null)
                    {
                        builder.Append(declaringType.FullName.Replace('+', '.'));
                        builder.Append(".");
                    }
                    builder.Append(method.Name);
                    if ((method is MethodInfo) && ((MethodInfo)method).IsGenericMethod)
                    {
                        Type[] genericArguments = ((MethodInfo)method).GetGenericArguments();
                        builder.Append("[");
                        int  index = 0;
                        bool flag2 = true;
                        while (index < genericArguments.Length)
                        {
                            if (!flag2)
                            {
                                builder.Append(",");
                            }
                            else
                            {
                                flag2 = false;
                            }
                            builder.Append(genericArguments[index].Name);
                            index++;
                        }
                        builder.Append("]");
                    }
                    builder.Append("(");
                    ParameterInfo[] parameters = method.GetParameters();
                    bool            flag3      = true;
                    for (int j = 0; j < parameters.Length; j++)
                    {
                        if (!flag3)
                        {
                            builder.Append(", ");
                        }
                        else
                        {
                            flag3 = false;
                        }
                        string name = "<UnknownType>";
                        if (parameters[j].ParameterType != null)
                        {
                            name = parameters[j].ParameterType.Name;
                        }
                        builder.Append(name + " " + parameters[j].Name);
                    }
                    builder.Append(")");
                    if (frame.GetILOffset() != -1)
                    {
                        string fileName = null;
                        try
                        {
                            fileName = frame.GetFileName();
                        }
                        catch (SecurityException)
                        {
                        }
                        if (fileName != null)
                        {
                            builder.Append(' ');
                            builder.AppendFormat(CultureInfo.InvariantCulture, format, new object[] { fileName, frame.GetFileLineNumber() });
                        }
                    }
                }
            }
            if (traceFormat == TraceFormat.TrailingNewLine)
            {
                builder.Append(Environment.NewLine);
            }
            return(builder.ToString());
        }
 private static string StackFrameToString(StackFrame sf, ref string errorFrom)
 {
     StringBuilder sb = new StringBuilder();
     int intParam;
     MemberInfo mi = sf.GetMethod();
     Type type = mi.DeclaringType;
     string namspace = type.Namespace ?? string.Empty;
     if (namspace.Equals("ExamineSystem.utility.eslog"))
     {
         return sb.ToString();
     }
     if (string.IsNullOrEmpty(errorFrom))
     {
         try
         {
             if (type.IsSubclassOf(typeof(System.Web.UI.Page)))
             {
                 errorFrom = type.FullName;
             }
             else if (type.IsSubclassOf(typeof(System.Web.UI.Control)))
             {
                 errorFrom = type.FullName;
             }
             else if (type.GetInterface("System.Web.IHttpHandler") != null)
             {
                 errorFrom = type.FullName;
             }
             else if (type.GetInterface("System.Web.IHttpAsyncHandler") != null)
             {
                 errorFrom = type.FullName;
             }
             else if (type.GetInterface("System.Web.IHttpModule") != null)
             {
                 errorFrom = type.FullName;
             }
             else if (type.GetInterface("System.Web.IHttpHandlerFactory") != null)
             {
                 errorFrom = type.FullName;
             }
         }
         catch (Exception)
         {
             errorFrom = string.Empty;
         }
     }
     sb.Append("   ");
     sb.Append(namspace);
     sb.Append(".");
     sb.Append(type.Name);
     sb.Append(".");
     sb.Append(mi.Name);
     // -- build method params
     sb.Append("(");
     intParam = 0;
     foreach (ParameterInfo param in sf.GetMethod().GetParameters())
     {
         if (intParam > 0)
             sb.Append(" , ");
         sb.Append(param.Name);
         sb.Append(" As ");
         sb.Append(param.ParameterType.Name);
         intParam += 1;
     }
     sb.Append(")");
     sb.Append(Environment.NewLine);
     // -- if source code is available, append location info
     sb.Append("       ");
     if (string.IsNullOrEmpty(sf.GetFileName()))
     {
         sb.Append("(unknown file)");
         //-- native code offset is always available
         sb.Append(": N ");
         sb.Append(String.Format("{0:#00000}", sf.GetNativeOffset()));
     }
     else
     {
         sb.Append(System.IO.Path.GetFileName(sf.GetFileName()));
         sb.Append(": line ");
         sb.Append(String.Format("{0:#0000}", sf.GetFileLineNumber()));
         sb.Append(", col ");
         sb.Append(String.Format("{0:#00}", sf.GetFileColumnNumber()));
         if (sf.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
         {
             sb.Append(", IL ");
             sb.Append(String.Format("{0:#0000}", sf.GetILOffset()));
         }
     }
     sb.Append(Environment.NewLine);
     return sb.ToString();
 }
        private void CalculateStatistics(object sender, FirstChanceExceptionEventArgs firstChanceExceptionArgs)
        {
            // this is thread local variable. No need to lock
            if (executionSyncObject == LOCKED)
            {
                return;
            }

            try
            {
                Exception exception;
                string    exceptionType;
                System.Diagnostics.StackFrame exceptionStackFrame;
                string problemId;
                string methodName       = "UnknownMethod";
                int    methodOffset     = System.Diagnostics.StackFrame.OFFSET_UNKNOWN;
                bool   getOperationName = false;

                executionSyncObject = LOCKED;

                if (this.MovingAverageTimeout < DateTime.UtcNow.Ticks)
                {
                    lock (this.movingAverageLockObject)
                    {
                        if (this.MovingAverageTimeout < DateTime.UtcNow.Ticks)
                        {
                            if (this.MovingAverageTimeout + TicksMovingAverage < DateTime.UtcNow.Ticks)
                            {
                                this.currentMovingAverage = 0;
                            }
                            else
                            {
                                this.currentMovingAverage = (this.currentMovingAverage * CurrentWeight) +
                                                            (((double)this.newProcessed) * NewWeight);
                            }

                            this.newThreshold = (long)((this.TargetMovingAverage - (this.currentMovingAverage * CurrentWeight)) / NewWeight);

                            this.newProcessed = 0;

                            this.MovingAverageTimeout = DateTime.UtcNow.Ticks + TicksMovingAverage;
                        }
                    }
                }

                exception = firstChanceExceptionArgs?.Exception;

                if (exception == null)
                {
                    WindowsServerEventSource.Log.FirstChanceExceptionCallbackExeptionIsNull();
                    return;
                }

                if (WasExceptionTracked(exception) == true)
                {
                    return;
                }

                exceptionType = exception.GetType().FullName;

                exceptionStackFrame = new System.Diagnostics.StackFrame(1);

                if (exceptionStackFrame != null)
                {
                    MethodBase methodBase = exceptionStackFrame.GetMethod();

                    if (methodBase != null)
                    {
                        methodName   = (methodBase.DeclaringType?.FullName ?? "Global") + "." + methodBase.Name;
                        methodOffset = exceptionStackFrame.GetILOffset();
                    }
                }

                if (methodOffset == System.Diagnostics.StackFrame.OFFSET_UNKNOWN)
                {
                    problemId = exceptionType + " at " + methodName;
                }
                else
                {
                    problemId = exceptionType + " at " + methodName + ":" + methodOffset.ToString(CultureInfo.InvariantCulture);
                }

                if (this.newProcessed < this.newThreshold)
                {
                    Interlocked.Increment(ref this.newProcessed);

                    getOperationName = true;
                }

                this.TrackStatistics(getOperationName, problemId, exception);
            }
            catch (Exception exc)
            {
                try
                {
                    WindowsServerEventSource.Log.FirstChanceExceptionCallbackException(exc.ToInvariantString());
                }
                catch (Exception)
                {
                    // this is absolutely critical to not throw out of this method
                    // Otherwise it will affect the customer application behavior significantly
                }
            }
            finally
            {
                executionSyncObject = UNLOCKED;
            }
        }
Beispiel #22
0
        // Builds a readable representation of the stack trace, specifying
        // the format for backwards compatibility.
        internal string ToString(TraceFormat traceFormat)
        {
            bool   displayFilenames = true; // we'll try, but demand may fail
            string word_At          = "at";
            string inFileLineNum    = "in {0}:line {1}";

            if (traceFormat != TraceFormat.NoResourceLookup)
            {
                word_At       = SR.Word_At;
                inFileLineNum = SR.StackTrace_InFileLineNumber;
            }

            bool          fFirstFrame = true;
            StringBuilder sb          = new StringBuilder(255);

            for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
            {
                StackFrame sf = GetFrame(iFrameIndex);
                MethodBase mb = sf.GetMethod();
                if (mb != null && (ShowInStackTrace(mb) ||
                                   (iFrameIndex == m_iNumOfFrames - 1))) // Don't filter last frame
                {
                    // We want a newline at the end of every line except for the last
                    if (fFirstFrame)
                    {
                        fFirstFrame = false;
                    }
                    else
                    {
                        sb.Append(Environment.NewLine);
                    }

                    sb.AppendFormat(CultureInfo.InvariantCulture, "   {0} ", word_At);

                    bool   isAsync       = false;
                    Type   declaringType = mb.DeclaringType;
                    string methodName    = mb.Name;
                    bool   methodChanged = false;
                    if (declaringType != null && declaringType.IsDefined(typeof(CompilerGeneratedAttribute)))
                    {
                        isAsync = typeof(IAsyncStateMachine).IsAssignableFrom(declaringType);
                        if (isAsync || typeof(IEnumerator).IsAssignableFrom(declaringType))
                        {
                            methodChanged = TryResolveStateMachineMethod(ref mb, out declaringType);
                        }
                    }

                    // if there is a type (non global method) print it
                    // ResolveStateMachineMethod may have set declaringType to null
                    if (declaringType != null)
                    {
                        // Append t.FullName, replacing '+' with '.'
                        string fullName = declaringType.FullName;
                        for (int i = 0; i < fullName.Length; i++)
                        {
                            char ch = fullName[i];
                            sb.Append(ch == '+' ? '.' : ch);
                        }
                        sb.Append('.');
                    }
                    sb.Append(mb.Name);

                    // deal with the generic portion of the method
                    if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod)
                    {
                        Type[] typars = ((MethodInfo)mb).GetGenericArguments();
                        sb.Append('[');
                        int  k             = 0;
                        bool fFirstTyParam = true;
                        while (k < typars.Length)
                        {
                            if (fFirstTyParam == false)
                            {
                                sb.Append(',');
                            }
                            else
                            {
                                fFirstTyParam = false;
                            }

                            sb.Append(typars[k].Name);
                            k++;
                        }
                        sb.Append(']');
                    }

                    ParameterInfo[] pi = null;
                    try
                    {
                        pi = mb.GetParameters();
                    }
                    catch
                    {
                        // The parameter info cannot be loaded, so we don't
                        // append the parameter list.
                    }
                    if (pi != null)
                    {
                        // arguments printing
                        sb.Append('(');
                        bool fFirstParam = true;
                        for (int j = 0; j < pi.Length; j++)
                        {
                            if (fFirstParam == false)
                            {
                                sb.Append(", ");
                            }
                            else
                            {
                                fFirstParam = false;
                            }

                            string typeName = "<UnknownType>";
                            if (pi[j].ParameterType != null)
                            {
                                typeName = pi[j].ParameterType.Name;
                            }
                            sb.Append(typeName);
                            sb.Append(' ');
                            sb.Append(pi[j].Name);
                        }
                        sb.Append(')');
                    }

                    if (methodChanged)
                    {
                        // Append original method name e.g. +MoveNext()
                        sb.Append("+");
                        sb.Append(methodName);
                        sb.Append("()");
                    }

                    // source location printing
                    if (displayFilenames && (sf.GetILOffset() != -1))
                    {
                        // If we don't have a PDB or PDB-reading is disabled for the module,
                        // then the file name will be null.
                        string fileName = null;

                        // Getting the filename from a StackFrame is a privileged operation - we won't want
                        // to disclose full path names to arbitrarily untrusted code.  Rather than just omit
                        // this we could probably trim to just the filename so it's still mostly usefull.
                        try
                        {
                            fileName = sf.GetFileName();
                        }
                        catch (SecurityException)
                        {
                            // If the demand for displaying filenames fails, then it won't
                            // succeed later in the loop.  Avoid repeated exceptions by not trying again.
                            displayFilenames = false;
                        }

                        if (fileName != null)
                        {
                            // tack on " in c:\tmp\MyFile.cs:line 5"
                            sb.Append(' ');
                            sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber());
                        }
                    }

                    if (sf.GetIsLastFrameFromForeignExceptionStackTrace() &&
                        !isAsync) // Skip EDI boundary for async
                    {
                        sb.Append(Environment.NewLine);
                        sb.Append(SR.Exception_EndStackTraceFromPreviousThrow);
                    }
                }
            }

            if (traceFormat == TraceFormat.TrailingNewLine)
            {
                sb.Append(Environment.NewLine);
            }

            return(sb.ToString());
        }
 public static bool HasILOffset(this StackFrame stackFrame)
 {
     return(stackFrame.GetILOffset() != StackFrame.OFFSET_UNKNOWN);
 }
        //--
        //-- turns a single stack frame object into an informative string
        //--
        private static string StackFrameToString(StackFrame sf)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            int intParam = 0;
            MemberInfo mi = sf.GetMethod();

            var _with1 = sb;
            //-- build method name
            _with1.Append("   ");
            _with1.Append(mi.DeclaringType.Namespace);
            _with1.Append(".");
            _with1.Append(mi.DeclaringType.Name);
            _with1.Append(".");
            _with1.Append(mi.Name);

            //-- build method params
            ParameterInfo[] objParameters = sf.GetMethod().GetParameters();
            ParameterInfo objParameter = null;
            _with1.Append("(");
            intParam = 0;
            foreach (ParameterInfo objParameter_loopVariable in objParameters)
            {
                objParameter = objParameter_loopVariable;
                intParam += 1;
                if (intParam > 1)
                    _with1.Append(", ");
                _with1.Append(objParameter.Name);
                _with1.Append(" As ");
                _with1.Append(objParameter.ParameterType.Name);
            }
            _with1.Append(")");
            _with1.Append(Environment.NewLine);

            //-- if source code is available, append location info
            _with1.Append("       ");
            if (sf.GetFileName() == null || sf.GetFileName().Length == 0)
            {
                _with1.Append(System.IO.Path.GetFileName(ParentAssembly().CodeBase));
                //-- native code offset is always available
                _with1.Append(": N ");
                _with1.Append(string.Format("{0:#00000}", sf.GetNativeOffset()));
            }
            else
            {
                _with1.Append(System.IO.Path.GetFileName(sf.GetFileName()));
                _with1.Append(": line ");
                _with1.Append(string.Format("{0:#0000}", sf.GetFileLineNumber()));
                _with1.Append(", col ");
                _with1.Append(string.Format("{0:#00}", sf.GetFileColumnNumber()));
                //-- if IL is available, append IL location info
                if (sf.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
                {
                    _with1.Append(", IL ");
                    _with1.Append(string.Format("{0:#0000}", sf.GetILOffset()));
                }
            }
            _with1.Append(Environment.NewLine);
            return sb.ToString();
        }
        // Token: 0x0600325C RID: 12892 RVA: 0x000C1298 File Offset: 0x000BF498
        internal string ToString(StackTrace.TraceFormat traceFormat)
        {
            bool   flag   = true;
            string arg    = "at";
            string format = "in {0}:line {1}";

            if (traceFormat != StackTrace.TraceFormat.NoResourceLookup)
            {
                arg    = Environment.GetResourceString("Word_At");
                format = Environment.GetResourceString("StackTrace_InFileLineNumber");
            }
            bool          flag2         = true;
            StringBuilder stringBuilder = new StringBuilder(255);

            for (int i = 0; i < this.m_iNumOfFrames; i++)
            {
                StackFrame frame  = this.GetFrame(i);
                MethodBase method = frame.GetMethod();
                if (method != null)
                {
                    if (flag2)
                    {
                        flag2 = false;
                    }
                    else
                    {
                        stringBuilder.Append(Environment.NewLine);
                    }
                    stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "   {0} ", arg);
                    Type declaringType = method.DeclaringType;
                    if (declaringType != null)
                    {
                        stringBuilder.Append(declaringType.FullName.Replace('+', '.'));
                        stringBuilder.Append(".");
                    }
                    stringBuilder.Append(method.Name);
                    if (method is MethodInfo && ((MethodInfo)method).IsGenericMethod)
                    {
                        Type[] genericArguments = ((MethodInfo)method).GetGenericArguments();
                        stringBuilder.Append("[");
                        int  j     = 0;
                        bool flag3 = true;
                        while (j < genericArguments.Length)
                        {
                            if (!flag3)
                            {
                                stringBuilder.Append(",");
                            }
                            else
                            {
                                flag3 = false;
                            }
                            stringBuilder.Append(genericArguments[j].Name);
                            j++;
                        }
                        stringBuilder.Append("]");
                    }
                    stringBuilder.Append("(");
                    ParameterInfo[] parameters = method.GetParameters();
                    bool            flag4      = true;
                    for (int k = 0; k < parameters.Length; k++)
                    {
                        if (!flag4)
                        {
                            stringBuilder.Append(", ");
                        }
                        else
                        {
                            flag4 = false;
                        }
                        string str = "<UnknownType>";
                        if (parameters[k].ParameterType != null)
                        {
                            str = parameters[k].ParameterType.Name;
                        }
                        stringBuilder.Append(str + " " + parameters[k].Name);
                    }
                    stringBuilder.Append(")");
                    if (flag && frame.GetILOffset() != -1)
                    {
                        string text = null;
                        try
                        {
                            text = frame.GetFileName();
                        }
                        catch (NotSupportedException)
                        {
                            flag = false;
                        }
                        catch (SecurityException)
                        {
                            flag = false;
                        }
                        if (text != null)
                        {
                            stringBuilder.Append(' ');
                            stringBuilder.AppendFormat(CultureInfo.InvariantCulture, format, text, frame.GetFileLineNumber());
                        }
                    }
                    if (frame.GetIsLastFrameFromForeignExceptionStackTrace())
                    {
                        stringBuilder.Append(Environment.NewLine);
                        stringBuilder.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow"));
                    }
                }
            }
            if (traceFormat == StackTrace.TraceFormat.TrailingNewLine)
            {
                stringBuilder.Append(Environment.NewLine);
            }
            return(stringBuilder.ToString());
        }
Beispiel #26
0
		private static string GetCurLine(StackFrame sf)
		{
			if (sf.GetILOffset() != -1)
			{
				string s = null;
				try
				{
					s = sf.GetFileName();
				}
				catch (SecurityException)
				{
				}
				if (s != null)
				{
					return string.Format(" in {0}:line {1}", s, sf.GetFileLineNumber());
				}
			}
			return "";
		}
        private static string StackFrameToString(StackFrame sf)
        {
            var sb = new StringBuilder();
            MemberInfo mi = sf.GetMethod();

            sb.AppendFormat("   {0}.{1}.{2}",
                mi.DeclaringType.Namespace,
                mi.DeclaringType.Name,
                mi.Name);

            ParameterInfo[] parameters = sf.GetMethod().GetParameters();
            sb.Append("(");
            sb.Append(String.Join(", ", parameters.Select(p => String.Format("{0} {1}", p.ParameterType.Name, p.Name)).ToArray()));
            sb.Append(")");
            sb.AppendLine();

            sb.Append("       ");
            if (String.IsNullOrEmpty(sf.GetFileName()))
            {
                sb.Append(Path.GetFileName(ParentAssembly.CodeBase));
                sb.Append(": N ");
                sb.AppendFormat("{0:#00000}", sf.GetNativeOffset());
            }
            else
            {
                sb.Append(Path.GetFileName(sf.GetFileName()));
                sb.AppendFormat(": line {0:#0000}, col {1:#00}", sf.GetFileLineNumber(), sf.GetFileColumnNumber());
                if (sf.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
                {
                    sb.AppendFormat(", IL {0:#0000}", sf.GetILOffset());
                }
            }
            sb.AppendLine();

            return sb.ToString();
        }
 /// <summary>
 ///    Gets the offset from the start of the Microsoft intermediate language (MSIL)
 ///    code for the method that is executing. This offset might be an approximation
 ///    depending on whether or not the just-in-time (JIT) compiler is generating debugging
 ///    code. The generation of this debugging information is controlled by the System.Diagnostics.DebuggableAttribute.
 /// </summary>
 /// <returns>The offset from the start of the MSIL code for the method that is executing.</returns>
 public override int GetILOffset() => StackFrame.GetILOffset();
        private static AirbrakeTraceLine TraceLineForFrame(StackFrame frame)
        {
            var method = frame.GetMethod();

            var lineNumber = frame.GetFileLineNumber();
            if (lineNumber == 0)
                lineNumber = frame.GetILOffset();

            var fileName = frame.GetFileName();
            if (string.IsNullOrEmpty(fileName))
                fileName = method.ReflectedType != null ? method.ReflectedType.FullName : "(unknown)";

            return new AirbrakeTraceLine(fileName, lineNumber, method.Name);
        }
 /// <summary>
 ///     Gets the offset from the start of the Microsoft intermediate language (MSIL)
 ///     code for the method that is executing. This offset might be an approximation
 ///     depending on whether or not the just-in-time (JIT) compiler is generating debugging
 ///     code. The generation of this debugging information is controlled by the System.Diagnostics.DebuggableAttribute.
 /// </summary>
 /// <returns>The offset from the start of the MSIL code for the method that is executing.</returns>
 public override int GetILOffset()
 {
     return(StackFrame.GetILOffset());
 }
Beispiel #31
0
        [System.Security.SecurityCritical] // auto-generated
#endif
        internal String ToString(TraceFormat traceFormat)
        {
            bool   displayFilenames = true; // we'll try, but demand may fail
            String word_At          = "at";
            String inFileLineNum    = "in {0}:line {1}";

            if (traceFormat != TraceFormat.NoResourceLookup)
            {
                word_At       = Environment.GetResourceString("Word_At");
                inFileLineNum = Environment.GetResourceString("StackTrace_InFileLineNumber");
            }

            bool          fFirstFrame = true;
            StringBuilder sb          = new StringBuilder(255);

            for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
            {
                StackFrame sf = GetFrame(iFrameIndex);
                MethodBase mb = sf.GetMethod();
                if (mb != null)
                {
                    // We want a newline at the end of every line except for the last
                    if (fFirstFrame)
                    {
                        fFirstFrame = false;
                    }
                    else
                    {
                        sb.Append(Environment.NewLine);
                    }

                    sb.AppendFormat(CultureInfo.InvariantCulture, "   {0} ", word_At);

                    Type t = mb.DeclaringType;
                    // if there is a type (non global method) print it
                    if (t != null)
                    {
                        // Append t.FullName, replacing '+' with '.'
                        string fullName = t.FullName;
                        for (int i = 0; i < fullName.Length; i++)
                        {
                            char ch = fullName[i];
                            sb.Append(ch == '+' ? '.' : ch);
                        }
                        sb.Append('.');
                    }
                    sb.Append(mb.Name);

                    // deal with the generic portion of the method
                    if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod)
                    {
                        Type[] typars = ((MethodInfo)mb).GetGenericArguments();
                        sb.Append('[');
                        int  k             = 0;
                        bool fFirstTyParam = true;
                        while (k < typars.Length)
                        {
                            if (fFirstTyParam == false)
                            {
                                sb.Append(',');
                            }
                            else
                            {
                                fFirstTyParam = false;
                            }

                            sb.Append(typars[k].Name);
                            k++;
                        }
                        sb.Append(']');
                    }

                    ParameterInfo[] pi = null;
#if FEATURE_CORECLR
                    try
                    {
#endif
                    pi = mb.GetParameters();
#if FEATURE_CORECLR
                }
                catch
                {
                    // The parameter info cannot be loaded, so we don't
                    // append the parameter list.
                }
#endif
                    if (pi != null)
                    {
                        // arguments printing
                        sb.Append('(');
                        bool fFirstParam = true;
                        for (int j = 0; j < pi.Length; j++)
                        {
                            if (fFirstParam == false)
                            {
                                sb.Append(", ");
                            }
                            else
                            {
                                fFirstParam = false;
                            }

                            String typeName = "<UnknownType>";
                            if (pi[j].ParameterType != null)
                            {
                                typeName = pi[j].ParameterType.Name;
                            }
                            sb.Append(typeName);
                            sb.Append(' ');
                            sb.Append(pi[j].Name);
                        }
                        sb.Append(')');
                    }

                    // source location printing
                    if (displayFilenames && (sf.GetILOffset() != -1))
                    {
                        // If we don't have a PDB or PDB-reading is disabled for the module,
                        // then the file name will be null.
                        String fileName = null;

                        // Getting the filename from a StackFrame is a privileged operation - we won't want
                        // to disclose full path names to arbitrarily untrusted code.  Rather than just omit
                        // this we could probably trim to just the filename so it's still mostly usefull.
                        try
                        {
                            fileName = sf.GetFileName();
                        }
                        catch (SecurityException)
                        {
                            // If the demand for displaying filenames fails, then it won't
                            // succeed later in the loop.  Avoid repeated exceptions by not trying again.
                            displayFilenames = false;
                        }

                        if (fileName != null)
                        {
                            // tack on " in c:\tmp\MyFile.cs:line 5"
                            sb.Append(' ');
                            sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber());
                        }
                    }

#if FEATURE_EXCEPTIONDISPATCHINFO
                    if (sf.GetIsLastFrameFromForeignExceptionStackTrace())
                    {
                        sb.Append(Environment.NewLine);
                        sb.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow"));
                    }
#endif // FEATURE_EXCEPTIONDISPATCHINFO
                }
            }

            if (traceFormat == TraceFormat.TrailingNewLine)
            {
                sb.Append(Environment.NewLine);
            }

            return(sb.ToString());
        }
Beispiel #32
0
        bool AddFrames(StringBuilder sb)
        {
            bool   printOffset;
            string debugInfo, indentation;
            string unknown = Locale.GetText("<unknown method>");

            indentation = "  ";
            debugInfo   = Locale.GetText(" in {0}:{1} ");

            var newline = String.Format("{0}{1}{2} ", Environment.NewLine, indentation,
                                        Locale.GetText("at"));

            int i;

            for (i = 0; i < FrameCount; i++)
            {
                StackFrame frame = GetFrame(i);
                if (i == 0)
                {
                    sb.AppendFormat("{0}{1} ", indentation, Locale.GetText("at"));
                }
                else
                {
                    sb.Append(newline);
                }

                if (frame.GetMethod() == null)
                {
                    string internal_name = frame.GetInternalMethodName();
                    if (internal_name != null)
                    {
                        sb.Append(internal_name);
                    }
                    else
                    {
                        sb.AppendFormat("<0x{0:x5} + 0x{1:x5}> {2}", frame.GetMethodAddress(), frame.GetNativeOffset(), unknown);
                    }
                }
                else
                {
                    GetFullNameForStackTrace(sb, frame.GetMethod());

                    if (frame.GetILOffset() == -1)
                    {
                        sb.AppendFormat(" <0x{0:x5} + 0x{1:x5}>", frame.GetMethodAddress(), frame.GetNativeOffset());
                        if (frame.GetMethodIndex() != 0xffffff)
                        {
                            sb.AppendFormat(" {0}", frame.GetMethodIndex());
                        }
                    }
                    else
                    {
                        sb.AppendFormat(" [0x{0:x5}]", frame.GetILOffset());
                    }

                    sb.AppendFormat(debugInfo, frame.GetSecureFileName(),
                                    frame.GetFileLineNumber());
                }
            }

            return(i != 0);
        }
        private static string StackFrameToString(StackFrame sf)
        {
            int intParam = 0;
            var sb = new StringBuilder();

            MemberInfo mi = sf.GetMethod();
            {
                //-- build method name
                sb.Append(" ");
                sb.Append(mi.DeclaringType.Namespace);
                sb.Append(".");
                sb.Append(mi.DeclaringType.Name);
                sb.Append(".");
                sb.Append(mi.Name);

                //-- build method params
                ParameterInfo[] objParameters = sf.GetMethod().GetParameters();
                sb.Append("(");
                intParam = 0;
                foreach (var objParameter in objParameters)
                {
                    intParam += 1;
                    if (intParam > 1) sb.Append(", ");
                    sb.Append(objParameter.Name);
                    sb.Append(" As ");
                    sb.Append(objParameter.ParameterType.Name);
                }
                sb.Append(")");
                sb.Append(Environment.NewLine);

                //-- if source code is available, append location info
                sb.Append(" ");

                if (string.IsNullOrEmpty(sf.GetFileName()))
                {
                    sb.Append(Path.GetFileName(GetParentAssembly().CodeBase));

                    //-- native code offset is always available
                    sb.Append(": N ");
                    sb.Append(string.Format("{0:#00000}", sf.GetNativeOffset()));
                }
                else
                {
                    sb.Append(Path.GetFileName(sf.GetFileName()));
                    sb.Append(": line ");
                    sb.Append(string.Format("{0:#0000}", sf.GetFileLineNumber()));
                    sb.Append(", col ");
                    sb.Append(string.Format("{0:#00}", sf.GetFileColumnNumber()));

                    //-- if IL is available, append IL location info
                    if (sf.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
                    {
                        sb.Append(", IL ");
                        sb.Append(string.Format("{0:#0000}", sf.GetILOffset()));
                    }
                }

                sb.Append(Environment.NewLine);
            }

            return sb.ToString();
        }
        private bool TryGetStackFrameInfo(StackFrame/*!*/ frame, out string/*!*/ methodName, out string/*!*/ fileName, out int line) {
            MethodBase method = frame.GetMethod();
            methodName = method.Name;

            fileName = (_hasFileAccessPermission) ? frame.GetFileName() : null;
            var sourceLine = line = frame.GetFileLineNumber();

            if (TryParseRubyMethodName(ref methodName, ref fileName, ref line)) {
                if (sourceLine == 0) {
                    RubyMethodDebugInfo debugInfo;
                    if (RubyMethodDebugInfo.TryGet(method, out debugInfo)) {
                        var ilOffset = frame.GetILOffset();
                        if (ilOffset >= 0) {
                            var mappedLine = debugInfo.Map(ilOffset);
                            if (mappedLine != 0) {
                                line = mappedLine;
                            }
                        }
                    }
                }

                return true;
            } else if (method.IsDefined(typeof(RubyStackTraceHiddenAttribute), false)) {
                return false;
            } else {
                object[] attrs = method.GetCustomAttributes(typeof(RubyMethodAttribute), false);
                if (attrs.Length > 0) {
                    // Ruby library method:
                    // TODO: aliases
                    methodName = ((RubyMethodAttribute)attrs[0]).Name;

                    if (!_exceptionDetail) {
                        fileName = null;
                        line = NextFrameLine;
                    }

                    return true;
                } else if (_exceptionDetail || IsVisibleClrFrame(method)) {
                    // Visible CLR method:
                    if (String.IsNullOrEmpty(fileName)) {
                        if (method.DeclaringType != null) {
                            fileName = (_hasFileAccessPermission) ? method.DeclaringType.Assembly.GetName().Name : null;
                            line = 0;
                        }
                    }
                    return true;
                } else {
                    // Invisible CLR method:
                    return false;
                }
            }
        }
Beispiel #35
0
        internal string ToString(StackTrace.TraceFormat traceFormat)
        {
            bool   flag1  = true;
            string str1   = "at";
            string format = "in {0}:line {1}";

            if (traceFormat != StackTrace.TraceFormat.NoResourceLookup)
            {
                str1   = Environment.GetResourceString("Word_At");
                format = Environment.GetResourceString("StackTrace_InFileLineNumber");
            }
            bool          flag2         = true;
            StringBuilder stringBuilder = new StringBuilder((int)byte.MaxValue);

            for (int index1 = 0; index1 < this.m_iNumOfFrames; ++index1)
            {
                StackFrame frame  = this.GetFrame(index1);
                MethodBase method = frame.GetMethod();
                if (method != (MethodBase)null)
                {
                    if (flag2)
                    {
                        flag2 = false;
                    }
                    else
                    {
                        stringBuilder.Append(Environment.NewLine);
                    }
                    stringBuilder.AppendFormat((IFormatProvider)CultureInfo.InvariantCulture, "   {0} ", (object)str1);
                    Type declaringType = method.DeclaringType;
                    if (declaringType != (Type)null)
                    {
                        stringBuilder.Append(declaringType.FullName.Replace('+', '.'));
                        stringBuilder.Append(".");
                    }
                    stringBuilder.Append(method.Name);
                    if (method is MethodInfo && method.IsGenericMethod)
                    {
                        Type[] genericArguments = method.GetGenericArguments();
                        stringBuilder.Append("[");
                        int  index2 = 0;
                        bool flag3  = true;
                        for (; index2 < genericArguments.Length; ++index2)
                        {
                            if (!flag3)
                            {
                                stringBuilder.Append(",");
                            }
                            else
                            {
                                flag3 = false;
                            }
                            stringBuilder.Append(genericArguments[index2].Name);
                        }
                        stringBuilder.Append("]");
                    }
                    stringBuilder.Append("(");
                    ParameterInfo[] parameters = method.GetParameters();
                    bool            flag4      = true;
                    for (int index2 = 0; index2 < parameters.Length; ++index2)
                    {
                        if (!flag4)
                        {
                            stringBuilder.Append(", ");
                        }
                        else
                        {
                            flag4 = false;
                        }
                        string str2 = "<UnknownType>";
                        if (parameters[index2].ParameterType != (Type)null)
                        {
                            str2 = parameters[index2].ParameterType.Name;
                        }
                        stringBuilder.Append(str2 + " " + parameters[index2].Name);
                    }
                    stringBuilder.Append(")");
                    if (flag1 && frame.GetILOffset() != -1)
                    {
                        string str2 = (string)null;
                        try
                        {
                            str2 = frame.GetFileName();
                        }
                        catch (NotSupportedException ex)
                        {
                            flag1 = false;
                        }
                        catch (SecurityException ex)
                        {
                            flag1 = false;
                        }
                        if (str2 != null)
                        {
                            stringBuilder.Append(' ');
                            stringBuilder.AppendFormat((IFormatProvider)CultureInfo.InvariantCulture, format, (object)str2, (object)frame.GetFileLineNumber());
                        }
                    }
                    if (frame.GetIsLastFrameFromForeignExceptionStackTrace())
                    {
                        stringBuilder.Append(Environment.NewLine);
                        stringBuilder.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow"));
                    }
                }
            }
            if (traceFormat == StackTrace.TraceFormat.TrailingNewLine)
            {
                stringBuilder.Append(Environment.NewLine);
            }
            return(stringBuilder.ToString());
        }
        bool AddFrames(StringBuilder sb)
        {
            bool any_frame = false;

            for (int i = 0; i < FrameCount; i++)
            {
                StackFrame frame = GetFrame(i);

                if (frame.GetMethod() == null)
                {
                    if (any_frame)
                    {
                        sb.Append(Environment.NewLine);
                    }
                    sb.Append(prefix);

                    string internal_name = frame.GetInternalMethodName();
                    if (internal_name != null)
                    {
                        sb.Append(internal_name);
                    }
                    else
                    {
                        sb.AppendFormat("<0x{0:x5} + 0x{1:x5}> <unknown method>", frame.GetMethodAddress(), frame.GetNativeOffset());
                    }
                }
                else
                {
                    GetFullNameForStackTrace(sb, frame.GetMethod(), any_frame, out var skipped);
                    if (skipped)
                    {
                        continue;
                    }

                    if (frame.GetILOffset() == -1)
                    {
                        sb.AppendFormat(" <0x{0:x5} + 0x{1:x5}>", frame.GetMethodAddress(), frame.GetNativeOffset());
                        if (frame.GetMethodIndex() != 0xffffff)
                        {
                            sb.AppendFormat(" {0}", frame.GetMethodIndex());
                        }
                    }
                    else
                    {
                        sb.AppendFormat(" [0x{0:x5}]", frame.GetILOffset());
                    }

                    var filename = frame.GetSecureFileName();
                    if (filename[0] == '<')
                    {
                        var mvid  = frame.GetMethod().Module.ModuleVersionId.ToString("N");
                        var aotid = GetAotId();
                        if (frame.GetILOffset() != -1 || aotid == null)
                        {
                            filename = string.Format("<{0}>", mvid);
                        }
                        else
                        {
                            filename = string.Format("<{0}#{1}>", mvid, aotid);
                        }
                    }

                    sb.AppendFormat(" in {0}:{1} ", filename, frame.GetFileLineNumber());
                }

                any_frame = true;
            }

            return(any_frame);
        }
        // Builds a readable representation of the stack trace, specifying
        // the format for backwards compatibility.
        internal String ToString(TraceFormat traceFormat)
        {
            String word_At       = "at";
            String inFileLineNum = "in {0}:line {1}";

            if (traceFormat != TraceFormat.NoResourceLookup)
            {
                word_At       = Environment.GetResourceString("Word_At");
                inFileLineNum = Environment.GetResourceString("StackTrace_InFileLineNumber");
            }

            bool          fFirstFrame = true;
            StringBuilder sb          = new StringBuilder(255);

            for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
            {
                StackFrame sf = GetFrame(iFrameIndex);
                MethodBase mb = sf.GetMethod();
                if (mb != null)
                {
                    // We want a newline at the end of every line except for the last
                    if (fFirstFrame)
                    {
                        fFirstFrame = false;
                    }
                    else
                    {
                        sb.Append(Environment.NewLine);
                    }

                    sb.AppendFormat(CultureInfo.InvariantCulture, "   {0} ", word_At);

                    Type t = mb.DeclaringType;
                    // if there is a type (non global method) print it
                    if (t != null)
                    {
                        sb.Append(t.FullName.Replace('+', '.'));
                        sb.Append(".");
                    }
                    sb.Append(mb.Name);

                    // deal with the generic portion of the method
                    if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod)
                    {
                        Type[] typars = ((MethodInfo)mb).GetGenericArguments();
                        sb.Append("[");
                        int  k             = 0;
                        bool fFirstTyParam = true;
                        while (k < typars.Length)
                        {
                            if (fFirstTyParam == false)
                            {
                                sb.Append(",");
                            }
                            else
                            {
                                fFirstTyParam = false;
                            }

                            sb.Append(typars[k].Name);
                            k++;
                        }
                        sb.Append("]");
                    }

                    // arguments printing
                    sb.Append("(");
                    ParameterInfo[] pi          = mb.GetParameters();
                    bool            fFirstParam = true;
                    for (int j = 0; j < pi.Length; j++)
                    {
                        if (fFirstParam == false)
                        {
                            sb.Append(", ");
                        }
                        else
                        {
                            fFirstParam = false;
                        }

                        String typeName = "<UnknownType>";
                        if (pi[j].ParameterType != null)
                        {
                            typeName = pi[j].ParameterType.Name;
                        }
                        sb.Append(typeName + " " + pi[j].Name);
                    }
                    sb.Append(")");

                    // source location printing
                    if (sf.GetILOffset() != -1)
                    {
                        // It's possible we have a debug version of an executable but no PDB.  In
                        // this case, the file name will be null.
                        String fileName = null;

                        try
                        {
                            fileName = sf.GetFileName();
                        }
                        catch (SecurityException)
                        {
                        }

                        if (fileName != null)
                        {
                            // tack on " in c:\tmp\MyFile.cs:line 5"
                            sb.Append(' ');
                            sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber());
                        }
                    }
                }
            }

            if (traceFormat == TraceFormat.TrailingNewLine)
            {
                sb.Append(Environment.NewLine);
            }

            return(sb.ToString());
        }
Beispiel #38
0
 /// <summary>
 /// Assert the specified condition, logging result to <see cref="AutoTraceSource.Trace"/>
 /// </summary>
 /// <param name="condition">Condition</param>
 public void Assert(bool condition)
 {
     //Debug.Assert(condition);
     StackFrame sf = new StackFrame(1);
     if (condition)
         Trace.Log(Trace.Level.Verbose, "Assert OK at {0}+{1} (in file {2}:{3},{4}", sf.GetMethod().Name,
             sf.GetILOffset(), sf.GetFileName(), sf.GetFileLineNumber(), sf.GetFileColumnNumber());
     else
         Trace.Log(Trace.Level.Warning, "Assert FAILED at {0}+{1} (in file {2}:{3},{4})", sf.GetMethod().Name,
             sf.GetILOffset(), sf.GetFileName(), sf.GetFileLineNumber(), sf.GetFileColumnNumber());
 }
        private static string StackFrameToString(StackFrame sf)
        {
            var sb = new StringBuilder();
            MemberInfo mi = sf.GetMethod();

            sb.Append("   ");
            sb.Append(mi.DeclaringType.Namespace);
            sb.Append(".");
            sb.Append(mi.DeclaringType.Name);
            sb.Append(".");
            sb.Append(mi.Name);
            
            var objParameters = sf.GetMethod().GetParameters();
            sb.Append("(");
            
            var intParam = 0;
            
            foreach (var objParameter in objParameters)
            {
                intParam++;
                if (intParam > 1)
                {
                    sb.Append(", ");
                }
                sb.Append(objParameter.Name);
                sb.Append(" As ");
                sb.Append(objParameter.ParameterType.Name);
            }
            sb.Append(")");
            sb.Append(Environment.NewLine);
            sb.Append("       ");
            if ((sf.GetFileName() == null) || (sf.GetFileName().Length == 0))
            {
                sb.Append(Path.GetFileName(ParentAssembly().CodeBase));
                sb.Append(": N ");
                sb.Append(string.Format("{0:#00000}", sf.GetNativeOffset()));
            }
            else
            {
                sb.Append(Path.GetFileName(sf.GetFileName()));
                sb.Append(": line ");
                sb.Append(string.Format("{0:#0000}", sf.GetFileLineNumber()));
                sb.Append(", col ");
                sb.Append(string.Format("{0:#00}", sf.GetFileColumnNumber()));
                if (sf.GetILOffset() != -1)
                {
                    sb.Append(", IL ");
                    sb.Append(string.Format("{0:#0000}", sf.GetILOffset()));
                }
            }
            sb.Append(Environment.NewLine);
            
            return sb.ToString();
        }
        private static string BuildLineForStackFrame(StackFrame frame)
        {
            var builder = new StringBuilder("<pre>");
            var method = frame.GetMethod();

            // Special case: no method available
            if (method == null)
            {
                return null;
            }

            // First, write the type name
            var type = method.DeclaringType;
            if (type != null)
            {
                // Special-case ExceptionDispatchInfo.Throw()
                if (type == typeof(ExceptionDispatchInfo) && method.Name == "Throw")
                {
                    return @"<pre><span class=""faded"">--- exception rethrown ---</span></pre>";
                }

                string prefix, friendlyName;
                SplitTypeIntoPrefixAndFriendlyName(type, out prefix, out friendlyName);
                builder.AppendFormat(CultureInfo.InvariantCulture, @"<span class=""faded"">at {0}</span>", HtmlEncodeAndReplaceLineBreaks(prefix));
                builder.Append(HtmlEncodeAndReplaceLineBreaks(friendlyName));
            }

            // Next, write the method signature
            builder.Append(HtmlEncodeAndReplaceLineBreaks("." + method.Name));

            // Is this method generic?
            if (method.IsGenericMethod)
            {
                builder.Append(HtmlEncodeAndReplaceLineBreaks(BuildMethodGenericParametersUnescaped(method)));
            }

            // Build method parameters
            builder.AppendFormat(CultureInfo.InvariantCulture, @"<span class=""faded"">{0}</span>", HtmlEncodeAndReplaceLineBreaks(BuildMethodParametersUnescaped(method)));

            // Do we have source information for this frame?
            if (frame.GetILOffset() != -1)
            {
                var filename = frame.GetFileName();
                if (!string.IsNullOrEmpty(filename))
                {
                    builder.AppendFormat(CultureInfo.InvariantCulture, " in {0}:line {1:D}", HtmlEncodeAndReplaceLineBreaks(filename), frame.GetFileLineNumber());
                }
            }

            // Finish
            builder.Append("</pre>");
            return builder.ToString();
        }
 private string SourceCodeInformation(StackFrame frame)
 {
     if (String.IsNullOrEmpty(frame.GetFileName()))
         return Path.GetFileName(_assemblyInfo.CodeBase) + ": N " + frame.GetNativeOffset();
     return Path.GetFileName(frame.GetFileName()) + ": line " + frame.GetFileLineNumber()
        + ", col " + frame.GetFileColumnNumber() + ", IL " + frame.GetILOffset();
 }