Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 4개 있습니다.)

windbg - .NET Framework 스레드 개체의 COM Apartment 유형 확인하는 방법


.NET 스레드 개체의 COM Apartment 유형을 확인하는 방법이 있을까요? 검색해 보니, 다음의 글이 나왔습니다.

How to get the current apartment for a thread
; http://chenlailin.blogspot.kr/2008/02/how-to-get-current-apartment-for-thread.html

제 경우에는, Windows 8 x64 + .NET 2.0 x86 환경으로 windbg를 이용하여 실습해보았는데 약간 달라서 기록을 남겨 봅니다.




우선, windbg를 실행해서 .NET 2.0 x86 응용 프로그램에 "attach to process"로 디버거를 연결한 후, TEB 내용을 확인했습니다. (Ctrl + S 키를 눌러 심벌 경로를 미리 설정해 둡니다. SRV*c:\Symbols*http://msdl.microsoft.com/download/symbols;)

0:000> !teb
TEB at 7f1bf000
    ExceptionList:        0050eb88
    StackBase:            00510000
    StackLimit:           004e6000
    SubSystemTib:         00000000
    FiberData:            00001e00
    ArbitraryUserPointer: 00000000
    Self:                 7f1bf000
    EnvironmentPointer:   00000000
    ClientId:             000077f4 . 00003ae0
    RpcHandle:            00000000
    Tls Storage:          7f1bf02c
    PEB Address:          7f1b5000
    LastErrorValue:       2
    LastStatusValue:      c0000135
    Count Owned Locks:    0
    HardErrorMode:        0

TEB 주소를 알았으니 좀 더 구체적인 내용을 살펴보겠습니다.

0:000> dt _TEB 7f1bf000
ntdll!_TEB
   +0x000 NtTib            : _NT_TIB
   +0x01c EnvironmentPointer : (null) 
...[생략]...
   +0xf80 ReservedForOle   : 0x006fc720 Void
...[생략]...
   +0xfe4 ReservedForWdf   : (null) 

ReservedForOle 필드의 옵셋값이 여전히 0xf80으로 변함이 없군요. ^^ 좋은 소식입니다. 해당 필드의 타입이 "Void"라고 나오지만, How to get the current apartment for a thread 글에 따르면 "SOleTlsData"임을 알 수 있습니다. 그래서, 명령을 내려 보았는데... 오류가 나는군요. ^^

0:000> dt SOleTlsData 0x006fc720
Symbol SOleTlsData not found.

검색해 보니, 없어질 만한 구조체는 아닌 것 같았습니다.

SOleTlsData structure
; https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms690269(v=vs.85)

How to get the current apartment for a thread 글을 자세히 보니, "dt SOleTlsData"의 출력 결과에 ole32!SOleTlsData라는 것이 보이는군요. ^^ 이를 힌트 삼아 dll을 명시해 주니 원하는 결과를 얻을 수 있었습니다.

0:000> dt ole32!SOleTlsData 0x006fc720
...[생략]...
   +0x030 pObjServer       : (null) 
   +0x034 dwTIDCaller      : 0
   +0x038 pCurrentCtxForNefariousReaders : 0x006fcdb0 Void
   +0x03c pCurrentContext  : 0x006fcdb0 CObjectContext
   +0x040 pEmptyCtx        : 0x006fcdb0 CObjectContext
   +0x048 ContextId        : 2
   +0x050 pNativeApt       : 0x00700680 CComApartment
...[생략]...

본문에서는 이상하게도 pCurrentContext를 추적해서 들어가는데요. 그럴 필요 없이 0x50 옵셋에 위치한 CComApartment 구조체를 바로 추적하는 것이 더 낫다는 것을 알게 되었습니다.

CComApartment Class
; https://learn.microsoft.com/en-us/cpp/atl/reference/ccomapartment-class

최종적으로 우리가 원하는 Apartment 유형을 구할 수 있습니다.

0:000> dt CComApartment 0x00700680 
ole32!CComApartment
   +0x000 __VFN_table : 0x77573dac 
   +0x004 _cRefs           : 4
   +0x008 _dwState         : 0
   +0x00c _AptKind         : 2 ( APTKIND_MULTITHREADED )
   ...[생략]...
   =76e20000 s_ulApartmentIdentifierCounter : 0x905a4d
   =76e20000 s_ShutdownRegLock : COleStaticMutexSem

0x0c 옵셋에 있는 _AptKind의 값으로는 다음과 같은 유형들이 있습니다.

// combase.h
// ; http://www.brandonfa.lk/win8/win8_devrel_head_x86/combase.h

enum tagAPTKIND {
    APTKIND_NEUTRALTHREADED = 1,
    APTKIND_MULTITHREADED = 2,
    APTKIND_APARTMENTTHREADED = 4,
    APTKIND_APPLICATION_STA = 8
};

본문에서는 명령어 하나로 알아내는 것이 다음과 같이 복잡했는데요.

// FIELD_OFFSET
// ; https://jeho.page/programming/2011/03/01/FIELD_OFFSET-%EB%A7%A4%ED%81%AC%EB%A1%9C.html

dt ole32!CComApartment poi(@@C++(#FIELD_OFFSET(ole32!CObjectContext,_pApartment))+poi(poi($thread+@@C++(#FIELD_OFFSET(ole32!_TEB, ReservedForOle)))+@@C++(#FIELD_OFFSET(ole32!SOleTlsData,pCurrentContext))))))

이것을 다음과 같이 좀 더 간단하게 고쳐줄 수 있습니다. ^^

dt ole32!CComApartment poi(@@C++(#FIELD_OFFSET(ole32!SOleTlsData,pNativeApt))+poi($thread+@@C++(#FIELD_OFFSET(ole32!_TEB, ReservedForOle))))




이 과정을 이용해서 .NET 응용 프로그램에서도 쉽게 결과를 구할 수 있습니다.

TEB 구하는 것은 예전에도 한번 언급해 드렸죠? ^^

.NET System.Threading.Thread 개체에서 Native Thread Id를 구할 수 있을까?
; https://www.sysnet.pe.kr/2/0/1244

이를 이용한 전체 소스 코드는 다음과 같습니다.

class Program
{
    [DllImport("ntdll.dll")]
    static extern IntPtr NtCurrentTeb();

    static void Main(string[] args)
    {
        if (IntPtr.Size == 8)
        {
            return; // not supported yet.
        }

        IntPtr pTeb = NtCurrentTeb();
        Console.WriteLine("TEB: " + pTeb.ToInt64().ToString("x"));
        Console.WriteLine("dt _TEB " + pTeb.ToInt64().ToString("x"));

        IntPtr reservedForOle = new IntPtr(pTeb.ToInt64() + 0xf80);
        int ReservedForOle = Marshal.ReadInt32(reservedForOle); // TEB.ReservedForOle
        Console.WriteLine("TEB.ReservedForOle: " + ReservedForOle.ToString("x"));
        Console.WriteLine("dt ole32!SOleTlsData " + ReservedForOle.ToString("x"));

        IntPtr pNativeApt = new IntPtr(ReservedForOle + 0x50);
        int NativeApt = Marshal.ReadInt32(pNativeApt); // SOleTlsData.pNativeApt
        Console.WriteLine("SOleTlsData.pNativeApt: " + NativeApt.ToString("x"));
        Console.WriteLine("dt CComApartment " + NativeApt.ToString("x"));

        IntPtr pAptKind = new IntPtr(NativeApt + 0x0c);
        int AptKind = Marshal.ReadInt32(pAptKind); // CComApartment._AptKind
        Console.WriteLine("CComApartment._AptKind: " + AptKind.ToString("x"));

        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }
}





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/29/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)
13521정성태1/11/20242407닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242193오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242223닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242489닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242298스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242408닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242728닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242387개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242313닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242267개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242265닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242181닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242255오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242310오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242989닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232565닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20233131닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232702닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232593Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232646닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232405개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232531디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233195닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232596오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232706Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232641Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...