Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

Visual Studio - 디버깅 시 다른 함수의 소스 코드를 보여주는 사례 (Enable COMDAT Folding 옵션)

Visual Studio 등의 디버거를 이용해 (보통 Release 모드로 빌드된 바이너리를) 디버깅하다 보면 이상하게 다른 함수의 소스 코드가 보이는 경우가 있습니다.

이에 대해 친절하게 설명한 글이 있는데요, ^^

Why does the debugger show me the wrong function?
; https://devblogs.microsoft.com/oldnewthing/20050322-00/?p=36113

글에서 예로 든 상황을 직접 실습해 보겠습니다.




사실 지난번에 쓴 글이 바로,

Visual C++ - 디버그 코드에서 빌드 옵션 조정으로 최적화 코드로의 전환
; https://www.sysnet.pe.kr/2/0/14035

저 글의 내용을 쉽게 확인하기 위해 Debug 빌드에서 MyClass.cpp 파일만 Release 빌드로 바꾸는 방법을 소개한 것이었습니다. 하지만, 이 글의 실습을 하려면 소스 코드에 약간의 변화가 필요한데요, 왜냐하면 (글에서는 x86으로 실습하고 있어 상관없지만) x64로 빌드하는 경우 int*는 8바이트를 반환하고, int는 4바이트를 반환하기 때문에,

--- C:\temp\ConsoleApp1\ConsoleApplication1\MyClass.cpp ------------------------
ConsoleApplication1.exe!Class1::GetQ(void):
48 8B 41 08          mov         rax,qword ptr [rcx+8]  
C3                   ret  

--- C:\temp\ConsoleApp1\ConsoleApplication1\MyClass.cpp ------------------------
ConsoleApplication1.exe!Class2::GetValue(void):
8B 41 08             mov         eax,dword ptr [rcx+8]  
C3                   ret  

GetValue 함수의 반환 값을 __int64로 바꿔 데이터 바이트 크기를 맞춰주어야 합니다.

int* Class1::GetQ()
{
    return q;
}

__int64 Class2::GetValue()
{
    return value;
}

이제야 컴파일 후 디버깅하면 다음과 같이 동일한 코드로 나옵니다.

--- C:\temp\ConsoleApp1\ConsoleApplication1\MyClass.cpp ------------------------
ConsoleApplication1.exe!Class1::GetQ(void):
48 8B 41 08          mov         rax,qword ptr [rcx+8]  
C3                   ret  

--- C:\temp\ConsoleApp1\ConsoleApplication1\MyClass.cpp ------------------------
ConsoleApplication1.exe!Class2::GetValue(void):
48 8B 41 08          mov         rax,qword ptr [rcx+8]  
C3                   ret  




하지만, 이 상태에서는 GetQ와 GetValue 함수가 동일한 기계어 코드는 가져도, F11 Step-into 진입 시에 개별 함수의 소스 코드가 열리게 됩니다.

즉, 글의 내용과 같게 동작하도록 만들려면 /OPT:ICF 옵션을 추가해야 하는데요, 아쉽게도 이것은 Linker 옵션이기 때문에 개별 파일에 지정할 수는 없고 프로젝트 단위로 "Linker" / "Optimization" 범주에서 "Enable COMDAT Folding" 옵션을 "Yes (/OPT:ICF)"로 바꿔주어야 합니다.

linker_icf_opt_1.png

이후 빌드하면, GetQ 함수의 BP에서 다음과 같이 열리지만,

linker_icf_opt_2.png

GetValue 함수 내에서는 Visual Studio에서 BP를 걸고 싶어도 걸리지 않게 됩니다. 또한, GetQ를 호출하든 GetValue를 호출하든,

__int64 Whatever(Class2* p)
{
    return p->GetValue(); // 여기서 F11을 누르면 GetQ 함수의 소스 코드가 열림
}

int* Whatever(Class1* p)
{
    return p->GetQ(); // 여기서 F11을 누르면 GetQ 함수의 소스 코드가 열림
}

디버거 입장에서는 동일한 기계어 코드를 가지는 함수를 모두 1개의 함수로 번역하므로 소스 코드상으로 다른 호출이라고 해도 함수의 구별이 불가능하게 된 것입니다.

바로 이 상황이, Release 모드로 빌드된 바이너리를 디버깅할 때 BP를 걸거나 F11로 진입할 때 다른 함수의 소스 코드가 열리는 이유였습니다.




그리고 다음의 글에서는,

How can I confirm in the Windows debugger that I’m looking at a COMDAT-folded function?
; https://devblogs.microsoft.com/oldnewthing/20250725-00/?p=111409

WinDbg에서 특정 함수가 COMDAT Folding으로 인해 다른 함수와 합쳐졌는지 확인하는 방법을 소개하고 있는데요, 이것도 마저 실습해 보겠습니다. ^^

우선, 기존 소스 코드에서 main 함수에 getchar 호출을 추가하고,

#include <stdio.h>
#include "MyClass.h"

__int64 Whatever(Class2* p)
{
    return p->GetValue();
}

int* Whatever(Class1* p)
{
    return p->GetQ();
}

int main()
{
    Class2 c2;
    Whatever(&c2);

    Class1 c1;
    Whatever(&c1);

    getchar();
}

실행 후, WinDbg로 attach 시킨 후에 다음과 같이 각각의 함수 주소를 확인합니다.

0:004> x ConsoleApplication1!Class1::GetQ
00007ff7`e2c911c4 ConsoleApplication1!Class1::GetQ (void)

0:004> x ConsoleApplication1!Class2::GetValue
00007ff7`e2c911c4 ConsoleApplication1!Class2::GetValue (void)

2개 모두 00007ff7`e2c911c4 동일한 주소를 가리키고 있죠? ^^ 반대로 특정 함수의 주소를 알고 있다면 ln 명령어로 확인할 수도 있습니다.

0:004> ln 00007ff7`e2c911c4
Browse module
Set bu breakpoint

 [C:\temp\ConsoleApp1\ConsoleApplication1\MyClass.cpp @ 4] (00007ff7`e2c911c4)   ConsoleApplication1!Class1::GetQ   |  (00007ff7`e2c911d0)   ConsoleApplication1!_RTC_AllocaHelper
Exact matches:
    ConsoleApplication1!Class2::GetValue (void)
    ConsoleApplication1!Class1::GetQ (void)

그럼 2개의 함수(GetValue, GetQ)가 동일한 주소를 가지고 있다는 점과, 그 2개의 함수에 대해 "Class1::GetQ" 함수로 디버거가 인식할 거라는 사실을 출력으로 확인할 수 있습니다.




그나저나, COMDAT(common data)는 무슨 약어인 걸까요? ^^ 이에 대해 찾아보면,

Why is Identical COMDAT Folding called Identical COMDAT Folding?
; https://devblogs.microsoft.com/oldnewthing/20161024-00/?p=94575

FORTRAN 언어의 기능이었던 "common data block", 보통은 줄여서 "common block"이라고 했던 것에서 유래했다고 합니다.




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







[최초 등록일: ]
[최종 수정일: 10/25/2025]

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

비밀번호

댓글 작성자
 




... 136  [137]  138  139  140  141  142  143  144  145  146  147  148  149  150  ...
NoWriterDateCnt.TitleFile(s)
1744정성태9/17/201437071.NET Framework: 460. GetTickCount / GetTickCount64와 0x7FFE0000 주솟값 [4]파일 다운로드1
1743정성태9/16/201426679오류 유형: 238. 설치 오류 - Failed to get size of pseudo bundle
1742정성태8/27/201433065개발 환경 구성: 236. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 [2]
1741정성태8/26/201426582.NET Framework: 459. GetModuleHandleEx로 알아보는 .NET 메서드의 DLL 모듈 관계파일 다운로드1
1740정성태8/25/201438089.NET Framework: 458. 닷넷 GC가 순환 참조를 해제할 수 있을까요? [2]파일 다운로드1
1739정성태8/24/201432188.NET Framework: 457. 교착상태(Dead-lock) 해결 방법 - Lock Leveling [2]파일 다운로드1
1738정성태8/23/201427662.NET Framework: 456. C# - CAS를 이용한 Lock 래퍼 클래스파일 다운로드1
1737정성태8/20/201424196VS.NET IDE: 93. Visual Studio 2013 동기화 문제
1736정성태8/19/201431012VC++: 79. [부연] CAS Lock 알고리즘은 과연 빠른가? [2]파일 다운로드1
1735정성태8/19/201423662.NET Framework: 455. 닷넷 사용자 정의 예외 클래스의 최소 구현 코드 - 두 번째 이야기
1734정성태8/13/201425729오류 유형: 237. Windows Media Player cannot access the file. The file might be in use, you might not have access to the computer where the file is stored, or your proxy settings might not be correct.
1733정성태8/13/201432097.NET Framework: 454. EmptyWorkingSet Win32 API를 사용하는 C# 예제파일 다운로드1
1732정성태8/13/201440924Windows: 99. INetCache 폴더가 다르게 보이는 이유
1731정성태8/11/201432263개발 환경 구성: 235. 점(.)으로 시작하는 파일명을 탐색기에서 만드는 방법
1730정성태8/11/201427966개발 환경 구성: 234. Royal TS의 터미널(Terminal) 연결에서 한글이 깨지는 현상 해결 방법
1729정성태8/11/201423410오류 유형: 236. SqlConnection - The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
1728정성태8/8/201436526.NET Framework: 453. C# - 오피스 파워포인트(Powerpoint) 파일을 WinForm에서 보는 방법파일 다운로드1
1727정성태8/6/201426887오류 유형: 235. SignalR 오류 메시지 - Counter 'Messages Bus Messages Published Total' does not exist in the specified Category. [2]
1726정성태8/6/201425251오류 유형: 234. IIS Express에서 COM+ 사용 시 SecurityException - "Requested registry access is not allowed" 발생
1725정성태8/6/201427439오류 유형: 233. Visual Studio 2013 Update3 적용 후 Microsoft.VisualStudio.Web.PageInspector.Runtime 모듈에 대한 FileNotFoundException 예외 발생
1724정성태8/5/201431594.NET Framework: 452. .NET System.Threading.Thread 개체에서 Native Thread Id를 구하는 방법 - 두 번째 이야기 [1]파일 다운로드1
1723정성태7/29/201464444개발 환경 구성: 233. DirectX 9 예제 프로젝트 빌드하는 방법 [3]파일 다운로드1
1722정성태7/25/201426946오류 유형: 232. IIS 500 Internal Server Error - NTFS 암호화된 폴더에 웹 애플리케이션이 위치한 경우
1721정성태7/24/201430849.NET Framework: 451. 함수형 프로그래밍 개념 - 리스트 해석(List Comprehension)과 순수 함수 [2]
1720정성태7/23/201427186개발 환경 구성: 232. C:\WINDOWS\system32\LogFiles\HTTPERR 폴더에 로그 파일을 남기지 않는 설정
1719정성태7/22/201431738Math: 13. 동전을 여러 더미로 나누는 경우의 수 세기(Partition Number) - 두 번째 이야기파일 다운로드1
... 136  [137]  138  139  140  141  142  143  144  145  146  147  148  149  150  ...