Microsoft MVP성태의 닷넷 이야기
.NET Framework: 932. C# - ETW 관련 Win32 API 사용 예제 코드 (1) [링크 복사], [링크+제목 복사],
조회: 12479
글쓴 사람
정성태 (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)
11995정성태7/23/201918920.NET Framework: 848. C# - smtp.daum.net 서비스(Implicit SSL)를 이용해 메일 보내는 방법 [2]
11994정성태7/22/201914421개발 환경 구성: 454. Azure 가상 머신(VM)에서 SMTP 메일 전송하는 방법파일 다운로드1
11993정성태7/22/20199878오류 유형: 561. Dism.exe 수행 시 "Error: 2 - The system cannot find the file specified." 오류 발생
11992정성태7/22/201911663오류 유형: 560. 서비스 관리자 실행 시 "Windows was unable to open service control manager database on [...]. Error 5: Access is denied." 오류 발생
11991정성태7/18/20199174디버깅 기술: 128. windbg - x64 환경에서 닷넷 예외가 발생한 경우 인자를 확인할 수 없었던 사례
11990정성태7/18/201911377오류 유형: 559. Settings / Update & Security 화면 진입 시 프로그램 종료
11989정성태7/18/201910279Windows: 162. Windows Server 2019 빌드 17763부터 Alt + F4 입력시 곧바로 로그아웃하는 현상
11988정성태7/18/201911714개발 환경 구성: 453. 마이크로소프트가 지정한 모든 Root 인증서를 설치하는 방법
11987정성태7/17/201916708오류 유형: 558. 윈도우 - KMODE_EXCEPTION_NOT_HANDLED 블루스크린(BSOD) 문제 [1]
11986정성태7/17/20199509오류 유형: 557. 드라이브 문자를 할당하지 않은 파티션을 탐색기에서 드라이브 문자와 함께 보여주는 문제
11985정성태7/17/20199632개발 환경 구성: 452. msbuild - csproj에 환경 변수 조건 사용 [1]
11984정성태7/9/201917833개발 환경 구성: 451. Microsoft Edge (Chromium)을 대상으로 한 Selenium WebDriver 사용법 [1]
11983정성태7/8/20198894오류 유형: 556. nodemon - 'mocha' is not recognized as an internal or external command, operable program or batch file.
11982정성태7/8/20198893오류 유형: 555. Visual Studio 빌드 오류 - result: unexpected exception occured (-1002 - 0xfffffc16)
11981정성태7/7/201911075Math: 64. C# - 3층 구조의 신경망(분류)파일 다운로드1
11980정성태7/7/201921509개발 환경 구성: 450. Visual Studio Code의 Java 확장을 이용한 간단한 프로젝트 구축파일 다운로드1
11979정성태7/7/201911047개발 환경 구성: 449. TFS에서 gitlab/github등의 git 서버로 마이그레이션하는 방법
11978정성태7/6/201910398Windows: 161. 계정 정보가 동일하지 않은 PC 간의 인증을 수행하는 방법 [1]
11977정성태7/6/201914958오류 유형: 554. git push - error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413 Request Entity Too Large
11976정성태7/4/20199321오류 유형: 553. (잘못 인증 한 후) 원격 git repo 재인증 시 "remote: HTTP Basic: Access denied" 오류 발생
11975정성태7/4/201917827개발 환경 구성: 448. Visual Studio Code에서 콘솔 응용 프로그램 개발 시 "입력"받는 방법
11974정성태7/4/201913183Linux: 22. "Visual Studio Code + Remote Development"로 윈도우 환경에서 리눅스(CentOS 7) C/C++ 개발
11973정성태7/4/201912399Linux: 21. 리눅스에서 공유 라이브러리가 로드되지 않는다면?
11972정성태7/3/201915272.NET Framework: 847. JAVA와 .NET 간의 AES 암호화 연동 [1]파일 다운로드1
11971정성태7/3/201912409개발 환경 구성: 447. Visual Studio Code에서 OpenCvSharp 개발 환경 구성
11970정성태7/2/201910733오류 유형: 552. 웹 브라우저에서 파일 다운로드 후 "Running security scan"이 끝나지 않는 문제
... 61  62  63  64  65  [66]  67  68  69  70  71  72  73  74  75  ...