성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
글쓰기
제목
이름
암호
전자우편
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'>C# - 코드를 통해 PDB 심벌 파일 다운로드 방법</h1> <p> 물론 symchk.exe를 이용하면 쉽게 다운로드할 수 있지만,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > pdb 파일을 다운로드하기 위한 symchk.exe 실행에 필요한 최소 파일 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/12091'>http://www.sysnet.pe.kr/2/0/12091</a> </pre> <br /> 관련 DLL들은 재배포 가능할 수 있어도 exe 파일에 대한 언급이 없습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > DbgHelp Versions ; <a target='tab' href='https://learn.microsoft.com/en-us/windows/win32/debug/dbghelp-versions'>https://learn.microsoft.com/en-us/windows/win32/debug/dbghelp-versions</a> </pre> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> 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.<br /> <br /> The DbgHelp.dll file that ships in Windows is not redistributable.<br /> </div><br /> <br /> 그래서 ^^ 그냥 직접 다운로드하는 코드를 만들어 봤습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 기반 지식은 이미 다 정리가 되었습니다. 아래의 글에서 PDB 파일의 경로 구성을 알아봤고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > PDB 기호 파일의 경로 구성 방식 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/2925'>http://www.sysnet.pe.kr/2/0/2925</a> </pre> <br /> 위의 지식을 기반으로 PE 파일로부터 정보를 얻는 방법도 설명했습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - PDB 파일 경로를 PE 파일로부터 얻는 방법 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/11237'>http://www.sysnet.pe.kr/2/0/11237</a> </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;' > PDB 파일을 수동으로 다운로드하는 방법 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/11096'>http://www.sysnet.pe.kr/2/0/11096</a> </pre> <br /> 이제 이것들을 잘 조합하기만 하면 됩니다. 우선, PE 파일의 헤더로부터 Debug Directory를 가져오는 코드를 지난 글에 소개한 예제를 확장해 구현했습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - 로딩된 Native DLL의 export 함수 목록 출력 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/12093'>http://www.sysnet.pe.kr/2/0/12093</a> </pre> <br /> 남은 작업은, 이렇게 구성한 PDB 파일 경로를 이용해 msdl.microsoft.com 심벌 서버로부터 다운로드하는 것인데 이에 대해서는 다음의 글에 소개한,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > PDB Downloader ; <a target='tab' href='https://blogs.msdn.microsoft.com/webtopics/2016/03/07/pdb-downloader/'>https://blogs.msdn.microsoft.com/webtopics/2016/03/07/pdb-downloader/</a> </pre> <br /> PDB Downloader에서 힌트를 얻었습니다. 물론, 소스 코드를 직접 분석하기보다는 그냥 fiddler를 이용해 네트워크 패킷을 보는 것이 더 직관적일 수 있는데요, 우선, "HEAD" method 쿼리를 이용해,<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'>HEAD http://msdl.microsoft.com/download/symbols/ntdll.pdb/0C2E19EA1901E9B82E4567D2D21E56D21/ntdll.pdb HTTP/1.1</span> User-Agent: Microsoft-Symbol-Server/10.0.10522.521 Host: msdl.microsoft.com Connection: Keep-Alive </pre> <br /> 요청을 보내면 다음과 같이 "Location" 헤더에 실제 다운로드할 수 있는 URL이 담겨 옵니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > HTTP/1.1 302 Found Cache-Control: no-store, no-cache, max-age=0 Content-Length: 0 <span style='color: blue; font-weight: bold'>Location</span>: 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 </pre> <br /> 그렇군요, 그러니까 PDB 파일 다운로드는 HEAD + GET의 조합으로 가능하다는 것입니다. (2020-11-23 업데이트: 현재 HEAD 요청 없이 곧바로 다운로드가 가능합니다.) 아래의 소스 코드는 PEImage.cs의 코드를 이용해 PDB 파일을 다운로드하는 예제입니다.<br /> <br /> <pre style='height: 400px; margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // ...[생략]... 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; } } } </pre> <br /> 완전하게 동작하는 코드는 다음의 github에 공개되어 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > DotNetSamples/WinConsole/PEFormat/PEFormatSample/ ; <a target='tab' href='https://github.com/stjeong/DotNetSamples/tree/master/WinConsole/PEFormat/PEFormatSample'>https://github.com/stjeong/DotNetSamples/tree/master/WinConsole/PEFormat/PEFormatSample</a> DotNetSamples/WinConsole/PEFormat/WindowsPE/ ; <a target='tab' href='https://github.com/stjeong/DotNetSamples/tree/master/WinConsole/PEFormat/WindowsPE'>https://github.com/stjeong/DotNetSamples/tree/master/WinConsole/PEFormat/WindowsPE</a> </pre> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1641
(왼쪽의 숫자를 입력해야 합니다.)