Microsoft MVP성태의 닷넷 이야기
.NET Framework: 873. C# - 코드를 통해 PDB 심벌 파일 다운로드 방법 [링크 복사], [링크+제목 복사]
조회: 10845
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

C# - 코드를 통해 PDB 심벌 파일 다운로드 방법

물론 symchk.exe를 이용하면 쉽게 다운로드할 수 있지만,

pdb 파일을 다운로드하기 위한 symchk.exe 실행에 필요한 최소 파일
; https://www.sysnet.pe.kr/2/0/12091

관련 DLL들은 재배포 가능할 수 있어도 exe 파일에 대한 언급이 없습니다.

DbgHelp Versions
; https://learn.microsoft.com/en-us/windows/win32/debug/dbghelp-versions

The most current versions of DbgHelp.dll, SymSrv.dll, and SrcSrv.dll are available as a part of the Debugging Tools For Windows package. The redistribution policies for these included DLLs were specifically designed to make it as easy as possible for people to include these files in their own packages and releases.

The DbgHelp.dll file that ships in Windows is not redistributable.


그래서 ^^ 그냥 직접 다운로드하는 코드를 만들어 봤습니다.




기반 지식은 이미 다 정리가 되었습니다. 아래의 글에서 PDB 파일의 경로 구성을 알아봤고,

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

위의 지식을 기반으로 PE 파일로부터 정보를 얻는 방법도 설명했습니다.

C# - PDB 파일 경로를 PE 파일로부터 얻는 방법
; https://www.sysnet.pe.kr/2/0/11237

또한, 마이크로소프트의 심벌 서버에서 다운로드하는 방법도 알았으니,

PDB 파일을 수동으로 다운로드하는 방법
; https://www.sysnet.pe.kr/2/0/11096

이제 이것들을 잘 조합하기만 하면 됩니다. 우선, PE 파일의 헤더로부터 Debug Directory를 가져오는 코드를 지난 글에 소개한 예제를 확장해 구현했습니다.

C# - 로딩된 Native DLL의 export 함수 목록 출력
; https://www.sysnet.pe.kr/2/0/12093

남은 작업은, 이렇게 구성한 PDB 파일 경로를 이용해 msdl.microsoft.com 심벌 서버로부터 다운로드하는 것인데 이에 대해서는 다음의 글에 소개한,

PDB Downloader
; https://blogs.msdn.microsoft.com/webtopics/2016/03/07/pdb-downloader/

PDB Downloader에서 힌트를 얻었습니다. 물론, 소스 코드를 직접 분석하기보다는 그냥 fiddler를 이용해 네트워크 패킷을 보는 것이 더 직관적일 수 있는데요, 우선, "HEAD" method 쿼리를 이용해,

HEAD http://msdl.microsoft.com/download/symbols/ntdll.pdb/0C2E19EA1901E9B82E4567D2D21E56D21/ntdll.pdb HTTP/1.1
User-Agent: Microsoft-Symbol-Server/10.0.10522.521
Host: msdl.microsoft.com
Connection: Keep-Alive

요청을 보내면 다음과 같이 "Location" 헤더에 실제 다운로드할 수 있는 URL이 담겨 옵니다.

HTTP/1.1 302 Found
Cache-Control: no-store, no-cache, max-age=0
Content-Length: 0
Location: https://vsblobprodscussu5shard62.blob.core.windows.net/b-4712e0edc5a240eabf23330d7df68e77/73D63042197DD1EE7B80F...[생략]...4cb6588
X-Cache: TCP_MISS
Server: Microsoft-HTTPAPI/2.0
X-MSEdge-Ref: Ref A: 6A044B29569A4FB582D54408AC47B3E5 Ref B: SLAEDGE0919 Ref C: 2019-12-25T03:49:24Z
Date: Wed, 25 Dec 2019 03:49:23 GMT

그렇군요, 그러니까 PDB 파일 다운로드는 HEAD + GET의 조합으로 가능하다는 것입니다. (2020-11-23 업데이트: 현재 HEAD 요청 없이 곧바로 다운로드가 가능합니다.) 아래의 소스 코드는 PEImage.cs의 코드를 이용해 PDB 파일을 다운로드하는 예제입니다.

// ...[생략]...

class Program
{
    static void Main(string[] args)
    {
        // DownloadPdbs(false);
        DownloadPdbs(true);
    }

    private static void DownloadPdbs(bool fromFile)
    {
        string rootPathToSave = Path.Combine(Environment.CurrentDirectory, "sym");
        if (Directory.Exists(rootPathToSave) == false)
        {
            Directory.CreateDirectory(rootPathToSave);
        }

        Process currentProcess = Process.GetCurrentProcess();
        foreach (ProcessModule pm in currentProcess.Modules)
        {
            Console.WriteLine($"[{pm.FileName}, 0x{pm.BaseAddress.ToString("x")}]");

            PEImage pe = null;

            if (fromFile == true)
            {
                pe = PEImage.ReadFromFile(pm.FileName);
            }
            else
            {
                pe = PEImage.ReadFromMemory(pm.BaseAddress, pm.ModuleMemorySize);
            }

            if (pe == null)
            {
                Console.WriteLine("Failed to read images");
                return;
            }

            string modulePath = pm.FileName;
            DownloadPdb(modulePath, rootPathToSave);

            Console.WriteLine();
        }
    }

    private static void DownloadPdb(string modulePath, string rootPathToSave)
    {
        if (File.Exists(modulePath) == false)
        {
            Console.WriteLine("NOT Found: " + modulePath);
            return;
        }

        PEImage pe = PEImage.ReadFromFile(modulePath);
        if (pe == null)
        {
            Console.WriteLine("Failed to read images");
            return;
        }

        Uri baseUri = new Uri("https://msdl.microsoft.com/download/symbols/");

        foreach (CodeViewRSDS codeView in pe.EnumerateCodeViewDebugInfo())
        {
            if (string.IsNullOrEmpty(codeView.PdbFileName) == true)
            {
                continue;
            }

            string pdbFileName = codeView.PdbFileName;
            if (Path.IsPathRooted(codeView.PdbFileName) == true)
            {
                pdbFileName = Path.GetFileName(codeView.PdbFileName);
            }

            Console.WriteLine("\tFileName: " + pdbFileName);
            Console.WriteLine("\tPdbFileName: " + codeView.PdbFileName);
            Console.WriteLine("\tLocal: " + codeView.PdbLocalPath);
            Console.WriteLine("\tUri: " + codeView.PdbUriPath);

            string localPath = Path.Combine(rootPathToSave, codeView.PdbLocalPath);
            string localFolder = Path.GetDirectoryName(localPath);

            if (Directory.Exists(localFolder) == false)
            {
                try
                {
                    Directory.CreateDirectory(localFolder);
                }
                catch (DirectoryNotFoundException)
                {
                    Console.WriteLine("NOT Found on local: " + codeView.PdbLocalPath);
                    continue;
                }
            }

            if (File.Exists(localPath) == true)
            {
                Console.WriteLine("Found on local: " + pdbFileName);
                continue;
            }

            if (CopyPdbFromLocal(modulePath, codeView.PdbFileName, localPath) == true)
            {
                Console.WriteLine("Found on local: " + pdbFileName);
                continue;
            }

            Uri target = new Uri(baseUri, codeView.PdbUriPath);
            Console.WriteLine(target);

            Uri pdbLocation = GetPdbLocation(target);

            if (pdbLocation == null)
            {
                string underscorePath = ProbeWithUnderscore(target.AbsoluteUri);
                pdbLocation = GetPdbLocation(new Uri(underscorePath));
            }

            if (pdbLocation != null)
            {
                DownloadPdbFile(pdbLocation, localPath);
            }
            else
            {
                Console.WriteLine("Not Found on symbol server: " + codeView.PdbFileName);
            }
        }

        Console.WriteLine();
    }

    private static bool CopyPdbFromLocal(string modulePath, string pdbFileName, string localTargetPath)
    {
        if (File.Exists(pdbFileName) == true)
        {
            File.Copy(pdbFileName, localTargetPath);
            return File.Exists(localTargetPath);
        }

        string fileName = Path.GetFileName(pdbFileName);
        string pdbPath = Path.Combine(Environment.CurrentDirectory, fileName);

        if (File.Exists(pdbPath) == true)
        {
            File.Copy(pdbPath, localTargetPath);
            return File.Exists(localTargetPath);
        }

        pdbPath = Path.ChangeExtension(modulePath, ".pdb");
        if (File.Exists(pdbPath) == true)
        {
            File.Copy(pdbPath, localTargetPath);
            return File.Exists(localTargetPath);
        }

        return false;
    }

    private static string ProbeWithUnderscore(string path)
    {
        path = path.Remove(path.Length - 1);
        path = path.Insert(path.Length, "_");
        return path;
    }

    private static void DownloadPdbFile(Uri target, string pathToSave)
    {
        System.Net.HttpWebRequest req = System.Net.WebRequest.Create(target) as System.Net.HttpWebRequest;

        using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse)
        using (FileStream fs = new FileStream(pathToSave, FileMode.CreateNew, FileAccess.Write, FileShare.None))
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            BinaryReader reader = new BinaryReader(resp.GetResponseStream());
            long contentLength = resp.ContentLength;

            while (contentLength > 0)
            {
                byte[] buffer = new byte[4096];
                int readBytes = reader.Read(buffer, 0, buffer.Length);
                bw.Write(buffer, 0, readBytes);

                contentLength -= readBytes;
            }
        }
    }

    private static Uri GetPdbLocation(Uri target)
    {
        System.Net.HttpWebRequest req = System.Net.WebRequest.Create(target) as System.Net.HttpWebRequest;
        req.Method = "HEAD";

        try
        {
            using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse)
            {
                return resp.ResponseUri;
            }
        }
        catch (System.Net.WebException)
        {
            return null;
        }
    }

}

완전하게 동작하는 코드는 다음의 github에 공개되어 있습니다.

DotNetSamples/WinConsole/PEFormat/PEFormatSample/
; https://github.com/stjeong/DotNetSamples/tree/master/WinConsole/PEFormat/PEFormatSample

DotNetSamples/WinConsole/PEFormat/WindowsPE/
; https://github.com/stjeong/DotNetSamples/tree/master/WinConsole/PEFormat/WindowsPE




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/9/2024]

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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  28  [29]  30  ...
NoWriterDateCnt.TitleFile(s)
12894정성태12/30/20217159.NET Framework: 1125. C# - DefaultObjectPool<T>의 IDisposable 개체에 대한 풀링 문제 [3]파일 다운로드1
12893정성태12/27/20218692.NET Framework: 1124. C# - .NET Platform Extension의 ObjectPool<T> 사용법 소개파일 다운로드1
12892정성태12/26/20216677기타: 83. unsigned 형의 이전 값이 최댓값을 넘어 0을 지난 경우, 값의 차이를 계산하는 방법
12891정성태12/23/20216603스크립트: 38. 파이썬 - uwsgi의 --master 옵션
12890정성태12/23/20216742VC++: 152. Golang - (문자가 아닌) 바이트 위치를 반환하는 strings.IndexRune 함수
12889정성태12/22/20219151.NET Framework: 1123. C# - (SharpDX + DXGI) 화면 캡처한 이미지를 빠르게 JPG로 변환하는 방법파일 다운로드1
12888정성태12/21/20217345.NET Framework: 1122. C# - ImageCodecInfo 사용 시 System.Drawing.Image와 System.Drawing.Bitmap에 따른 Save 성능 차이파일 다운로드1
12887정성태12/21/20219381오류 유형: 777. OpenCVSharp4를 사용한 프로그램 실행 시 "The type initializer for 'OpenCvSharp.Internal.NativeMethods' threw an exception." 예외 발생
12886정성태12/20/20217344스크립트: 37. 파이썬 - uwsgi의 --enable-threads 옵션 [2]
12885정성태12/20/20217580오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경
12884정성태12/20/20216651개발 환경 구성: 620. Windows 10+에서 WMI root/Microsoft/Windows/WindowsUpdate 네임스페이스 제거
12883정성태12/19/20217490오류 유형: 775. uwsgi-plugin-python3 환경에서 "ModuleNotFoundError: No module named 'django'" 오류 발생
12882정성태12/18/20216598개발 환경 구성: 619. Windows Server에서 WSL을 위한 리눅스 배포본을 설치하는 방법
12881정성태12/17/20217146개발 환경 구성: 618. WSL Ubuntu 20.04에서 파이썬을 위한 uwsgi 설치 방법 (2)
12880정성태12/16/20216920VS.NET IDE: 170. Visual Studio에서 .NET Core/5+ 역어셈블 소스코드 확인하는 방법
12879정성태12/16/202113143오류 유형: 774. Windows Server 2022 + docker desktop 설치 시 WSL 2로 선택한 경우 "Failed to deploy distro docker-desktop to ..." 오류 발생
12878정성태12/15/20218188개발 환경 구성: 617. 윈도우 WSL 환경에서 같은 종류의 리눅스를 다중으로 설치하는 방법
12877정성태12/15/20216861스크립트: 36. 파이썬 - pymysql 기본 예제 코드
12876정성태12/14/20216704개발 환경 구성: 616. Custom Sources를 이용한 Azure Monitor Metric 만들기
12875정성태12/13/20216432스크립트: 35. python - time.sleep(...) 호출 시 hang이 걸리는 듯한 문제
12874정성태12/13/20216396오류 유형: 773. shell script 실행 시 "$'\r': command not found" 오류
12873정성태12/12/20217517오류 유형: 772. 리눅스 - PATH에 등록했는데도 "command not found"가 나온다면?
12872정성태12/12/20217309개발 환경 구성: 615. GoLang과 Python 빌드가 모두 가능한 docker 이미지 만들기
12871정성태12/12/20217458오류 유형: 771. docker: Error response from daemon: OCI runtime create failed
12870정성태12/9/20216060개발 환경 구성: 614. 파이썬 - PyPI 패키지 만들기 (4) package_data 옵션
12869정성태12/8/20218255개발 환경 구성: 613. git clone 실행 시 fingerprint 묻는 단계를 생략하는 방법
... 16  17  18  19  20  21  22  23  24  25  26  27  28  [29]  30  ...