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

C# - ETW 이벤트의 Keywords에 속한 EventId 구하는 방법 (1) PInvoke

일례로 예전 ETW 글에서,

C# - (.NET Core 2.2부터 가능한) 프로세스 내부에서 CLR ETW 이벤트 수신
; https://www.sysnet.pe.kr/2/0/12474

"Microsoft-Windows-DotNETRuntime" ETW 제공자의 Exception 키워드(keyword) 범주에 속하는 이벤트를,

.NET runtime exception events
; https://docs.microsoft.com/en-us/dotnet/fundamentals/diagnostics/runtime-exception-events

활성화시켰습니다. 그리고 해당 키워드에 속한 이벤트가 여러 개 있는데 그것들에도 각각 "Event ID"라는 것이 부여되어 있어 식별이 가능합니다. 가령 Exception 범주의 경우 위의 문서에 나오듯이 아래와 같은 ID로 구별되는 이벤트가 발생합니다.

  • ExceptionThrown_V1 - Event ID == 80
  • ExceptionCatchStart - Event ID == 250
  • ExceptionCatchStop - Event ID == 251
  • ExceptionFinallyStart - Event ID == 252
  • ExceptionFinallyStop - Event ID == 253
  • ExceptionFilterStart - Event ID == 254
  • ExceptionFilterStop - Event ID == 255
  • ExceptionThrownStop - Event ID == 256

사실 이 정보들은 ETW manifest 파일에 기록돼 있긴 합니다.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\CLR-ETW.man
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\CLR-ETW.man

<instrumentationManifest xmlns="http://schemas.microsoft.com/win/2004/08/events">
    <instrumentation xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:win="http://manifests.microsoft.com/win/2004/08/windows/events">
        <events xmlns="http://schemas.microsoft.com/win/2004/08/events">
            <!--CLR Runtime Publisher-->
            <provider name="Microsoft-Windows-DotNETRuntime" guid="{e13c0d23-ccbc-4e12-931b-d9cc2eee27e4}" symbol="MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER" resourceFileName="%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\clretwrc.dll" messageFileName="%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\clretwrc.dll">
                <!--Keywords-->
                <keywords>
                    <keyword name="GCKeyword" mask="0x1" message="$(string.RuntimePublisher.GCKeywordMessage)" symbol="CLR_GC_KEYWORD"/>
                    ...[생략]...
                    <keyword name="ExceptionKeyword" mask="0x8000" message="$(string.RuntimePublisher.ExceptionKeywordMessage)" symbol="CLR_EXCEPTION_KEYWORD"/>
                    ...[생략]...
                </keywords>
                ..[생략]...
                <events>
                    <!-- CLR GC events, value reserved from 0 to 39 and 200 to 239 -->
                    <!-- Note the opcode's for GC events do include 0 to 9 for backward compatibility, even though
          they don't mean what those predefined opcodes are supposed to mean -->
                    <event value="1" version="0" level="win:Informational" template="GCStart" keywords="GCKeyword" opcode="win:Start" task="GarbageCollection" symbol="GCStart" message="$(string.RuntimePublisher.GCStartEventMessage)"/>
                    ..[생략]...
                    <!-- CLR Exception events -->
                    <event value="80" version="0" level="win:Informational" opcode="win:Start" task="Exception" symbol="ExceptionThrown" message="$(string.RuntimePublisher.ExceptionExceptionThrownEventMessage)"/>
                    <event value="80" version="1" level="win:Error" template="Exception" keywords="ExceptionKeyword MonitoringKeyword" opcode="win:Start" task="Exception" symbol="ExceptionThrown_V1" message="$(string.RuntimePublisher.ExceptionExceptionThrown_V1EventMessage)"/>
                    <event value="250" version="0" level="win:Informational" template="ExceptionHandling" keywords="ExceptionKeyword" opcode="win:Start" task="ExceptionCatch" symbol="ExceptionCatchStart" message="$(string.RuntimePublisher.ExceptionExceptionHandlingEventMessage)"/>
                    <event value="251" version="0" level="win:Informational" keywords="ExceptionKeyword" opcode="win:Stop" task="ExceptionCatch" symbol="ExceptionCatchStop" message="$(string.RuntimePublisher.ExceptionExceptionHandlingNoneEventMessage)"/>
                    <event value="252" version="0" level="win:Informational" template="ExceptionHandling" keywords="ExceptionKeyword" opcode="win:Start" task="ExceptionFinally" symbol="ExceptionFinallyStart" message="$(string.RuntimePublisher.ExceptionExceptionHandlingEventMessage)"/>
                    <event value="253" version="0" level="win:Informational" keywords="ExceptionKeyword" opcode="win:Stop" task="ExceptionFinally" symbol="ExceptionFinallyStop" message="$(string.RuntimePublisher.ExceptionExceptionHandlingNoneEventMessage)"/>
                    <event value="254" version="0" level="win:Informational" template="ExceptionHandling" keywords="ExceptionKeyword" opcode="win:Start" task="ExceptionFilter" symbol="ExceptionFilterStart" message="$(string.RuntimePublisher.ExceptionExceptionHandlingEventMessage)"/>
                    <event value="255" version="0" level="win:Informational" keywords="ExceptionKeyword" opcode="win:Stop" task="ExceptionFilter" symbol="ExceptionFilterStop" message="$(string.RuntimePublisher.ExceptionExceptionHandlingNoneEventMessage)"/>                                                                                                       
                    <event value="256" version="0" level="win:Informational" keywords="ExceptionKeyword" opcode="win:Stop" task="Exception" symbol="ExceptionThrownStop" message="$(string.RuntimePublisher.ExceptionExceptionHandlingNoneEventMessage)"/>
                    <!-- CLR Contention events -->
                    ..[생략]...
                </events>
            </provider>
            ..[생략]...
        </resources>
    </localization>
</instrumentationManifest>

그래서 Event ID 목록을 man 파일로부터 구하는 것이 가능하지만, 혹시 프로그래밍으로도 가능할까요? 아쉽게도 "C# - (.NET Core 2.2부터 가능한) 프로세스 내부에서 CLR ETW 이벤트 수신" 글에서 사용한 EventSource 타입으로는 해당 이벤트 목록을 구할 수 공식적인 방법이 없습니다.

대안으로 생각해 볼 수 있는 것이 지난 글의,

C# - ETW 관련 Win32 API 사용 예제 코드 (1)
; https://www.sysnet.pe.kr/2/0/12292#trace_event_cs

TraceEventSession.cs 파일처럼 P/Invoke 호출을 해보는 건데요, 그래서 아래의 함수를 더 추가하면,

TdhEnumerateManifestProviderEvents function (tdh.h)
; https://docs.microsoft.com/en-us/windows/win32/api/tdh/nf-tdh-tdhenumeratemanifestproviderevents

TRACE_PROVIDER_INFO structure (tdh.h)
; https://docs.microsoft.com/en-us/windows/win32/api/tdh/ns-tdh-trace_provider_info

EVENT_DESCRIPTOR structure (evntprov.h)
; https://docs.microsoft.com/en-us/windows/win32/api/evntprov/ns-evntprov-event_descriptor

다음과 같이 코딩해 특정 Keyword에 해당하는 이벤트 ID 목록을 구하는 것이 가능합니다.

EVENT_DESCRIPTOR[] eventDescs = GetEventProviders(guid); // guid == e13c0d23-ccbc-4e12-931b-d9cc2eee27e4 ("Microsoft-Windows-DotNETRuntime")

Console.WriteLine("EventIDs at Keyword == Exception: ");
foreach (EVENT_DESCRIPTOR desc in eventDescs)
{
    if ((desc.Keyword & 0x8000) == 0x8000) // 0x8000 == Exception keyword mask
    {
        Console.WriteLine("\t" + desc);
    }
}

/* 출력 결과
EventIDs at Keyword == Exception:
        250 at 32768
        251 at 32768
        252 at 32768
        253 at 32768
        254 at 32768
        255 at 32768
        256 at 32768
        80 at 8589967360
*/

private static EVENT_DESCRIPTOR[] GetEventProviders(Guid guid)
{
    uint bufSize = 0;
    int result = 0;
    IntPtr ptr = IntPtr.Zero;

    try
    {
        do
        {
            if (bufSize != 0)
            {
                ptr = Marshal.AllocHGlobal((int)bufSize);
            }

            result = NativeMethods.TdhEnumerateManifestProviderEvents(ref guid, ptr, ref bufSize);

            if (ptr != IntPtr.Zero && result != 0)
            {
                Marshal.FreeHGlobal(ptr);
                ptr = IntPtr.Zero;
            }

        } while (result == (int)TDHSTATUS.ERROR_INSUFFICIENT_BUFFER);

        /* PROVIDER_EVENT_INFO */
        int offset = 0;
        uint numberOfEvents = (uint)Marshal.ReadInt32(ptr, 0);
        offset += sizeof(uint);

        // unused
        // uint reserved = (uint)Marshal.ReadInt32(ptr, offset);
        offset += sizeof(uint);

        EVENT_DESCRIPTOR[] descs = new EVENT_DESCRIPTOR[numberOfEvents];
        int descSize = Marshal.SizeOf(descs[0]);
        int nDesc = (int)((bufSize - offset) / descSize);

        Debug.Assert(numberOfEvents == nDesc);

        for (int i = 0; i < nDesc; i++)
        {
            descs[i] = (EVENT_DESCRIPTOR)Marshal.PtrToStructure(ptr + (offset + i * descSize), typeof(EVENT_DESCRIPTOR));
        }

        return descs;
    }
    finally
    {
        if (ptr != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(ptr);
        }
    }
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로, PowerShell의 Get-WinEvent를 명령어를 이용해서도 구할 수 있습니다.

PS C:\temp> (Get-WinEvent -ListProvider Microsoft-Windows-DotNETRuntime).Events | Format-Table ID, Keywords

 Id Keywords
 -- --------
...[생략]...
 80 {MonitoringKeyword, ExceptionKeyword}
...[생략]...
250 {ExceptionKeyword}
251 {ExceptionKeyword}
252 {ExceptionKeyword}
253 {ExceptionKeyword}
254 {ExceptionKeyword}
255 {ExceptionKeyword}
256 {ExceptionKeyword}




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/15/2024]

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)
12922정성태1/14/20226642개발 환경 구성: 625. AKS - Azure Kubernetes Service 생성 및 SLO/SLA 변경 방법
12921정성태1/14/20225627개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226398오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/20226227Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/20226448Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225676오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225408오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20225679오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/20227585VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/20228129.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/20228752개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/20226101VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
12910정성태1/10/20226562제니퍼 .NET: 30. 제니퍼 닷넷 적용 사례 (8) - CPU high와 DB 쿼리 성능에 문제가 함께 있는 사이트
12909정성태1/10/20227965오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20225816.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226254오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20226868.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20226530오류 유형: 780. Could not load file or assembly 'Microsoft.VisualStudio.TextTemplating.VSHost.15.0, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
12904정성태1/8/20228553개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227148.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227185오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20227279오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
12900정성태1/5/20228929개발 환경 구성: 622. vcpkg로 ffmpeg를 빌드하는 경우 생성될 구성 요소 제어하는 방법
12899정성태1/3/20228412개발 환경 구성: 621. windbg에서 python 스크립트 실행하는 방법 - pykd (2)
12898정성태1/2/20228969.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c) [1]파일 다운로드1
12897정성태1/2/20227848.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 [4]파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...