Microsoft MVP성태의 닷넷 이야기
.NET Framework: 932. C# - ETW 관련 Win32 API 사용 예제 코드 (1) [링크 복사], [링크+제목 복사],
조회: 12483
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  72  73  [74]  75  ...
NoWriterDateCnt.TitleFile(s)
11795정성태12/19/201812652Windows: 154. PowerShell - Zone 별로 DNS 레코드 유형 정보 조회 [1]
11794정성태12/16/201810009오류 유형: 508. Get-AzureWebsite : Request to a downlevel service failed.
11793정성태12/16/201811648개발 환경 구성: 423. NuGet 패키지 제작 - Native와 Managed DLL을 분리하는 방법 [1]
11792정성태12/11/201812407Graphics: 34. .NET으로 구현하는 OpenGL (11) - Per-Pixel Lighting파일 다운로드1
11791정성태12/11/201812414VS.NET IDE: 130. C/C++ 프로젝트의 시작 프로그램으로 .NET Core EXE를 지정하는 경우 닷넷 디버깅이 안 되는 문제 [1]
11790정성태12/11/201810721오류 유형: 507. Could not save daemon configuration to C:\ProgramData\Docker\config\daemon.json: Access to the path 'C:\ProgramData\Docker\config' is denied.
11789정성태12/10/201820638Windows: 153. C# - USB 장치의 연결 및 해제 알림을 위한 WM_DEVICECHANGE 메시지 처리 [2]파일 다운로드2
11788정성태12/4/201810552오류 유형: 506. SqlClient - Value was either too large or too small for an Int32.Couldn't store <2151292191> in ... Column
11787정성태11/29/201814524Graphics: 33. .NET으로 구현하는 OpenGL (9), (10) - OBJ File Format, Loading 3D Models파일 다운로드1
11786정성태11/29/201811163오류 유형: 505. OpenGL.NET 예제 실행 시 "Managed Debugging Assistant 'CallbackOnCollectedDelegate'" 예외 발생
11785정성태11/21/201813594디버깅 기술: 120. windbg 분석 사례 - ODP.NET 사용 시 Finalizer에서 System.AccessViolationException 예외 발생으로 인한 비정상 종료
11784정성태11/18/201813289Graphics: 32. .NET으로 구현하는 OpenGL (7), (8) - Matrices and Uniform Variables, Model, View & Projection Matrices파일 다운로드1
11783정성태11/18/201811383오류 유형: 504. 윈도우 환경에서 docker가 설치된 컴퓨터 간의 ping IP 주소 풀이 오류
11782정성태11/18/201811152Windows: 152. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선순위 조정 기능 - 두 번째 이야기
11781정성태11/17/201813364개발 환경 구성: 422. SFML.NET 라이브러리 설정 방법 [1]파일 다운로드1
11780정성태11/17/201814839오류 유형: 503. vcpkg install bzip2 빌드 에러 - "Error: Building package bzip2:x86-windows failed with: BUILD_FAILED"
11779정성태11/17/201815225개발 환경 구성: 421. vcpkg 업데이트 [1]
11778정성태11/14/201813011.NET Framework: 803. UWP 앱에서 한 컴퓨터(localhost, 127.0.0.1) 내에서의 소켓 연결
11777정성태11/13/201812028오류 유형: 502. Your project does not reference "..." framework. Add a reference to "..." in the "TargetFrameworks" property of your project file and then re-run NuGet restore.
11776정성태11/13/201811278.NET Framework: 802. Windows에 로그인한 계정이 마이크로소프트의 계정인지, 로컬 계정인지 알아내는 방법
11775정성태11/13/201813827Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing파일 다운로드1
11774정성태11/8/201811685Graphics: 30. .NET으로 구현하는 OpenGL (4), (5) - Shader파일 다운로드1
11773정성태11/7/201811449Graphics: 29. .NET으로 구현하는 OpenGL (3) - Index Buffer파일 다운로드1
11772정성태11/6/201813727Graphics: 28. .NET으로 구현하는 OpenGL (2) - VAO, VBO파일 다운로드1
11771정성태11/5/201812903사물인터넷: 56. Audio Jack 커넥터의 IR 적외선 송신기 - 두 번째 이야기 [1]
11770정성태11/5/201819938Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리 [3]파일 다운로드1
... 61  62  63  64  65  66  67  68  69  70  71  72  73  [74]  75  ...