530 likes | 703 Views
Debugging in Windows Env. Feb, 2004 Kim, Hyungsik Consultant hsikkim@microsoft.com Microsoft Korea. 목차. Introduction 문제의 종류 , 디버깅 방법 분류 , 용어설명 , 무엇이 필요한가 ? Debuggers, Debugging Tool list up 디버깅 툴 설치 디렉토리 살펴보기 Exception Flow 이해 Demo : 디버거 설치 덤프 수집하기 덤프 분석하기 주요 상황별 Player 이해
E N D
Debuggingin Windows Env Feb, 2004 Kim, Hyungsik Consultant hsikkim@microsoft.com Microsoft Korea
목차 • Introduction • 문제의 종류, 디버깅 방법 분류, 용어설명, 무엇이 필요한가? • Debuggers, Debugging Tool list up • 디버깅 툴 설치 디렉토리 살펴보기 • Exception Flow 이해 • Demo : 디버거 설치 • 덤프 수집하기 • 덤프 분석하기 • 주요 상황별 Player 이해 • Inetinfo.exe, dllhost.exe, aspnet_wp.exe 등.. • Live Debugging 데모 • 심벌 생성하기 • Debugging 상황별 대처 시나리오 • Art of Debugging • References • Summary
문제(Bug)의 종류 • Crash –비정상종료 • Access Violation –자주 일어나는 케이스 Crash 란 말보다 AV란 말을 더 많이 사용하는 듯.. • Hang –모호한 말, 여러 케이스 • CPU 100% • Lock • IO Pending • Memory Leak • 논리적인 오류 • 그외…
Debugging 이란? • Debugger 및 Debugging Tool를 이용해서 문제를 해결하는 과정 • Debugging 대상에 의한 분류 • Kernel Mode Debugging • Drivers, File Systems, Operating System components • Kernel 의 문제 생기면 블루스크린 • User Mode Debugging • User Application도 문제가 발생할 수 있다. 이 경우 User App만 종료됨. • Debugging 방법에 의한 분류 • Dump Debugging – Dump화일로 분석 • Interactive(Live)Debugging –실행시 Debuggee 에 Attach
용어 설명 • Dump • 특정 시점에 특정 프로세스의 메모리 이미지를 디스크에 적은 것 • Checked Build and Free Build • 디버깅정보를 포함한 버젼 (Checked or Debug Build) • 디버깅정보가 없는 버젼,속도향상 (Free or Release Build) • Exception • 소프트웨어 혹은 하드웨어에서 발생하는 이벤트 • 대부분 Bad Event를 의미하며 대부분 소프트웨어에서 발생함. • First Chance 와 Second Chance로 구별됨. • Symbols • Q121366 • Binary 화일이 메모리에 로드된 주소를 기준으로실제함수명+변수명등의 매칭 기능 제공 • Attach • 디버거가 디버깅 할 대상 프로세스에 Connect하는 것
Debugging을 위해 필요한 것 • Dump 수집기 • Debugger • 심벌 • 소스 코드 위로부터 순차적으로 중요. 심벌이 없어도 일단 어는 모듈이 문제인지는 알수 있고, 소스가 없어도 함수명은 알아낼수 있음.
Debuggers • CDB/NTSD • CDB and NTSD 는 콘솔 어플리케이션임. Windows NT 이상에 사용 가능 • Windbg • GUI 지원하는 디버거 Windows NT, Win2000, WinMe • MSDEV • DevStudio is a GUI based tool ( including a debugger) that allows editing, compiling and debugging programs • All Platform including Win95/98
Dump catchers (덤프 수집기) UserDump (First Chance Exception) • 수동 덤프 수집시 사용 • 자동으로 덤프 수집시에도 사용됨.(Service로 동작) • Doctor Watson (Second Chance) • Drwtsn32, Drwtsn32 -i • 2nd chance exception 발생하여 프로세스 비 정상 종료시 덤프 및 분석로그 생성 • Adplus.vbs (First Chance , Second Chance) • 내부적으로 CDB 사용하여 덤프및 로그 생성 • Adplus –crash –pn inetinfo.exe • Adplus –crash –iis • Adplus –hang –iis • Windbg, CDB 도 커맨드 이용하여 덤프 수집 가능함.
Memleak 관련 툴 • Umdh • 메모리 리크를 알아낼 때 사용됨. • Q268343 • GFlags • Heap Curruption 점검시 사용 • 메모리 리크 점검시도 umdh와 같이 사용
Demo –심벌 및 디버거 설치 • http://www.microsoft.com/whdc/ddk/debugging/default.mspx • 최신 버젼 Debugger 다운로드 가능 • 각종 툴별 Symbol Path 지정하는 법 • CDB, DoctorWatson • _NT_SYMBOL_PATH 환경변수 Windbg • Windbg • 메뉴에서 심벌 패스 지정하면 됨.
Doctor Watson • Auto Debugger 이해하기 • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug • Drwtsn32 • drwtsn32 –i (default debugger로 세팅) • drwtsn32 (설정값 설정화면 로드) • Drwtsn32는 이미 설치되어 있음. 별도의 설치 작업은 필요 없음.
Doctor Watson Log 활용법 • 독립적인 exe 형태의 서비스 demon 같은 프로세스가 이상 종료시 유용하다 • 자체 핸들러가 있어서 2nd chance가 발생하지 않는 경우 (COM+ Compoent, Asp pages, asp.net pages) 에는 잘 사용되지 않는다. • 꼭 덤프를 분석해야만 문제를 해결할수 있는 것은 아니다. • Doctor Watson Log도 충분히 활용하면 문제를 쉽게 해결할 수 있다. • Log는 누적되므로 이전에 문제 생겼던 정보도 알수 있다. • Log에서 정확한 모듈명+함수명을 보여줄려면 미리 심벌패스가 _NT_SYMBOL_PATH에 설치되어 있어야 한다. • 자체 핸들러가 없어서 이상 종료 하는 프로세스의 덤프 수집할려면 이게 좋은 방법 • 2nd Chance Exception 수집
Userdump 사용해보기 • Userdump 툴은 서비스로 동작하여 원하는 프로세스를 감시할 수 있다. • 특정 Exception을 지정할 수 있다. 보통 AV만 지정하여 감시한다. • 수동으로 덤프수집도 가능하다.- 행 덤프시 사용 • Q241215 에서 다운로드 할수 있음. (디버깅 툴과는 별도 설치 필요함.)
Userdump • 수동 덤프 수집 • Userdump가 설치된 디렉토리에서 아래와 같이 키인 • Userdump –p • 전체 프로세스 리스트 함. • Userdump 1132 1132.dmp • Pid 1132 덤프 수집하여 1132.dmp 화일로 저장 • Userdump notepad.exe notepad.dmp • Notepad.exe 프로그램 덤프 수집하여 notepad.dmp로 저장 • 수동 덤프 수집후 대상 application 계속 런닝됨. • 1st chance Exception 수집
Adplus.vbs 사용하기 • Debugging 툴에 포함된 유틸리티 • 내부적으로는 cdb를 사용하여 특정 App의 1st Exception 및 2nd Exception에 반응하도록 코딩 되어 있음. • Vbs 화일의 내용을 고쳐서 동작을 커스터마이즈 할수 있음. • 1st Exception 시에도 Full Dump 받으라고 할수 있음. • -crash mode는 Local Console에서만 가능 (터미날 에서는 작동할 수 없음)
WinDBG 와 친숙해지기 • Attaching to a Process • Starting a Process • Reading a Dump File • Common Commands • k for stacK • lm for list modules • ~ lists all threads • ~ <thread number> changes to a specific thread number • ~*kb lists the stacks for all threads in a process • g Go (Start the process again)
Basic Debugging Commands • K,Kb,kp • To list the current thread • ~*k • To list all the thread • R • To dump the registers • Dd <address> • Dump in DWORD from the specified address • Dv • Dump local variables
Basic Debugging Commands (2) • !locks • To determine if there are any critical section deadlocks • !peb • To dump process environment block • !reload • To reload the symbols • U • Display in Disassembly
Demo – Open CrashDump Using WinDBG to view a .DMP file generated by UserDump or Dr. Watson
Demo – Attach Process Attaching Process기본 명령어 사용해 보기 kb, ~*kb, Call Stack, go Breakpoint 사용해 보기 bp, bl, bcSymbol Path 재 지정후 다시로드.reload Exception Flow 보여주기
Exception 이해 AdPlus 1st ,Userdump 디버거 1st Chance Exception 알림 Kernel Debugger가 처리하지 않으면 Exception Handler 찾음 1 Handler Y/N? 2nd Chance Exception 알림 Exception 발생 Debugger가 처리하지 않으면 프로세스 종료 2 AdPlus 2nd,DoctorWatson Program 종료 Program 계속
Understanding Key Players • Asp, Asp.net 환경에서 Process 연관도 이해하기. • Virtual Dir 설정에 따른 프로세스 연관도 이해 • COM+ 사용시 Exception Flow 이해
IIS WebService 이해 • Debugging 대상을 이해하기 위해서 IIS Webservice 환경 이해 필요 • 실행환경별 구분 • InProcess (inetinfo) • Isolated (독자적 Dllhost) • Pooled out of Process (Pooled Dllhost, Default)
DLLHOST.EXE ISAPI PoolThreadLimit (2 x # MB) MaxPoolThreads (4 x CPUs) ASP ASP ASP COM+ Application APP APP APP APP HTTP GIF GET Initial: Number of CPUs + 7 HTM DLLHOST.EXE Web Application Architecture IIS Pool Threads SMTP FTPSVC W3SVC Web Application Manager INETINFO.EXE Port 80
호출상황별 Exception Flow • AV InProc 컴포넌트 called by User Win32 Process • 1st chance Exception 발생 • 핸들러 있으면 계속 수행, 없으면 2nd Chance 발생. 프로그램 종료 • AV InProc 컴포넌트 called by ASP 페이지 • Asp 혹은 Asp.net은 기본적으로 자체 핸들러 있음. • 1st chance 만 발생후 계속 수행 • AV Com+ 컴포넌트(dllhost.exe) called by User Application • COM+ Failfast 동작 • Com+의 Dllhost.exe 에서 1st Chance만 발생후 dllhost.exe 종료 • User Application은 핸들러 없으면 종료, 있으면 계속 수행 • AV Com+ 컴포넌트 (dllhost.exe) called by Asp페이지 • COM+ Failfast 동작 • Com+의 Dllhost.exe 에서 1st Chance만 발생후 dllhost.exe 종료 • Asp페이지는 시스템 기본 에러 핸들러 따라감.
COM+ Failfast • HKEY_LOCAL_MACHINE\Software\Microsoft\COM3 • Add Key to create a new key named Debug. • Under the newly created key, click Add Value on the Edit menu to add a string value named DebugBreakOnFailFast, and then click OK. • Set the value of the new string to Y. • When the COM+ application failfasts, it displays the Assertion Failed dialog box. At this point, you can obtain a dump with Userdump.
Developer Tools – VB 6.0 • Visual Basic 6.0 • Component Creation • ActiveX DLL or ActiveX EXE • Threading Models Supported • Apartment Model (STA) • Single • Symbols • Can be generated by checking the “Symbolic Debug Information” checkbox • Recommendations • “Unattended Execution” and “Retain In Memory” must be checked when using components within IIS/MTS environment (Q241896)
VB Compile Option “Unattended Execution” and “Retain In Memory” must be checked when using components within IIS/MTS environment (Q241896) http://support.microsoft.com/default.aspx?scid=kb;en-us;286036
VB Component 컴파일 옵션 점검 툴 • SAMPLE: Using VBCHKW2K to Isolate DLLs Compiled Without Retain In Memory and Unattended Execution • http://support.microsoft.com/default.aspx?scid=kb;en-us;286036
Developer Tools • Visual C++ 6.0 • Component Creation • Use the ATL Wizard • Threading Models Supported • Apartment, Free, Both, Both w/ FTM • Symbols • Debug builds by default • Release builds Link Debug under Project Settings.. • Production 서버에 올라간 버젼은 대부분 Release Mode일 것임. 그러면 Release 모드에서 Debug Symbol을 만들어야 함.
디버깅 시나리오 • Crash (AV) • High CPU Utilization • Memory Leak • Art of Debugging
Scenario 1: Access Violations • 일반적인 원인 • Null pointer assignment/access • Stray pointers pointing to invalid memory • Array indices going out of range • Non thread safe components in multithreaded environment • For Visual Basic COM DLLs – unattended execution and retain in memory is not set
Scenario 1: Access Violations (2) • Dump를 수집 • (DrWatson , Userdump, adplus.vbs) • Windbg 로 덤프 연다. • 문제를 일으킨 쓰레드의 call stack 본다. • 문제를 일으킨 소스를 review한다.
Scenario 2: High CPU Utilization • CPU를 많이 사용하는 프로세스를 찾아내라. • 성능모니터 이용 아래 카운터 사용 • % processor time • Process ID
Scenario 2: High CPU Utilization (2) • 성능로그에서, 문제가되는 프로세스의 쓰레드별로 CPU 사용량을 측정하라. (스레드 ID도 로깅) • Add following counter • Object = thread • Counter = ID thread • Instance = highest CPU consuming process
Scenario 2: High CPU Utilization (3) • 문제가 되는 스레드 ID를 알아낸다. • UserDump를 사용하여 문제프로세스의 덤프를 받는다. • userdump <process ID> <dump file name> • Windbg로 덤프를 연후 문제가 된 쓰레드의 콜스택을 본다. • 문제가되는 함수의 소스를 Review한다.
Art of Debugging • 고객의 말은 반만 믿어라. • 자신이 정확한 현상 데이타를 보기전에는 고객의 말은 참조만 하라. 잘못된 현상 정의로 인해 많은 시간이 소요되고는 한다. • 버그의 재현 절차를 알아내라. • 버그의 재현을 성공한다면 이미 그 버그는 반은 풀린 것이다. • 버그를 잘 설명할수 있어야 한다. • 그냥 “이상해요”, “불안해요”라는 말을 다음의 말로 바꾼다. • 5명 이상의 사용자가 2시간 사용후 inetinfo.exe 가 Hang이 걸린다. • 복잡한 문제라면 여러개의 단일 문제로 나눈다. • 버그는 하나가 아닐수 있다. 하나씩 풀어 나가면 된다. • 내가 버그를 잘 설명할 수 있을때 동료들이 도와줄수 있는 것이다.
Art of Debugging (continued) • 도구를 잘 이해하고 적절한 도구를 사용해야 한다. • 덤프 수집이 필요한 버그인가? 소스코드 Review가 필요한 버그인가? • Exception Flow 를 이해하는 것은 중요하다. • 조심해야 할 상황 • “혼자 사용할때는 문제 없는데, 여럿이 사용하면 에러가 납니다.” • 정말로 동시성 문제일까? 사용자 A로만 테스트 하였고 사용자 B는 잘못된 데이타를 가지고 있어서 난 에러였다. 데이타 에러였던 것이다. • 고객이 시스템 오픈전에 동시 사용자 테스트를 하였는지 확인할 필요가 있다. • “동시성 테스트도 마쳤습니다.” • 과연 서로 다른 정보를 넣어서 테스트 했을까? 대부분의 동시 사용자 테스트는 1인의 정보를 그대로 카피해서 하는 경우가 많다. • 새로운 기능을 추가한 뒤 부터 문제가 발생합니다. • 이런 경우 새로운 기능과는 전혀 관련이 없는 곳에서의 조작 미스가 원인 일수도 있습니다.
References • 중요 디버깅 툴 다운로드 • http://www.microsoft.com/ddk - 디버깅 툴 (windbg, cdb, autodump+) • http://support.microsoft.com/default.aspx?scid=kb;en-us;241215– userdump • http://www.sysinternals.com– Process Explorer 및 각종 툴 • Win32 Debugging Articles Microsoft Debugging Tools Knowledge Base Articles http://www.microsoft.com/ddk/debugging/DBG-KB.asp • 메모리 리크 Tool 및 사용법Umdhtools.exe: How to Use Umdh.exe to Find Memory Leakshttp://support.microsoft.com/default.aspx?scid=kb;en-us;268343 • 디버거 없이 비정상 종료 지점 알아내기 (for Win9x)HOWTO: Determine the Location of a Crash http://support.microsoft.com/default.aspx?scid=kb;en-us;196755 • 프로그램 스스로 예외 발생시 call stack 정보 기록하기 (win9x에서도 가능) • http://msdn.microsoft.com/msdnmag/issues/02/03/hood/default.aspx
References • VB COM+ 컴포넌트작성시 주의할 점. PRB: Visual Basic DLL Has Memory Leaks and Crashes in COM+ If 'Retain In Memory' Is Not Set • http://support.microsoft.com/default.aspx?scid=kb;en-us;264957 • VB COM+ 컴포넌트 빌드 옵션 점검 툴 (Windows 2000용) SAMPLE: Using VBCHKW2K to Isolate DLLs Compiled Without Retain In Memory and Unattended Execution • http://support.microsoft.com/default.aspx?scid=kb;en-us;286036 • VC++ 6.0 프로젝트용 디버깅 정보 생성하는 법 (Release Mode에서) HOWTO: Create Debug Symbols for a Visual C++ Application • http://support.microsoft.com/default.aspx?scid=kb;en-us;291585 • Win32 App환경에서 audodump+ 사용하는 법 HOWTO: Use Autodump+ to Troubleshoot "Hangs" and "Crashes" • http://support.microsoft.com/default.aspx?scid=kb;en-us;286350 • HOWTO: Obtain a Userdump When COM+ Failfasts COM+ Failfast 이해 및 COM+ Component crash시 덤프 수집 방법 • http://support.microsoft.com/default.aspx?scid=kb;en-us;287643