Microsoft MVP성태의 닷넷 이야기
.NET Framework: 932. C# - ETW 관련 Win32 API 사용 예제 코드 (1) [링크 복사], [링크+제목 복사]
조회: 11967
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 11개 있습니다.)
.NET Framework: 475. ETW(Event Tracing for Windows)를 C#에서 사용하는 방법
; https://www.sysnet.pe.kr/2/0/1804

.NET Framework: 483. 코드로 살펴 보는 ETW의 활성화 시점
; https://www.sysnet.pe.kr/2/0/1815

.NET Framework: 915. ETW(Event Tracing for Windows)를 이용한 닷넷 프로그램의 내부 이벤트 활용
; https://www.sysnet.pe.kr/2/0/12244

.NET Framework: 923. C# - ETW(Event Tracing for Windows)를 이용한 Finalizer 실행 감시
; https://www.sysnet.pe.kr/2/0/12255

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

.NET Framework: 933. C# - ETW 관련 Win32 API 사용 예제 코드 (2) NT Kernel Logger
; https://www.sysnet.pe.kr/2/0/12296

.NET Framework: 934. C# - ETW 관련 Win32 API 사용 예제 코드 (3) ETW Consumer 구현
; https://www.sysnet.pe.kr/2/0/12299

.NET Framework: 935. C# - ETW 관련 Win32 API 사용 예제 코드 (4) CLR ETW Consumer
; https://www.sysnet.pe.kr/2/0/12300

.NET Framework: 936. C# - ETW 관련 Win32 API 사용 예제 코드 (5) - Private Logger
; https://www.sysnet.pe.kr/2/0/12302

개발 환경 구성: 504. ETW - 닷넷 프레임워크 기반의 응용 프로그램을 위한 명령행 도구 etrace 소개
; https://www.sysnet.pe.kr/2/0/12303

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




C# - ETW 관련 Win32 API 사용 예제 코드 (1)

예전에 ETW의 Provider 측 코드를 작성하는 방법을 소개했고,

ETW(Event Tracing for Windows)를 C#에서 사용하는 방법
; https://www.sysnet.pe.kr/2/0/1804

닷넷 프레임워크 관련한 ETW 이벤트 활용과 함께 Consumer 측에 대해서도 다뤘으니,

ETW(Event Tracing for Windows)를 이용한 닷넷 프로그램의 내부 이벤트 활용
; https://www.sysnet.pe.kr/2/0/12244

ETW 관련한 명령어들을 Win32 API 수준으로 내려 살펴보는 시간을 갖겠습니다. ^^




우선, ETW provider를 나열하는 "xperf -providers" 명령어를 코드로 구현해 볼까요?

ETW provider 목록
; https://www.sysnet.pe.kr/2/0/10909

정식 BCL에 이 기능은 없지만 "Microsoft.Diagnostics.Tracing.TraceEvent" 패키지의 소스 코드를 보면 Win23 API와 Interop하는 소스 코드를 볼 수 있습니다.

// perfview/src/TraceEvent/
// ; https://github.com/microsoft/perfview/blob/master/src/TraceEvent/TraceEventSession.cs#L1533

static unsafe void PrintProviders()
{
    var providersByName = new SortedDictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
    int buffSize = 0;
    var hr = NativeMethods.TdhEnumerateProviders(null, ref buffSize);
    Debug.Assert(hr == 122);     // ERROR_INSUFFICIENT_BUFFER
    var buffer = stackalloc byte[buffSize];
    var providersDesc = (PROVIDER_ENUMERATION_INFO*)buffer;

    hr = NativeMethods.TdhEnumerateProviders(providersDesc, ref buffSize);
    if (hr != 0)
    {
        Trace.WriteLine("TdhEnumerateProviders failed HR = " + hr);
        providersDesc->NumberOfProviders = 0;
    }

    var providers = (TRACE_PROVIDER_INFO*)&providersDesc[1];
    for (int i = 0; i < providersDesc->NumberOfProviders; i++)
    {
        var name = new string((char*)&buffer[providers[i].ProviderNameOffset]);
        providersByName[name] = providers[i].ProviderGuid;
    }

    foreach (var item in providersByName)
    {
        Console.WriteLine(item.Key + ": " + item.Value);
    }
}

internal struct PROVIDER_ENUMERATION_INFO
{
    public int NumberOfProviders;
    public int Padding;
}

unsafe class NativeMethods
{
    [DllImport("tdh.dll")]
    internal static extern int TdhEnumerateProviders(PROVIDER_ENUMERATION_INFO* pBuffer, ref int pBufferSize);

}

그러니까, TdhEnumerateProviders Win32 API 하나로 ETW provider 목록을 모두 열람할 수 있습니다. (참고로, ETW Provider 목록은 레지스트리에 등록되므로 "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WINEVT\Publishers\"의 하위 키를 열람해도 됩니다.)




"logman query -ets" 명령을 실행하면 현재 StartTrace로 실행해 둔 ETW 세션이 있는지 확인할 수 있습니다. 제 PC의 경우 최초 로그인 시 다음과 같은 세션들이 있었습니다.

C:\Windows\System32> logman query -ets

Data Collector Set                      Type                          Status
-------------------------------------------------------------------------------
Circular Kernel Context Logger          Trace                         Running
AppModel                                Trace                         Running
DiagLog                                 Trace                         Running
Diagtrack-Listener                      Trace                         Running
EventLog-Application                    Trace                         Running
EventLog-Microsoft-Windows-Sysmon-Operational Trace                         Running
EventLog-RemoteDesktopServices-RemoteFX-SessionLicensing-Debug Trace                         Running
EventLog-System                         Trace                         Running
LwtNetLog                               Trace                         Running
Microsoft-Windows-Rdp-Graphics-RdpIdd-Trace Trace                         Running
NetCore                                 Trace                         Running
NtfsLog                                 Trace                         Running
RadioMgr                                Trace                         Running
UBPM                                    Trace                         Running
WdiContextLog                           Trace                         Running
WiFiSession                             Trace                         Running
SgrmEtwSession                          Trace                         Running
UserNotPresentTraceSession              Trace                         Running
CldFltLog                               Trace                         Running
Admin_PS_Provider                       Trace                         Running
NetCfgTrace                             Trace                         Running
WindowsUpdate_trace_log                 Trace                         Running
MpWppTracing-20200819-152610-00000003-ffffffff Trace                         Running
ScreenOnPowerStudyTraceSession          Trace                         Running
SHS-08192020-152637-7-7f                Trace                         Running
Cloud Files Diagnostic Event Listener   Trace                         Running
8696EAC4-1288-4288-A4EE-49EE431B0AD9    Trace                         Running
Microsoft-VisualStudio-Telemetry-PerfWatson2-19040 Trace                         Running
Microsoft-VisualStudio-Telemetry-PerfWatson2-18384 Trace                         Running

The command completed successfully.

이 목록은, Win32 API로는 QueryAllTraces로 구할 수 있는데 Interop 과정이 좀 복잡한 것을 제외하고는 API 문서에 나온 기능을 C#으로도 다음과 같이 옮길 수 있습니다.

public static List<EventTraceProperitesManaged> QueryAllSessions()
{
    List<EventTraceProperitesManaged> list = new List<EventTraceProperitesManaged>();

    unsafe
    {
        IntPtr ptrBuf = Marshal.AllocHGlobal(EventTraceProperties.MaxSessionBufferSize);

        try
        {
            IntPtr[] arrayBuf = new IntPtr[EventTraceProperties.MAX_SESSIONS];

            for (int i = 0; i < EventTraceProperties.MAX_SESSIONS; i++)
            {
                EventTraceProperties* pProp = (EventTraceProperties*)(((byte*)ptrBuf.ToPointer()) + EventTraceProperties.RecordSize * i);

                IntPtr elemPtr = new IntPtr(pProp);
                arrayBuf[i] = elemPtr;

                pProp->Initialize();
            }

            GCHandle gcHandle = GCHandle.Alloc(arrayBuf, GCHandleType.Pinned);

            try
            {
                IntPtr elem0 = gcHandle.AddrOfPinnedObject();

                uint activeSessionCount = 0;
                int status = NativeMethods.QueryAllTraces(elem0, EventTraceProperties.MAX_SESSIONS, ref activeSessionCount);
                if (status == 0)
                {
                    for (int i = 0; i < activeSessionCount; i++)
                    {
                        EventTraceProperties* pProp = (EventTraceProperties*)(((byte*)ptrBuf.ToPointer()) + EventTraceProperties.RecordSize * i);
                        list.Add(pProp->ReadAsManaged());
                    }
                }
                else
                {
                    Console.WriteLine(status);
                }
            }
            finally
            {
                gcHandle.Free();
            }
        }
        finally
        {
            Marshal.FreeHGlobal(ptrBuf);
        }
    }

    return list;
}

대개의 경우, ETW Consumer를 만들 때 저런 식으로 열람할 일은 없을 것입니다. 대신 자신이 만드는 세션 이름으로 이미 등록된 적이 있는지 알아야 할 필요는 있는데 이를 위해 QueryTrace Win32 API를 사용할 수 있습니다.

// EventTraceWatcher
// ; https://www.nuget.org/packages/EventTraceWatcher/
// ; ./src/EventTraceWatcher.cs LoadExistingEventTraceProperties

public static bool IsSessionActive(string sessionName)
{
    EventTraceProperties prop = new EventTraceProperties(true);
    int status = NativeMethods.QueryTrace(0, sessionName, ref prop);

    if (status == 0)
    {
        return true;
    }
    else if (status == EventTraceProperties.ERROR_WMI_INSTANCE_NOT_FOUND)
    {
        // The instance name passed was not recognized as valid by a WMI data provider.
        return false;
    }
              
    throw new System.ComponentModel.Win32Exception(status);
}

/*
Console.WriteLine("Active == " + IsSessionActive("EventLog-Application"));
// Active == True
*/




예전에 썼던 글에서 EventTraceWatcher를 소개한 적이 있는데요, 해당 클래스를 사용해 보면,

// How to consume ETW events from C#
// ; https://learn.microsoft.com/en-us/archive/blogs/danielvl/how-to-consume-etw-events-from-c

using System;
using Microsoft.Samples.Eventing;

class Program
{
    static void Main()
    {
        try
        {
            new Program().Run();
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex);
        }
    }

    private void Run()
    {
        Guid RewriteProviderId = new Guid("0469abfa-1bb2-466a-b645-e3e15a02f38b");

        using (EventTraceWatcher watcher = new EventTraceWatcher("Rewrite", RewriteProviderId))
        {

            watcher.EventArrived += delegate (object sender, EventArrivedEventArgs e) {

                if (e.Error != null)
                {
                    Console.Error.WriteLine(e.Error);
                    Environment.Exit(-1);
                }

                Console.WriteLine("Event Name: " + e.EventId);

                foreach (var p in e.Properties)
                {
                    Console.WriteLine("\t" + p.Key + " -- " + p.Value);
                }

                Console.WriteLine();
            };

            watcher.Start();

            Console.WriteLine("Press <Enter> to exit");
            Console.ReadLine();

            watcher.Stop();
        }
    }
}

프로세스가 정상 종료하면서 watcher.Stop() 코드가 실행되었음에도 여전히 "Rewrite"라는 이름의 세션이 살아 있는 것을 "logman query -ets" 명령어로 확인할 수 있습니다. 사실 다른 커널 리소스 핸들과 달리, ETW 핸들은 (EXE) 프로세스의 종료에 상관이 없어야 하는 것이 맞습니다. 하지만 위의 경우에는 프로세스가 종료하면 ETW 세션도 닫히기를 원하는 상황인데, 게다가 소스 코드로 디버깅해 보면 분명히 using 문으로 인한 finally에 의해 Dispose가 실행되었고, 그에 따라 StopTrace와 CloseTrace가 실행되었지만 여전히 ETW 세션이 안 닫힙니다.

이 경우 StopTrace의 반환값은, 0x1069(0n4201) 값으로 C++ 헤더 파일에서 다음과 같이 설명하고 있습니다.

//
// MessageId: ERROR_WMI_INSTANCE_NOT_FOUND
//
// MessageText:
//
// The instance name passed was not recognized as valid by a WMI data provider.
//
#define ERROR_WMI_INSTANCE_NOT_FOUND     4201L

어쨌든, 이렇게 (의도치 않게) 살아 있는 세션을 닫으려면 logman을 이용해 다음과 같은 식의 명령어를 실행해야 합니다.

logman stop <SessionName> -ets

예) logman stop Rewrite -ets

코드로 이것을 구현하려면 ControlTrace API를 사용하는데,

// ControlTraceW function
// ; https://learn.microsoft.com/en-us/windows/win32/api/evntrace/nf-evntrace-controltracew

public const uint EVENT_TRACE_CONTROL_QUERY = 0;
public const uint EVENT_TRACE_CONTROL_STOP = 1;
public const uint EVENT_TRACE_CONTROL_UPDATE = 2;

public static void CloseActiveSession(string sessionName)
{
    if (IsSessionActive(sessionName, out _) == true)
    {
        EventTraceProperties prop = new EventTraceProperties();
        prop.Initialize();

        NativeMethods.ControlTrace(0, sessionName, ref prop, EVENT_TRACE_CONTROL_STOP);
    }
}

public static int CloseActiveSession(ulong sessionHandle)
{
    EventTraceProperties prop = new EventTraceProperties();
    prop.Initialize();

    return NativeMethods.ControlTrace(sessionHandle, null, ref prop, EVENT_TRACE_CONTROL_STOP);
}

문서에 보면 ControlTrace가 StopTrace 함수를 대체한다고 쓰여있기는 합니다. 하지만 그렇다고 해도 StopTrace 호출이 세션을 닫지 못한다는 것은 이해가 안 됩니다. 참고로, 보다 더 최근에 나왔던 "Microsoft.Diagnostics.Tracing.TraceEvent" 라이브러리에서는 StopTrace는 아예 호출도 안 하고 ControlTrace로 세션을 닫고 있습니다.

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




규칙을 알 수 없지만, 가끔씩 logman query에 오류가 발생하는 경우가 있습니다.

C:\Windows\System32> logman query -ets

Data Collector Set                      Type                          Status
-------------------------------------------------------------------------------

Error:
The GUID passed was not recognized as valid by a WMI data provider.

그래서 그런지, 저렇게 열거하는 QueryAllTraces API도 가끔씩 호출이 실패하는 경우가 있는데 ^^; 원인을 모르겠습니다.




ETW 관련 오류 코드들은 "C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared\winerror.h" 헤더 파일에서 찾을 수 있으며 주로 다음의 오류코드들을 볼 수 있을 것입니다.

int result = NativeMethods.CloseTrace(this.traceHandle);

//
// MessageId: ERROR_CTX_CLOSE_PENDING
//
// MessageText:
//
// A close operation is pending on the session.
//
#define ERROR_CTX_CLOSE_PENDING          7007L 

int result = NativeMethods.StopTrace(this.sessionHandle, this.loggerName, out properties /*as statistics*/);

//
// MessageId: ERROR_BAD_LENGTH
//
// MessageText:
//
// The program issued a command but the command length is incorrect.
//
#define ERROR_BAD_LENGTH                 24L

//
// MessageId: ERROR_INVALID_HANDLE
//
// MessageText:
//
// The handle is invalid.
//
#define ERROR_INVALID_HANDLE             6L

//
// MessageId: ERROR_INVALID_PARAMETER
//
// MessageText:
//
// The parameter is incorrect.
//
#define ERROR_INVALID_PARAMETER          87L    // dderror




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 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)
13173정성태11/27/20225272.NET Framework: 2072. 닷넷 응용 프로그램의 스레드 스택 크기 변경
13172정성태11/25/20225126.NET Framework: 2071. 닷넷에서 ESP/RSP 레지스터 값을 구하는 방법파일 다운로드1
13171정성태11/25/20224697Windows: 214. 윈도우 - 스레드 스택의 "red zone"
13170정성태11/24/20225019Windows: 213. 윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?
13169정성태11/23/20225616Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
13168정성태11/22/20224883제니퍼 .NET: 31. 제니퍼 닷넷 적용 사례 (9) - DB 서비스에 부하가 걸렸다?!
13167정성태11/21/20224937.NET Framework: 2070. .NET 7 - Console.ReadKey와 리눅스의 터미널 타입
13166정성태11/20/20224657개발 환경 구성: 651. Windows 사용자 경험으로 WSL 환경에 dotnet 런타임/SDK 설치 방법
13165정성태11/18/20224576개발 환경 구성: 650. Azure - "scm" 프로세스와 엮인 서비스 모음
13164정성태11/18/20225487개발 환경 구성: 649. Azure - 비주얼 스튜디오를 이용한 AppService 원격 디버그 방법
13163정성태11/17/20225422개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226489.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20225731.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20225637.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20228819.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225133오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20225789.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20226685.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/20226209디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
13154정성태11/3/20225682.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo파일 다운로드1
13153정성태11/2/20226955.NET Framework: 2062. C# - 코드로 재현하는 소켓 상태(SYN_SENT, SYN_RECV)
13152정성태11/1/20225582.NET Framework: 2061. ASP.NET Core - DI로 추가한 클래스의 초기화 방법 [1]
13151정성태10/31/20225691C/C++: 161. Windows 11 환경에서 raw socket 테스트하는 방법파일 다운로드1
13150정성태10/30/20225736C/C++: 160. Visual Studio 2022로 빌드한 C++ 프로그램을 위한 다른 PC에서 실행하는 방법
13149정성태10/27/20225663오류 유형: 825. C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제파일 다운로드1
13148정성태10/26/20225656오류 유형: 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
... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...