Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 13개 있습니다.)
디버깅 기술: 22. VS.NET SP1 + .NET Framework 소스 코드 디버깅
; https://www.sysnet.pe.kr/2/0/623

개발 환경 구성: 112. Visual Studio 2010 - .NET Framework 소스 코드 디버깅
; https://www.sysnet.pe.kr/2/0/1009

개발 환경 구성: 143. Visual Studio 2010 - .NET Framework 소스 코드 디버깅 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1243

개발 환경 구성: 297. 소스 코드가 없는 닷넷 어셈블리를 디버깅할 때 지역 변숫값을 확인하는 방법
; https://www.sysnet.pe.kr/2/0/11036

개발 환경 구성: 391. (GitHub 등과 직접 연동해) 소스 코드 디버깅을 쉽게 해 주는 SourceLink
; https://www.sysnet.pe.kr/2/0/11630

VS.NET IDE: 126. 디컴파일된 소스에 탐색을 사용하도록 설정(Enable navigation to decompiled sources)
; https://www.sysnet.pe.kr/2/0/11689

VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
; https://www.sysnet.pe.kr/2/0/12200

개발 환경 구성: 500. (PDB 연결이 없는) DLL의 소스 코드 디버깅을 dotPeek 도구로 해결하는 방법
; https://www.sysnet.pe.kr/2/0/12281

VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할
; https://www.sysnet.pe.kr/2/0/12401

VS.NET IDE: 170. Visual Studio에서 .NET Core/5+ 역어셈블 소스코드 확인하는 방법
; https://www.sysnet.pe.kr/2/0/12880

VS.NET IDE: 177. 비주얼 스튜디오 2022를 이용한 (소스 코드가 없는) 닷넷 모듈 디버깅 - "외부 원본(External Sources)"
; https://www.sysnet.pe.kr/2/0/13109

VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
; https://www.sysnet.pe.kr/2/0/13247

VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
; https://www.sysnet.pe.kr/2/0/13554




(GitHub 등과 직접 연동해) 소스 코드 디버깅을 쉽게 해 주는 SourceLink

지난 글들에서 .NET Core 2.1에 도입된 기능 소개에 이어,

.NET Core 2.1 - 확장 도구(Tools) 관리
; https://www.sysnet.pe.kr/2/0/11538

.NET Core 2.1 - Tiered Compilation 도입
; https://www.sysnet.pe.kr/2/0/11539

이번에는 SourceLink라는 것에 대해 알아보겠습니다.

Announcing .NET Core 2.1 - SourceLink
; https://devblogs.microsoft.com/dotnet/announcing-net-core-2-1/

dotnet/sourcelink 
; https://github.com/dotnet/sourcelink

(* 문서에 의하면 .NET Core 쪽으로만 지원하는 듯이 씌여져 있지만,
현재 .NET Full Framework을 대상으로 한 프로젝트들에서도 문제 없이 적용할 수 있습니다.)

사실 디버깅 중에 소스 코드와 매칭시키는 것은 pdb 파일을 통해 소스 서버로의 링크를 제공하는 것으로 예전부터 가능했습니다.

TFS Team Build + Source Server = 소스 코드 디버깅
; https://www.sysnet.pe.kr/2/0/600

TFS 2010의 소스 서버 수작업 구성
; https://www.sysnet.pe.kr/2/0/902

소스 서버 보안
; https://www.sysnet.pe.kr/2/0/658

그런데, 이게 좀 귀찮다는 문제가 있습니다. ^^ 예를 들어 소스 서버를 운영하는 것도 나름 일인 것이고, 이미 github에 올려진 많은 공개 라이브러리들은 굳이 소스 서버를 2중으로 별도로 운영하는 것이 비효율적입니다. 이런 문제를 해결해 github 등과 곧바로 연동하는 소스 코드 디버깅이 가능하도록 해주는 것이 바로 "SourceLink"입니다.




그럼, 실습을 한번 해볼까요? ^^ 현재(2018-07-27 기준) 지원하는 SourceLink의 연결은 3개입니다.

  • GitHub
  • Visual Studio Team Services or Team Foundation Server
  • GitLab

그냥 github로 정하고, .NET Core 2.1 대상으로 다음과 같이 간단한 예제 라이브러리 프로젝트를 하나 만들어 보겠습니다.

stjeong/NetCoreEmptyLibSample 
; https://github.com/stjeong/NetCoreEmptyLibSample

using System;

namespace NetCoreEmptyLibSample
{
    public class SampleType
    {
        public void DoNothing()
        {
            Console.WriteLine("Really!");
        }
    }
}

예제 프로젝트가 마련되었으니, 이제 이 프로젝트에 SourceLink 기능을 추가하는데 방법은, 해당 프로젝트의 csproj 파일에 다음의 내용을 추가하는 것입니다.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>

    <!-- Optional: Declare that the Repository URL can be published to NuSpec -->
    <PublishRepositoryUrl>true</PublishRepositoryUrl>
 
    <!-- Optional: Embed source files that are not tracked by the source control manager to the PDB -->
    <EmbedUntrackedSources>true</EmbedUntrackedSources>

    <!-- Optional: Build symbol package (.snupkg) to distribute the PDB containing Source Link -->
    <IncludeSymbols>true</IncludeSymbols>
    <SymbolPackageFormat>snupkg</SymbolPackageFormat>

  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/>
  </ItemGroup>

</Project>

참고로, 자신의 프로젝트가 github 이외의 소스 제어를 사용하고 있다면 각각 다음의 PackageReference를 사용할 수 있습니다.

[Azure Repos (former Visual Studio Team Services)]
<PackageReference Include="Microsoft.SourceLink.AzureRepos.Git" Version="1.0.0" PrivateAssets="All"/>

[Azure DevOps Server (former Team Foundation Server)]
<PackageReference Include="Microsoft.SourceLink.AzureDevOpsServer.Git" Version="1.0.0" PrivateAssets="All"/>

[GitLab]
<PackageReference Include="Microsoft.SourceLink.GitLab" Version="1.0.0" PrivateAssets="All"/>

이제 빌드하면 끝입니다. 빌드한 바이너리(DLL과 PDB)를 다른 사람의 PC에 복사해 실습할 수 있습니다.

(주의 사항: 빌드 시점의 github commit을 기준으로 하기 때문에 변경된 소스 코드가 있다면 반드시 commit을 한 후 빌드해 다른 개발자에게 전달해야 합니다.)




정말로 디버깅 중에 소스 코드 진입이 가능한지 ^^ .NET Core 콘솔 프로젝트를 하나 만들고, 복사한 NetCoreEmptyLibSample.dll을 참조 추가한 후, 해당 라이브러리에서 제공하는 타입을 사용합니다.

using NetCoreEmptyLibSample;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            SampleType st = new SampleType();
            st.DoNothing();

            Console.WriteLine("Hello World!");
        }
    }
}

비주얼 스튜디오에서 BP를 걸고 디버깅 시작 후 F11(Step Into) 키를 눌러 진입하려고 시도하면 다음의 창이 뜹니다. (만약, 아래의 창이 뜨지 않는다면 Tools / Options 창에서 "Debugging" 옵션의 "Enable Just My Code"를 해제합니다.)

sourcelink_1.png

당연히 "Download Source and Continue Debugging"이나 "...(Don't Ask Again)"이 붙은 항목을 선택 후 진행하면 곧바로 소스 코드를 github로부터 다운로드해 다음과 같이 메서드 내의 코드로 디버깅이 들어갑니다.

sourcelink_2.png

와~~~ ^^ 소스 서버 구성하는 것보다 훨씬 간단해서 좋습니다.

참고로 다운로드한 소스 코드는 다음의 폴더에 캐시됩니다.

%LOCALAPPDATA%\SourceServer\51066fd97788357507fc4214d608f858a5a8c0be23357e8587faf90868540688\NetCoreEmptyLibSample




이런 기능이 동작할 수 있었던 것은 바로 Microsoft.SourceLink.GitHub에 의해 pdb 파일 안에 다음과 같이 소스 코드 파일에 대한 경로를 github 경로로 대응시킨 설정을 포함하고 있기 때문입니다.

{
    "documents":
    {
        "E:\\NetCoreEmptyLibSample\\*":"https://raw.githubusercontent.com/stjeong/NetCoreEmptyLibSample/92eb70045cce2227195feb6b4e1de17bf767e1ca/*"
    }
}

(중간의 "92eb70045cce2227195feb6b4e1de17bf767e1ca" 문자열은 github commit에 대한 id입니다.)

그리고 Visual Studio 2017의 15.3 버전부터는 저 항목에 대한 설정을 읽어 처리를 해주기 때문에 디버깅이 가능했던 것이고, 따라서 SourceLink 기능이 정상 동작하려면 (물론 일반 디버깅에서도 마찬가지지만) 반드시 pdb 파일이 있어야 합니다. 이것 때문에 nuget에 올릴 패키지인 경우 csproj에 다음의 설정을 포함시켜야 합니다.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>

    ...[생략]...

    <!-- Optional: Include PDB in the built .nupkg -->
    <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>

  </PropertyGroup>

    ...[생략]...

</Project>

위의 설정이 없으면 nupkg 압축 파일 패키지에 pdb 파일이 누락되므로 SourceLink 기능이 동작하지 않게 됩니다.




위에서도 한 번 언급했지만, pdb 파일에 포함되는 경로는 github에 마지막으로 commit한 시점을 기준으로 합니다. 따라서 마지막 commit 이후 소스 코드를 변경하고 빌드한 경우, 여전히 지난 시점의 commit ID를 기준으로 pdb 파일에 경로가 들어가기 때문에 이 시점의 바이너리를 다른 개발자에게 배포하면 이후에 github commit을 했어도 유효하지 않은 소스 코드 경로가 되어 다음과 같은 식의 오류 화면이 뜨거나, 이전 버전의 소스 코드를 보여줄 수 있습니다.

You need to find Class1.cs to view the source for the current call stack frame

Source Link Error:
git-credential-manager.exe: Could not obtain credentials. Process failed with exit code -1.
ERROR: The request failed with code 404: "Not Found".

Source Link URL: https://raw.githubusercontent.com/stjeong/NetCoreEmptyLibSample/92eb70045cce2227195feb6b4e1de17bf767e1ca/ClassLibrary1/Class1.cs

Try one of the following options:
    - Authenticate for Source Link (https://raw.githubusercontent.com/stjeong/NetCoreEmptyLibSample/92eb70045cce2227195feb6b4e1de17bf767e1ca/ClassLibrary1/Class1.cs)

    - Browse and find Class1.cs...




csproj에 PackageReference 추가 이후, 빌드 시 다음과 같은 오류가 발생할 수 있습니다.

Error Unable to locate repository containing directory 'E:\NetCoreEmptyLibSample\NetCoreEmptyLibSample'.
%USERPROFILE%\.nuget\packages\microsoft.build.tasks.git\1.0.0-beta-63102-01\build\Microsoft.Build.Tasks.Git.targets 20  

원인 파악을 위해 Microsoft.Build.Tasks.Git.targets 파일의 20번째 라인을 보면,

<Microsoft.Build.Tasks.Git.LocateRepository Directory="$(MSBuildProjectDirectory)" >
    <Output TaskParameter="Id" PropertyName="_SourceControlLocalRepositoryId" />
</Microsoft.Build.Tasks.Git.LocateRepository>

그러니까, Git 소스 컨트롤을 추가하지 않은 프로젝트에 대해 저런 오류가 발생하는 것입니다.

또는 다음과 같은 오류가 발생한다면?

Error The value of SourceRoot.RepositoryUrl with identity 'E:\NetCoreEmptyLibSample\' is invalid: ''"
%USERPROFILE%\.nuget\packages\microsoft.sourcelink.github\1.0.0\build\Microsoft.SourceLink.GitHub.targets 38  

<Microsoft.SourceLink.GitHub.GetSourceLinkUrl SourceRoot="@(SourceRoot)" Hosts="@(SourceLinkGitHubHost)" ImplicitHost="$(SourceLinkImplicitRepositoryHost)">
    <Output TaskParameter="SourceLinkUrl" PropertyName="_SourceLinkUrlToUpdate"/>
</Microsoft.SourceLink.GitHub.GetSourceLinkUrl>"

Git 소스 컨트롤은 추가했지만 아직 github의 원격 repo를 연결하지 않은 상태의 프로젝트이기 때문입니다.




재미있는 것은, 원래 이 기능은 다음의 개발자가 구현했던 것이라고 합니다. ^^

ctaggart/SourceLink 
; https://github.com/ctaggart/SourceLink

문서에 보면, Visual Studio의 "Enable source server support" 기능을,

VS.NET SP1 + .NET Framework 소스 코드 디버깅
; https://www.sysnet.pe.kr/2/0/623

"SourceLink"의 버전 1로, "Enable Source Link support" 옵션을 버전 2로, 그리고 이번 글에서 설명한 SourceLink를 버전 3으로 표현하고 있습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/23/2023]

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

비밀번호

댓글 작성자
 



2018-07-30 03시55분
[이성환] 얽... 본문에 이미지가 안 보여욤..ㅜ.ㅜ
[guest]
2018-07-30 05시50분
^^ 제가 실수했군요. 올렸으니 이제 보일 것입니다.
정성태
2023-06-23 10시05분
Improved .NET Debugging Experience with Source Link
; https://blog.ndepend.com/improved-net-debugging-experience-with-source-link
정성태

... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13172정성태11/25/20225119.NET Framework: 2071. 닷넷에서 ESP/RSP 레지스터 값을 구하는 방법파일 다운로드1
13171정성태11/25/20224694Windows: 214. 윈도우 - 스레드 스택의 "red zone"
13170정성태11/24/20225018Windows: 213. 윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?
13169정성태11/23/20225608Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
13168정성태11/22/20224877제니퍼 .NET: 31. 제니퍼 닷넷 적용 사례 (9) - DB 서비스에 부하가 걸렸다?!
13167정성태11/21/20224917.NET Framework: 2070. .NET 7 - Console.ReadKey와 리눅스의 터미널 타입
13166정성태11/20/20224638개발 환경 구성: 651. Windows 사용자 경험으로 WSL 환경에 dotnet 런타임/SDK 설치 방법
13165정성태11/18/20224546개발 환경 구성: 650. Azure - "scm" 프로세스와 엮인 서비스 모음
13164정성태11/18/20225471개발 환경 구성: 649. Azure - 비주얼 스튜디오를 이용한 AppService 원격 디버그 방법
13163정성태11/17/20225391개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226470.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20225713.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20225633.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20228814.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225131오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20225767.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20226678.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/20226188디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
13154정성태11/3/20225661.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo파일 다운로드1
13153정성태11/2/20226938.NET Framework: 2062. C# - 코드로 재현하는 소켓 상태(SYN_SENT, SYN_RECV)
13152정성태11/1/20225564.NET Framework: 2061. ASP.NET Core - DI로 추가한 클래스의 초기화 방법 [1]
13151정성태10/31/20225676C/C++: 161. Windows 11 환경에서 raw socket 테스트하는 방법파일 다운로드1
13150정성태10/30/20225714C/C++: 160. Visual Studio 2022로 빌드한 C++ 프로그램을 위한 다른 PC에서 실행하는 방법
13149정성태10/27/20225644오류 유형: 825. C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제파일 다운로드1
13148정성태10/26/20225639오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/20224761오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...