Microsoft MVP성태의 닷넷 이야기
.NET Framework: 380. 프로세스 스스로 풀 덤프 남기는 방법 [링크 복사], [링크+제목 복사],
조회: 24964
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 6개 있습니다.)
개발 환경 구성: 105. 풀 덤프 파일을 남기는 방법
; https://www.sysnet.pe.kr/2/0/991

.NET Framework: 205. 코드(C#)를 통한 풀 덤프 만드는 방법
; https://www.sysnet.pe.kr/2/0/995

디버깅 기술: 51. 닷넷 응용 프로그램에서 특정 예외가 발생했을 때 풀 덤프 받는 방법
; https://www.sysnet.pe.kr/2/0/1376

.NET Framework: 380. 프로세스 스스로 풀 덤프 남기는 방법
; https://www.sysnet.pe.kr/2/0/1485

.NET Framework: 868. (닷넷 프로세스를 대상으로) 디버거 방식이 아닌 CLR Profiler를 이용해 procdump.exe 기능 구현
; https://www.sysnet.pe.kr/2/0/12049

개발 환경 구성: 462. 시작하자마자 비정상 종료하는 프로세스의 메모리 덤프 - procdump
; https://www.sysnet.pe.kr/2/0/12051




C# - 프로세스 스스로 풀 덤프 남기는 방법

가끔 보면, 필요에 의해서 메모리 덤프를 남겨야 하는 경우가 있습니다. 이때 외부 도구(DebugDiag, Process Dump,...)를 쓰는 것도 가능하지만 최종 사용자에게 이런 도구를 사용하게 하는 것은 어찌 보면 현실성이 없습니다.

그냥 EXE 프로세스 내부에서 일정 조건을 체크하고 스스로 남기게 하거나, 아니면 고객 지원팀에서 쉽게 가이드할 수 있도록 숨겨진 단축키로 기능을 제공하는 것이 더 현실적입니다.

어찌 되었든 프로세스 스스로 덤프를 남길 수 있어야 하는데, 이에 대해서는 예전에 한번 설명을 했었습니다. ^^

코드(C#)를 통한 풀 덤프 만드는 방법
; https://www.sysnet.pe.kr/2/0/995

그때는 외부 프로세스의 덤프를 뜨는 방법을 소개해서 더 복잡했지만, 프로세스 스스로 덤프를 남기는 것은 단지 덤프 파일이 남게 될 대상 폴더에 권한이 있는지 정도만 확인해 주면 됩니다.

소스 코드는 "How to write out a minidump from try/catch in C#?" 글의 내용을 가져다 쓰면 되는데, 제 경우에는 MinidumpWriter 타입으로 정리해 보았습니다.

using System;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;

namespace Utility
{
    public class MinidumpWriter
    {
        [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool IsWow64Process([In] IntPtr processHandle,
             [Out, MarshalAs(UnmanagedType.Bool)] out bool wow64Process);

        [DllImport("kernel32.dll")]
        public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CloseHandle(IntPtr hObject);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr GetCurrentProcess();

        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool OpenProcessToken(IntPtr ProcessHandle,
            UInt32 DesiredAccess, out IntPtr TokenHandle);

        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool LookupPrivilegeValue(string lpSystemName, string lpName,
            out LUID lpLuid);

        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
           [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
           ref TOKEN_PRIVILEGES NewState,
           UInt32 Zero,
           IntPtr Null1,
           IntPtr Null2);

        [DllImport("DbgHelp.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
        private static extern Boolean MiniDumpWriteDump(
                                    IntPtr hProcess,
                                    Int32 processId,
                                    IntPtr fileHandle,
                                    MiniDumpType dumpType,
                                    IntPtr excepInfo,
                                    IntPtr userInfo,
                                    IntPtr extInfo);

        [StructLayout(LayoutKind.Sequential)]
        public struct LUID
        {
            public UInt32 LowPart;
            public Int32 HighPart;
        }

        public enum MiniDumpType
        {
            Normal = 0x00000000,
            WithDataSegs = 0x00000001,
            WithFullMemory = 0x00000002,
            WithHandleData = 0x00000004,
            FilterMemory = 0x00000008,
            ScanMemory = 0x00000010,
            WithUnloadedModules = 0x00000020,
            WithIndirectlyReferencedMemory = 0x00000040,
            FilterModulePaths = 0x00000080,
            WithProcessThreadData = 0x00000100,
            WithPrivateReadWriteMemory = 0x00000200,
            WithoutOptionalData = 0x00000400,
            WithFullMemoryInfo = 0x00000800,
            WithThreadInfo = 0x00001000,
            WithCodeSegs = 0x00002000,
            WithoutAuxiliaryState = 0x00004000,
            WithFullAuxiliaryState = 0x00008000
        }

        private static uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
        private static uint STANDARD_RIGHTS_READ = 0x00020000;
        private static uint TOKEN_ASSIGN_PRIMARY = 0x0001;
        private static uint TOKEN_DUPLICATE = 0x0002;
        private static uint TOKEN_IMPERSONATE = 0x0004;
        private static uint TOKEN_QUERY = 0x0008;
        private static uint TOKEN_QUERY_SOURCE = 0x0010;
        private static uint TOKEN_ADJUST_PRIVILEGES = 0x0020;
        private static uint TOKEN_ADJUST_GROUPS = 0x0040;
        private static uint TOKEN_ADJUST_DEFAULT = 0x0080;
        private static uint TOKEN_ADJUST_SESSIONID = 0x0100;
        private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
        private static uint TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
            TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
            TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
            TOKEN_ADJUST_SESSIONID);

        public const string SE_DEBUG_NAME = "SeDebugPrivilege";

        public const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001;
        public const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002;
        public const UInt32 SE_PRIVILEGE_REMOVED = 0x00000004;
        public const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000;

        [StructLayout(LayoutKind.Sequential)]
        public struct TOKEN_PRIVILEGES
        {
            public UInt32 PrivilegeCount;
            public LUID Luid;
            public UInt32 Attributes;
        }

        [Flags]
        public enum ProcessAccessFlags : uint
        {
            All = 0x001F0FFF,
            Terminate = 0x00000001,
            CreateThread = 0x00000002,
            VMOperation = 0x00000008,
            VMRead = 0x00000010,
            VMWrite = 0x00000020,
            DupHandle = 0x00000040,
            SetInformation = 0x00000200,
            QueryInformation = 0x00000400,
            Synchronize = 0x00100000
        }

        public static bool MakeDump(string dumpFilePath, int processId)
        {
            SetDumpPrivileges();

            Process targetProcess = Process.GetProcessById(processId);
            using (FileStream stream = new FileStream(dumpFilePath, FileMode.Create))
            {
                Boolean res = MiniDumpWriteDump(
                    targetProcess.Handle,
                                    processId,
                                    stream.SafeFileHandle.DangerousGetHandle(),
                                    MiniDumpType.WithFullMemory,
                                    IntPtr.Zero,
                                    IntPtr.Zero,
                                    IntPtr.Zero);

                int dumpError = res ? 0 : Marshal.GetLastWin32Error();
                Console.WriteLine(dumpError);
            }

            CloseHandle(targetProcess.Handle);

            return true;
        }

        private static void SetDumpPrivileges()
        {
            IntPtr hToken;
            LUID luidSEDebugNameValue;
            TOKEN_PRIVILEGES tkpPrivileges;

            if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken))
            {
                Console.WriteLine("OpenProcessToken() failed, error = {0} . SeDebugPrivilege is not available", Marshal.GetLastWin32Error());
                return;
            }

            if (!LookupPrivilegeValue(null, SE_DEBUG_NAME, out luidSEDebugNameValue))
            {
                Console.WriteLine("LookupPrivilegeValue() failed, error = {0} .SeDebugPrivilege is not available", Marshal.GetLastWin32Error());
                CloseHandle(hToken);
                return;
            }

            tkpPrivileges.PrivilegeCount = 1;
            tkpPrivileges.Luid = luidSEDebugNameValue;
            tkpPrivileges.Attributes = SE_PRIVILEGE_ENABLED;

            if (!AdjustTokenPrivileges(hToken, false, ref tkpPrivileges, 0, IntPtr.Zero, IntPtr.Zero))
            {
                Console.WriteLine("LookupPrivilegeValue() failed, error = {0} .SeDebugPrivilege is not available", Marshal.GetLastWin32Error());
                return;
            }

            CloseHandle(hToken);
        }
    }
}

사용법은 다음과 같이 매우 간단합니다.

using System;
using System.Windows.Forms;
using System.Diagnostics;
using Utility;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int pid = Process.GetCurrentProcess().Id;
            MinidumpWriter.MakeDump(@"c:\temp\test.dmp", pid);
        }
    }
}

(첨부된 파일은 위의 예제를 포함한 프로젝트입니다.)

기왕이면 .dmp 파일을 압축해서 지정된 네트워크 서버로 자동 전송하는 것도 구현하면 금상첨화일 것입니다. ^^




덤프를 남겼으면 분석을 해야죠. ^^ 세상이 좋아져서 windbg가 없어도 DebugDiag를 이용하면 쉽게 덤프 분석을 할 수 있습니다.

Debug Diagnostic Tool v1.2 
; http://www.microsoft.com/en-us/download/details.aspx?id=26798

설치하고 나면 윈도우 탐색기에서 확장자가 .dmp인 경우 컨텍스트 메뉴를 이용해 곧바로 분석을 시도할 수 있습니다.

auto_full_dump_1.png

그런데, "Debug Diagnostic Tool (Analysis Only) GUID" 메뉴를 실행해서 분석을 완료하면 결과가 채 나오기도 전에 "ShellExecute failed to display the report. The returned code was 2." 오류 메시지가 나오는 경우도 있습니다. 이에 대한 원인은 다음의 글에 실려 있는데요.

DebugDiag fails to open report (ShellExecute)
; http://forums.iis.net/t/1146219.aspx

따라서, "C:\Program Files\DebugDiag\Reports" 폴더에 대한 "쓰기 권한"을 명시적으로 부여해 주시면 됩니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 4/12/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2014-07-07 03시31분
정성태
2014-09-04 06시56분
[Tip] 프로세스 크래시 발생시 유저덤프 남기기
; http://greemate.tistory.com/entry/Tip-Windows-7에서-유저모드-크래시-덤프-켜기
정성태
2015-11-09 12시11분
C/C++의 경우,

예외 때문에 종료될 때 미니덤프로 정보를 남기는 방법
; (broken) http://sunhyeon.wordpress.com/2015/11/08/예외-때문에-종료될-때-미니덤프로-정보를-남기는-방/
정성태

1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13589정성태3/29/20241202닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241598닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241406오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241687Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241561Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241483개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241516Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241642Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241792개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241321닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241523오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241701닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241965닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241607닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241717닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241640닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241586닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241683닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241783닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241752닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241694닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241808닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241813오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241830오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241691닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241936Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...