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

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13244정성태2/5/20234331VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20235154디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234613디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20234037디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20234189디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233877디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20236018.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235712.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20235193개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234838개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235927개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20237298오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234954스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233986오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234363개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235387.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235495.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20235156개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234832.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20234025개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234466Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234615오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20234330개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234487Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234596오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20234216Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...