summaryrefslogtreecommitdiff
path: root/Runtime/Export/StackTrace.cs
blob: 6e61bd5b5062daa6a601d2351f6b425c0a18a78e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
using System;
using System.Diagnostics;
using System.Text;
using System.Reflection.Emit;
using System.Reflection;
using System.Runtime.Serialization;
using System.Collections;

#if UNITY_WINRT
using SystemException = System.Exception;
#endif

namespace UnityEngine
{
#if !UNITY_WINRT
public class StackTraceUtility
{
	static string projectFolder = "";

	static internal void SetProjectFolder (string folder)
	{
		projectFolder = folder;
	}

	static public string ExtractStackTrace ()
	{
	    StackTrace trace = new StackTrace (1, true);
	    string traceString = ExtractFormattedStackTrace (trace).ToString ();
	    return traceString;
	}
	
	static bool IsSystemStacktraceType (object name)
	{
		string casted = (string)name;
		return casted.StartsWith ("UnityEditor.") || casted.StartsWith ("UnityEngine.") || casted.StartsWith ("System.") || casted.StartsWith ("UnityScript.Lang.") || casted.StartsWith ("Boo.Lang.") || casted.StartsWith ("UnityEngine.SetupCoroutine");
	}

	static public string ExtractStringFromException(System.Object exception)
	{
		string message = "", stackTrace = "";
		ExtractStringFromExceptionInternal(exception, out message, out stackTrace);
		return message + "\n" + stackTrace;
	}

    static internal void ExtractStringFromExceptionInternal(System.Object exceptiono, out string message, out string stackTrace)
	{
        if (exceptiono == null) throw new ArgumentException("ExtractStringFromExceptionInternal called with null exception");
        var exception = exceptiono as System.Exception;
        if (exception == null) throw new ArgumentException("ExtractStringFromExceptionInternal called with an exceptoin that was not of type System.Exception");

		// StackTrace might not be available
		StringBuilder sb = new StringBuilder(exception.StackTrace == null ? 512 : exception.StackTrace.Length*2);
		message = "";
		string traceString = "";
	    while (exception != null)
	    {
			if (traceString.Length == 0)
				traceString	= exception.StackTrace;
			else
				traceString	= exception.StackTrace + "\n" + traceString;
				
			string thisMessage = exception.GetType ().Name;
	    	string exceptionMessage = "";
			if (exception.Message!=null) exceptionMessage = exception.Message;
			if (exceptionMessage.Trim().Length != 0)
			{
				thisMessage += ": ";
				thisMessage += exceptionMessage;	
			}
			message = thisMessage;
			if (exception.InnerException != null)
			{
				traceString = "Rethrow as " + thisMessage + "\n" + traceString;
			}
	    	exception = exception.InnerException;
	    }
	    
		sb.Append (traceString + "\n");

		StackTrace trace = new StackTrace (1, true);
		sb.Append (ExtractFormattedStackTrace (trace));

		stackTrace = sb.ToString();
	}
		
	static internal string PostprocessStacktrace (string oldString, bool stripEngineInternalInformation)
	{
		if (oldString==null) return String.Empty;
		string [] split = oldString.Split ('\n');
		StringBuilder sb = new StringBuilder(oldString.Length);
		for (int i=0; i<split.Length; i++)
			split[i] = split[i].Trim();
		
		for (int i=0; i<split.Length; i++)
		{
			string newLine = split[i];
			
			// Ignore empty lines
			if (newLine.Length == 0 || newLine[0] == '\n')
				continue;
						
			// Ignore unmanaged
			if (newLine.StartsWith ("in (unmanaged)"))
				continue;
			// Make GameView GUI stack traces skip editor GUI part
			if (stripEngineInternalInformation && newLine.StartsWith("UnityEditor.EditorGUIUtility:RenderGameViewCameras"))						break;
			// Ignore deep system stacktraces
			if (stripEngineInternalInformation && i<split.Length-1 && IsSystemStacktraceType(newLine))
			{
				if (IsSystemStacktraceType(split[i+1]))
					continue;
				int lineInfo = newLine.IndexOf(" (at");
				if (lineInfo != -1)
					newLine = newLine.Substring (0, lineInfo);				
			}
			// Ignore wrapper managed to native
			if (newLine.IndexOf ("(wrapper managed-to-native)") != -1)
				continue;
			if (newLine.IndexOf ("(wrapper delegate-invoke)") != -1)
				continue;
			// Ignore unknown method
			if (newLine.IndexOf ("at <0x00000> <unknown method>") != -1)
				continue;
			// Ignore C++ line information
			if (stripEngineInternalInformation && newLine.StartsWith ("[") && newLine.EndsWith("]"))
				continue;
			// Ignore starting at
			if (newLine.StartsWith ("at "))
			{
				newLine = newLine.Remove (0, 3);
			}
						
			// Remove square brace [0x00001]
			int brace = newLine.IndexOf("[0x");
			int braceClose = -1;
			if (brace != -1)
				braceClose = newLine.IndexOf("]", brace);
			if (brace != -1 && braceClose > brace)
			{
				newLine = newLine.Remove (brace, braceClose - brace + 1);
			}
			
			newLine = newLine.Replace("  in <filename unknown>:0", "");
				
			newLine = newLine.Replace(projectFolder, "");

			// Unify path names to unix style
			newLine = newLine.Replace('\\','/');
			
			int inStart = newLine.LastIndexOf ("  in ");
			if (inStart != -1)
			{
				newLine = newLine.Remove(inStart, 5);
				newLine = newLine.Insert(inStart, " (at ");
				newLine = newLine.Insert(newLine.Length, ")");
			}

			sb.Append (newLine+"\n");
		}

		return sb.ToString ();
	}
	
	static internal string ExtractFormattedStackTrace (StackTrace stackTrace)
	{
		StringBuilder sb = new StringBuilder(255);
		int iIndex;
		
		// need to skip over "n" frames which represent the 
		// System.Diagnostics package frames
		for (iIndex=0; iIndex < stackTrace.FrameCount; iIndex++)
		{
			StackFrame frame = stackTrace.GetFrame (iIndex);
			
			MethodBase mb = frame.GetMethod ();
			if (mb == null)
				continue;
								
			Type classType = mb.DeclaringType;
			if (classType == null)
				continue;
			
			// Add namespace.classname:MethodName
			String ns = classType.Namespace;
			if (ns != null && ns.Length != 0)
			{
				sb.Append (ns);
				sb.Append (".");
			}
			
			sb.Append (classType.Name);
			sb.Append (":");
			sb.Append (mb.Name);
			sb.Append ("(");
			
			// Add parameters
			int j=0;
			ParameterInfo[] pi = mb.GetParameters();
			bool fFirstParam = true;
			while (j < pi.Length)
			{
				if (fFirstParam == false)
					sb.Append (", ");
				else
					fFirstParam = false;
				
				sb.Append (pi[j].ParameterType.Name);                
				j++;
			}    
			sb.Append (")");
			
			// Add path name and line number - unless it is a Debug.Log call, then we are only interested
			// in the calling frame.
			string path = frame.GetFileName ();
			if (path != null && !(classType.Name == "Debug" && classType.Namespace == "UnityEngine"))
			{
				sb.Append (" (at ");
				
				if (path.StartsWith (projectFolder))
				{
					path = path.Substring (projectFolder.Length, path.Length - projectFolder.Length);
				}
				sb.Append (path);
				sb.Append (":");
				sb.Append (frame.GetFileLineNumber ().ToString ());
				sb.Append (")");
			}

			sb.Append ("\n");
		}

		return sb.ToString();
	}
}
#endif

[Serializable]
public class UnityException : SystemException
{
	const int Result = unchecked ((int)0x80004003);
	string unityStackTrace;
	
	// Constructors
	public UnityException ()
		: base ("A Unity Runtime error occurred!")
	{
		HResult = Result;
	}

	public UnityException (string message)
		: base (message)
	{
		HResult = Result;
	}

	public UnityException (string message, Exception innerException)
		: base (message, innerException)
	{
		HResult = Result;
	}
#if !UNITY_WINRT
	protected UnityException (SerializationInfo info, StreamingContext context)
		: base (info, context)
	{
	}
#endif
}

[Serializable]
public class MissingComponentException : SystemException
{
	const int Result = unchecked ((int)0x80004003);
	string unityStackTrace;
	
	// Constructors
	public MissingComponentException ()
		: base ("A Unity Runtime error occurred!")
	{
		HResult = Result;
	}

	public MissingComponentException (string message)
		: base (message)
	{
		HResult = Result;
	}

	public MissingComponentException (string message, Exception innerException)
		: base (message, innerException)
	{
		HResult = Result;
	}
#if !UNITY_WINRT
	protected MissingComponentException (SerializationInfo info, StreamingContext context)
		: base (info, context)
	{
	}
#endif
}


[Serializable]
public class UnassignedReferenceException : SystemException
{
	const int Result = unchecked ((int)0x80004003);
	string unityStackTrace;
	
	// Constructors
	public UnassignedReferenceException ()
		: base ("A Unity Runtime error occurred!")
	{
		HResult = Result;
	}

	public UnassignedReferenceException (string message)
		: base (message)
	{
		HResult = Result;
	}

	public UnassignedReferenceException (string message, Exception innerException)
		: base (message, innerException)
	{
		HResult = Result;
	}
#if !UNITY_WINRT
	protected UnassignedReferenceException (SerializationInfo info, StreamingContext context)
		: base (info, context)
	{
	}
#endif
}


[Serializable]
public class MissingReferenceException : SystemException
{
	const int Result = unchecked ((int)0x80004003);
	string unityStackTrace;
	
	// Constructors
	public MissingReferenceException ()
		: base ("A Unity Runtime error occurred!")
	{
		HResult = Result;
	}

	public MissingReferenceException (string message)
		: base (message)
	{
		HResult = Result;
	}

	public MissingReferenceException (string message, Exception innerException)
		: base (message, innerException)
	{
		HResult = Result;
	}
#if !UNITY_WINRT
	protected MissingReferenceException (SerializationInfo info, StreamingContext context)
		: base (info, context)
	{
	}
#endif
}


}