Microsoft MVP성태의 닷넷 이야기
.NET Framework: 663. C# - PDB 파일 경로를 PE 파일로부터 얻는 방법 [링크 복사], [링크+제목 복사]
조회: 14699
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 5개 있습니다.)

C# - PDB 파일 경로를 PE 파일로부터 얻는 방법

아래와 같은 질문이 나온 김에,

서드파티 dll 디버깅에 대해 질문드립니다.
; https://www.sysnet.pe.kr/3/0/4852

PE(Portable Executables) 포맷에 대한 지식도 넓힐 겸, PE 바이너리 파일로부터 연관된 PDB 파일 경로를 얻는 방법을 알아보겠습니다. ^^

Visual Studio에서 다음과 같은 단순 프로젝트를 빌드한 후,

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine();
        }
    }
}

PEViewer 등을 통해 확인해 보면 "IMAGE_DEBUG_DIRECTORY"가 있는 것을 확인할 수 있습니다.

pe_debug_pdb_1.png

위의 내용에서 "Pointer to Raw Data" == "0x83C"이고 그 위치에는 "IMAGE_DEBUG_TYPE_CODEVIEW" 타입의 데이터가 위치해 있습니다.

pe_debug_pdb_2.png




그럼, 코드를 통해 이 값들을 추적해 볼까요? ^^

우선 PE 파일을 다룰 수 있는 라이브러리를 Nuget으로부터 추가한 후,

Install-Package Workshell.PE -Version 1.7.0

// 또는 직접 만들거나,
libpe - PE32/PE32+ Binaries Viewer Library
; https://www.codeproject.com/Articles/5205732/libpe-PE32-PE32plus-Binaries-Viewer-Library

IMAGE_DEBUG_DIRECTORY를 다음과 같이 가져올 수 있지만,

Workshell.PE.ExecutableImage pe = Workshell.PE.ExecutableImage.FromFile("ConsoleApp1.exe");

foreach (var item in pe.NTHeaders.DataDirectories)
{
    if (item.DirectoryType == Workshell.PE.DataDirectoryType.Debug)
    {
        ShowDebugDirectoryInfo(pe, item);
        return;
    }
}

private static void ShowDebugDirectoryInfo(Workshell.PE.ExecutableImage pe, DataDirectory item)
{
    Console.WriteLine("Debug directory: ");
    Console.WriteLine("\t RVA: " + item.VirtualAddress.ToString("x"));
    Console.WriteLine("\t Size: " + item.Size.ToString("x"));
           
    LocationCalculator calc = pe.GetCalculator();

    ulong offset = calc.RVAToOffset(item.VirtualAddress);
    // offset == IMAGE_DEBUG_TYPE_CODEVIEW 영역을 가리키는 파일의 위치

    // var textSection = item.GetSection();
    // offset = item.VirtualAddress - textSection.Location.RelativeVirtualAddress + textSection.Location.FileOffset;
}

그냥 이렇게 간단하게 구하는 방법도 제공해 주고 있습니다. ^^

Workshell.PE.ExecutableImage pe = Workshell.PE.ExecutableImage.FromFile("ConsoleApp1.exe");

DebugDirectory debugDir = DebugDirectory.Get(pe);
DebugDirectoryEntry debugEntry = debugDir[0]; // debugEntry == IMAGE_DEBUG_DIRECTORY 데이터

IMAGE_DEBUG_DIRECTORY가 가리키는 IMAGE_DEBUG_TYPE_CODEVIEW의 데이터를 구해오는 방법은 debugEntry.PointerToRawData가 가리키는 파일 위치의 데이터를 debugEntry.SizeOfData 만큼 읽어오면 됩니다. 하지만, Workshell.PE 라이브러리는 이에 대한 것도 다음과 같이 간단하게 가져오는 방법을 제공합니다.

DebugData debugData = DebugData.Get(debugEntry);
byte [] buf = debugData.GetBytes(); // buf == IMAGE_DEBUG_TYPE_CODEVIEW 데이터

위의 buf 내용은 PEView 도구를 통해 본 IMAGE_DEBUG_TYPE_CODEVIEW의 데이터와 일치합니다.

그렇다면 이제부터 buf 내용을 분석해 봐야 할 텐데, 이에 대해서는 다음의 글에 포맷과 함께 자세한 설명이 있습니다.

Matching debug information
; http://www.debuginfo.com/articles/debuginfomatch.html

위의 문서에 보면 IMAGE_DEBUG_DIRECTORY가 n 개의 IMAGE_DEBUG_TYPE_CODEVIEW를 가지고 있다는 것을 알 수 있습니다.

[그림 출처: http://www.debuginfo.com/articles/debuginfomatch.html]
pe_debug_pdb_3.gif

그렇다면, 우리의 코드가 다음과 같이 바뀌어야겠군요. ^^

static void Main(string[] args)
{
    Workshell.PE.ExecutableImage pe = Workshell.PE.ExecutableImage.FromFile("ConsoleApp1.exe");

    DebugDirectory debugDir = DebugDirectory.Get(pe);

    foreach (var debugEntry in debugDir)
    {
        if (debugEntry.Type == 2) // 2 == IMAGE_DEBUG_TYPE_CODEVIEW
        {
            ShowDebugData(debugEntry);
            Console.WriteLine();
        }
    }
}

private static void ShowDebugData(DebugDirectoryEntry debugEntry)
{
    DebugData debugData = DebugData.Get(debugEntry);
    byte [] buf = debugData.GetBytes();

    Console.WriteLine(debugEntry.GetEntryType() + ": Len == " + buf.Length);
}

IMAGE_DEBUG_DIRECTORY가 포함한 디버그 정보가 IMAGE_DEBUG_TYPE_CODEVIEW 타입인 경우 해당 CodeView 구조는 첫 번째 4바이트의 Signature로 구별할 수 있는 다양한 버전이 존재합니다.

"NB09" - CodeView 4.10 (디버그 정보가 실행 파일 안에 있는 경우)
"NB11" - CodeView 5.0 (디버그 정보가 실행 파일 안에 있는 경우)
"NB10" - PDB 2.0 파일을 가리키는 경우
"RSDS" - PDB 7.0 파일을 가리키는 경우

(참고로, PDB가 아닌 DBG 파일에 보관된 경우 디버그 정보의 타입은 IMAGE_DEBUG_TYPE_MISC)

그런데... NB10을 보니 어디선가 낯이 익습니다. 오호~~~ 예전에 한번 살펴본 글이 있습니다. ^^

PDB 기호 파일의 경로 구성 방식
; https://www.sysnet.pe.kr/2/0/2925

그러니까, 이 글에서 만들고 있는 코드들이 결국 위의 글에서 소개한 "debugdir.zip"에 담긴 C++ 소스 코드의 C# 버전이었던 것입니다.

C++ 소스 코드를 보면 CodeView 구조 중 NB10과 RSDS를 다음과 같이 포함하고 있습니다.

#define CV_SIGNATURE_NB10   '01BN'
#define CV_SIGNATURE_RSDS   'SDSR'

// CodeView header 
struct CV_HEADER
{
    DWORD CvSignature; // NBxx
    LONG  Offset;      // Always 0 for NB10
};

// CodeView NB10 debug information 
// (used when debug information is stored in a PDB 2.00 file) 
struct CV_INFO_PDB20
{
    CV_HEADER  Header;
    DWORD      Signature;       // seconds since 01.01.1970
    DWORD      Age;             // an always-incrementing value 
    BYTE       PdbFileName[1];  // zero terminated string with the name of the PDB file 
};

// CodeView RSDS debug information 
// (used when debug information is stored in a PDB 7.00 file) 
struct CV_INFO_PDB70
{
    DWORD      CvSignature;
    GUID       Signature;       // unique identifier 
    DWORD      Age;             // an always-incrementing value 
    BYTE       PdbFileName[1];  // zero terminated string with the name of the PDB file 
};

C# 코드도 저 규칙에 맞게 스트림 데이터를 읽어 변환해 주면 됩니다. 다음은, 이 글에서 첨부한 실행 파일의 사용 예입니다.

PE File: ConsoleApp1.exe
No IMAGE_DEBUG_DIRECTORY

PE File: PDBInfoFromPE.exe
CodeView Info Type: RSDS
Signature: 65c91292-efaf-448f-ae22-c45caa840f59, Age: 1, Path: F:\cloud_drive\Dropbox\articles\pdb_create\PDBPathFromPE\PDBInfoFromPE\obj\Debug\PDBInfoFromPE.pdb
PDB Download Path: \PDBInfoFromPE.pdb\65c91292efaf448fae22c45caa840f591\PDBInfoFromPE.pdb

PE File: msvcirt.dll
CodeView Info Type: NB10
Signature: 1048575954, Age: 1, Path: msvcirt.pdb
PDB Download Path: \msvcirt.pdb\10485759541\msvcirt.pdb

위에서 ConsoleApp1.exe의 경우 IMAGE_DEBUG_DIRECTORY가 없다고 나오는데, C# 프로젝트 설정의 "Build" / "Advanced" - "Output" / "Debugging information" 옵션을 "none"으로 주면 "IMAGE_DEBUG_DIRECTORY"가 생성되지 않기 때문입니다.

또한, "PDB Donwload Path"라는 경로를 부가적으로 출력하고 있는데 이는 "PDB 기호 파일의 경로 구성 방식" 글에서 설명한 규칙을 반영한 것입니다.

(첨부 파일은 이 글의 완전한 코드를 포함합니다.)




시간 나시면 다음의 글도 한번 읽어보세요. ^^

PDB Symbol 로드 오류 - Cannot find or openthe PDB file.
; https://www.sysnet.pe.kr/2/0/987

결국, 이 글의 소스 코드와 함께 PDB 파일로부터 Signature/Age 정보를 읽어내는 코드를 추가하면 위의 글에서 소개한 ChkMatch 프로그램도 만들 수 있습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/26/2023]

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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13606정성태4/24/202498닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024328닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024349오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024603닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024797닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024838닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024848닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024862닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024884닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024867닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241052닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241050닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241068닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241079닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241218C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241196닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241150닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241263닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241168오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241329Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241112Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241063개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241302Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241559Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...