성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>.NET 스레드 콜 스택 덤프 (3) - MSE 소스 코드 개선</h1> <p> 지난번 글에서 <a target='tab' href='http://mse.codeplex.com/'>MSE(Managed Stack Explorer) 소스 코드</a>를 이용한 콜 스택 덤프를 얻는 방법을 살펴봤었는데요. 그런데, 정작 그 소스 코드를 실행해 보면 실망하신 분이 있을지도 모르겠습니다. 왜냐하면, 기존의 System.Diagnostics.StackTrace.ToString()과 같은 결과를 보여주지는 않기 때문입니다. 일단, MSE 소스 코드를 이용하면 스택 정보가 Microsoft.Mse.Library.FrameInfo 타입 안에 따로 저장되어 있기 때문에 System.Diagnostics.StackTrace처럼 정보를 나타내려면 다음과 같은 구성이 필요합니다 <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > CorDebugger debugger = new CorDebugger(txt); using (ProcessInfo procInfo = new ProcessInfo(targetProcessId, debugger)) { procInfo.UpdateAllStackTraces(0); foreach (var info in procInfo.ThreadInfos) { Console.WriteLine("================"); <span style='color: blue; font-weight: bold'>foreach (var frame in info.Value.FrameStack)</span> { Console.Write(" at "); Console.Write(frame.FunctionFullName); Console.Write(" in "); Console.Write(frame.FunctionFileName); Console.Write(":line "); Console.WriteLine(frame.FunctionLineNumber); } } } </pre> <br /> 그럼, 결과를 System.Diagnostics.StackTrace와 비교해 볼까요?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > === System.Diagnostics.StackTrace 출력 결과 === at System.IO.__ConsoleStream.ReadFile(SafeFileHandle handle, Byte* bytes, Int32 numBytesToRead, Int32& numBytesRead, IntPtr mustBeZero) at System.IO.__ConsoleStream.ReadFileNative(SafeFileHandle hFile, Byte[] bytes, Int32 offset, Int32 count, Int32 mustBeZero, Int32& errorCode) at System.IO.__ConsoleStream.Read(Byte[] buffer, Int32 offset, Int32 count) at System.IO.StreamReader.ReadBuffer() at System.IO.StreamReader.ReadLine() at System.IO.TextReader.SyncTextReader.ReadLine() at ConsoleApplication1.Program.Wait() in D:\...[생략]...\Program.cs:line 74 at ConsoleApplication1.Program.Run(Object state) in D:\...[생략]...\Program.cs:line 60 at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart(Object obj) === MSE 출력 결과 === at [Internal thisFrame, 'M-->U', System.IO.__ConsoleStream::ReadFile] in :line -1 at System.IO.__ConsoleStream.ReadFileNative in :line -1 at System.IO.__ConsoleStream.Read in :line -1 at System.IO.StreamReader.ReadBuffer in :line -1 at System.IO.StreamReader.ReadLine in :line -1 at System.IO.TextReader.SyncTextReader.ReadLine in :line -1 at ConsoleApplication1.Program.Wait in Program.cs:line 75 at ConsoleApplication1.Program.Run in Program.cs:line 61 at System.Threading.ExecutionContext.Run in :line -1 at System.Threading.ThreadHelper.ThreadStart in :line -1 </pre> <br /> 결정적으로, 해당 메서드의 Parameter 정보와 소스 코드 정보가 없습니다. 이번 글은, 이 2가지 정보를 알 수 있도록 MSE 소스 코드를 개선하는 것이 그 목적입니다. ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 일단, 소스 코드 파일에 대한 정보를 맞추는 것은 간단합니다. 왜냐하면, MSE 소스 코드에서 단순히 FrameInfo에 그 정보를 포함할 수 있었는데도 웬일인지 누락되어 있을 뿐이기 때문입니다.<br /> <br /> 그래서, mseLibrary\FrameInfo.cs 파일의 생성자에서 소스 코드 파일의 전체 경로를 보관하는 변수만 하나 추가해 주면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>string functionFileFullName; public string FunctionFileFullName { get { return functionFileFullName; } }</span> internal FrameInfo(CorFrame frame, CorMetadataImport importer) { ... [생략]... if (functionPos != null) { functionLineNumber = functionPos.Line; functionFileName = Path.GetFileName(functionPos.Path); <span style='color: blue; font-weight: bold'>functionFileFullName = functionPos.Path;</span> } else { ResourceManager stackStrings = new ResourceManager(typeof(Resources)); functionLineNumber = -1;//no line number available functionFileName = stackStrings.GetString("sourceUnavailable"); } } </pre> <br /> 이 결과를 반영해서 다시 예제 코드를 변경하고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > foreach (var info in procInfo.ThreadInfos) { Console.WriteLine("================"); foreach (var frame in info.Value.FrameStack) { Console.Write(" at "); Console.Write(frame.FunctionFullName); if (string.IsNullOrEmpty(frame.FunctionFileFullName) == false) { Console.Write(" in "); <span style='color: blue; font-weight: bold'>Console.Write(frame.FunctionFileFullName);</span> Console.Write(":line "); Console.Write(frame.FunctionLineNumber); } Console.WriteLine(); } } </pre> <br /> 실행해 보면, 결과가 좀 더 근사해집니다. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > === 소스 파일 정보를 포함한 MSE 출력 결과 === at [Internal thisFrame, 'M-->U', System.IO.__ConsoleStream::ReadFile] at System.IO.__ConsoleStream.ReadFileNative at System.IO.__ConsoleStream.Read at System.IO.StreamReader.ReadBuffer at System.IO.StreamReader.ReadLine at System.IO.TextReader.SyncTextReader.ReadLine at ConsoleApplication1.Program.Wait in D:\...[생략]...\Program.cs:line 75 at ConsoleApplication1.Program.Run in D:\...[생략]...\Program.cs:line 61 at System.Threading.ExecutionContext.Run at System.Threading.ThreadHelper.ThreadStart </pre> <br /> 이제 남은 것은 'parameter 정보'군요. ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 처음에 저는, parameter 정보를 받아오는 것이 매우 쉬울 거라 생각했습니다. 왜냐하면, 다음과 같이 Method에 대한 Metadata Token 값을 구할 수 있었고, 이어서 이를 기반으로 .NET Reflection에서의 MethodInfo 정보를 쉽게 얻을 수 있었기 때문입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>string functionArguments; public string FunctionArguments { get { return functionArguments; } } </span> private SourcePosition GetMetaDataInfo(CorMetadataImport importer) { ...[생략]... <span style='color: blue; font-weight: bold'> MethodInfo methodInfo = importer.GetMethodInfo(thisFrame.Function.Token); foreach (var parameterInfo in methodInfo.GetParameters()) { sbParamInfo.Append(parameterInfo.ParameterType); sbParamInfo.Append(" "); sbParamInfo.Append(parameterInfo.Name); sbParamInfo.Append(", "); } functionArguments = sbParamInfo.ToString().TrimEnd(',', ' ');</span> ...[생략]... } </pre> <br /> 이를 반영해서 다음과 같이 예제 코드를 변경하고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > foreach (var info in procInfo.ThreadInfos) { Console.WriteLine("================"); foreach (var frame in info.Value.FrameStack) { Console.Write(" at "); Console.Write(frame.FunctionFullName); <span style='color: blue; font-weight: bold'>Console.Write(string.Format("({0})", frame.FunctionArguments));</span> ...[생략]... } } </pre> <br /> 실행해 보면, 결과는 예상과는 다르게 엉뚱한 출력을 보여줍니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > === 함수의 인자 정보를 포함한 MSE 출력 결과 === at [Internal thisFrame, 'M-->U', System.IO.__ConsoleStream::ReadFile]() at System.IO.__ConsoleStream.ReadFileNative(Type: <span style='color: blue; font-weight: bold'>System.IO.__ConsoleStream</span> hFile, Type: <span style='color: blue; font-weight: bold'>System.IO.__ConsoleStream</span> bytes, Type: <span style='color: blue; font-weight: bold'>System.IO.__ConsoleStream</span> offset, Type: <span style='color: blue; font-weight: bold'>System.IO.__ConsoleStream</span> count, Type: <span style='color: blue; font-weight: bold'>System.IO.__ConsoleStream</span> mustBeZero, Type: <span style='color: blue; font-weight: bold'>System.IO.__ConsoleStream</span> errorCode) at System.IO.__ConsoleStream.Read(Type: <span style='color: blue; font-weight: bold'>System.IO.__ConsoleStream</span> buffer, Type: <span style='color: blue; font-weight: bold'>System.IO.__ConsoleStream</span> offset, Type: <span style='color: blue; font-weight: bold'>System.IO.__ConsoleStream</span> count) at System.IO.StreamReader.ReadBuffer() at System.IO.StreamReader.ReadLine() at System.IO.TextReader.SyncTextReader.ReadLine() at ConsoleApplication1.Program.Wait() in D:\...[생략]...\Program.cs:line 75 at ConsoleApplication1.Program.Run(<span style='color: blue; font-weight: bold'>Type: ConsoleApplication1.Program</span> state) in D:\...[생략]...\Program.cs:line 61 at System.Threading.ExecutionContext.Run(Type: <span style='color: blue; font-weight: bold'>System.Threading.ExecutionContext</span> executionContext, Type: <span style='color: blue; font-weight: bold'>System.Threading.ExecutionContext</span> callback, Type: <span style='color: blue; font-weight: bold'>System.Threading.ExecutionContext</span> state) at System.Threading.ThreadHelper.ThreadStart(Type: <span style='color: blue; font-weight: bold'>System.Threading.ThreadHelper</span> obj) </pre> <br /> 매개 변수의 '이름'은 정상적으로 출력된 반면, 타입이 잘못 출력된 것을 확인할 수 있습니다. 가만히 보면, 매개 변수의 타입이 아니라 해당 메서드를 소유하고 있는 타입의 이름을 출력하는 것을 볼 수 있습니다. 실제로, 디버깅을 이용하여 parameterInfo.MetadataToken 값을 읽어 보면 0이 출력되는 것을 볼 수 있습니다.<br /> <br /> 음... 재미있군요. 그래도 명색이 디버거의 기능인데 무언가 정보를 모두 가져오지 못하는 것 같습니다.<br /> <br /> 아무래도 ICorDebugger와 Reflection의 연동에 문제가 있을까 싶어서 이번에는 순수하게 CorApi에 있는 기능들로 구성을 해보았습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > int argIndex = 0; foreach (var parameterInfo in methodInfo.GetParameters()) { try { GetFunctionClassPath(sbParamInfo, thisFrame.GetArgument(argIndex).ExactType); } catch { } sbParamInfo.Append(" "); sbParamInfo.Append(parameterInfo.Name); sbParamInfo.Append(", "); argIndex++; } </pre> <br /> 실행해 보면, 이번에는 쪼끔(!) 더 나은 결과를 보여주고 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > === 함수의 인자 정보를 포함한 MSE 출력 결과 === at [Internal thisFrame, 'M-->U', System.IO.__ConsoleStream::ReadFile]() at System.IO.__ConsoleStream.ReadFileNative( hFile, bytes, offset, count, mustBeZero, <span style='color: blue; font-weight: bold'>System.Int32&</span> errorCode) at System.IO.__ConsoleStream.Read( buffer, offset, count) at System.IO.StreamReader.ReadBuffer() at System.IO.StreamReader.ReadLine() at System.IO.TextReader.SyncTextReader.ReadLine() at ConsoleApplication1.Program.Wait() in D:\...[생략]...\Program.cs:line 75 at ConsoleApplication1.Program.Run(<span style='color: blue; font-weight: bold'>System.Object</span> state) in D:\...[생략]...\Program.cs:line 61 at System.Threading.ExecutionContext.Run( executionContext, callback, state) at System.Threading.ThreadHelper.ThreadStart( obj) </pre> <br /> 하지만, 극히 일부 매개 변수의 타입만 정상적으로 보여줄 뿐 대단히 실망스러운 결과입니다. 매개변수를 가져오지 못하는 항목들을 만날 때마다 다음과 같은 예외 메시지를 볼 수 있었습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > System.Runtime.InteropServices.COMException was caught Message=An IL variable is not available at the current native IP. (Exception from HRESULT: 0x80131304) Source=CorApi ErrorCode=-2146233596 StackTrace: at Microsoft.Samples.Debugging.CorDebug.NativeApi.ICorDebugILFrame.GetArgument(UInt32 dwIndex, ICorDebugValue& ppValue) at Microsoft.Samples.Debugging.CorDebug.CorFrame.GetArgument(Int32 index) in D:\...[생략]...\Thread.cs:line 502 at Microsoft.Mse.Library.FrameInfo.GetMetaDataInfo(CorMetadataImport importer) in D:\...[생략]...\FrameInfo.cs:line 309 </pre> <br /> 이와 관련해서 검색해 보니 다음의 글이 나오는데요.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > ICorDebugILFrame->GetArgument() wierdness ; <a target='tab' href='http://social.msdn.microsoft.com/Forums/en/netfxtoolsdev/thread/85f54cb7-38d1-42be-b430-d137745b9937'>http://social.msdn.microsoft.com/Forums/en/netfxtoolsdev/thread/85f54cb7-38d1-42be-b430-d137745b9937</a> </pre> <br /> 음... 결국 디버거 측에서 ICorDebugModule2::SetJitCompilerFlags 메서드를 이용하여 해당 닷넷 프로그램이 CORDEBUG_JIT_DISABLE_OPTIMIZATION 옵션이 설정된 체로 실행되어야만 ICorDebugILFrame.GetArgument 메서드가 정상 동작할 수 있다는 것입니다. 아쉽군요. 다른 스레드의 콜 스택을 뜨기 위해서 미리부터 위의 로직을 실행시켜놓고 ICorDebug를 붙여놓는다는 것은 현실적으로 사용할 수 없는 방법에 불과합니다.<br /> <br /> 고민이 되는 문제군요... 혹시 이를 우회할 수 있는 다른 방법이 없을까 생각을 좀 더 해보았습니다. 그러다가, 이번에는 다시 Reflection으로 돌아가서 완전한 Full Version을 사용하는 것으로 방향을 바꿔 보았습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MethodInfo temporaryMethodInfo = importer.GetMethodInfo(thisFrame.Function.Token); MethodInfo methodInfo = null; string typeName = temporaryMethodInfo.DeclaringType.FullName; string methodName = temporaryMethodInfo.Name; int methodToken = temporaryMethodInfo.MetadataToken; <span style='color: blue; font-weight: bold'>Assembly asm = Assembly.LoadFrom(moduleFullName);</span> Type typeTarget = typeTarget = asm.GetType(typeName, false, true); MemberInfo[] memberInfos = null; if (typeTarget != null) { memberInfos = <a target='tab' href='http://www.sysnet.pe.kr/2/0/1161'>typeTarget.GetMember</a>(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); foreach (var memberInfo in memberInfos) { MethodInfo targetInfo = memberInfo as MethodInfo; if (targetInfo == null) { continue; } if (targetInfo.MetadataToken == methodToken) { methodInfo = targetInfo; } } } if (methodInfo != null) { foreach (var parameterInfo in methodInfo.GetParameters()) { sbParamInfo.Append(<span style='color: blue; font-weight: bold'>parameterInfo.ParameterType</span>); sbParamInfo.Append(" "); sbParamInfo.Append(parameterInfo.Name); sbParamInfo.Append(", "); } functionArguments = sbParamInfo.ToString().TrimEnd(',', ' '); } </pre> <br /> 해당 Assembly까지 직접 Load 처리를 하니,,, 오호~~~ 이번에말로 제법 만족할 만한 결과를 얻었습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > === Assembly.LoadFrom을 이용한 MSE 출력 결과 === at [Internal thisFrame, 'M-->U', System.IO.__ConsoleStream::ReadFile]() at System.IO.__ConsoleStream.ReadFileNative(Microsoft.Win32.SafeHandles.SafeFileHandle hFile, System.Byte[] bytes, System.Int32 offset, System.Int32 count, System.Int32 mustBeZero, System.Int32& errorCode) at System.IO.__ConsoleStream.Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) at System.IO.StreamReader.ReadBuffer() at System.IO.StreamReader.ReadLine() at System.IO.TextReader.SyncTextReader.ReadLine() at ConsoleApplication1.Program.Wait() in D:\...[생략]...\Program.cs:line 75 at ConsoleApplication1.Program.Run(System.Object state) in D:\...[생략]...\Program.cs:line 61 at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state) at System.Threading.ThreadHelper.ThreadStart(System.Object obj) </pre> <br /> 목적은 달성할 수 있었지만, 아쉽게도 이 방법을 사용하기 위해서는 주의해야 할 사항이 하나 있습니다. <span style='text-decoration: line-through'>만약 대상 프로그램이 ".NET Framework 2.0 응용 프로그램"이고, 위의 콜 스택을 뜨는 프로그램이 ".NET Framework 4.0 응용 프로그램"이라면 Assembly.Load로 올라오는 BCL 라이브러리의 버전이 상이해져서 CorDebug로부터 얻어오는 MetadataToken 정보가 달라지게 되어 정확한 타입 이름을 얻지 못하게 됩니다.</span> 현재 (또는 기약이 없지만) MSE 소스 코드는 .NET 2.0에 대해서만 지원되고 있습니다. <br /> <span style='text-decoration: line-through'>따라서, 이 때문에 덤프 뜨는 프로그램을 4가지 버전으로 준비해야 합니다.</span> <br /> <ul> <li>dumpx86clr2.exe</li> <li><span style='text-decoration: line-through'>dumpx86clr4.exe</span></li> <li>dumpx64clr2.exe</li> <li><span style='text-decoration: line-through'>dumpx64clr4.exe</span></li> </ul> <br /> 불편하겠지만, '범용적으로 사용하려면' 실행하기 전에 대상 응용 프로그램의 Target Platform 및 CLR 정보를 알아내서 적절한 버전의 dump[...].exe를 실행해 주어야 합니다.<br /> <br /> <a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=640&boardid=331301885'>첨부된 파일은 위의 코드를 포함한 예제 프로젝트</a>입니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
3635
(왼쪽의 숫자를 입력해야 합니다.)