Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 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 사용 예제 코드 (2) NT Kernel Logger

지난 글에 이어,

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

이번에는 ETW Consumer를 Win32 API를 이용해 작성해 보겠습니다.




우선 세션을 먼저 생성해야 하는데 이를 위해 StartTrace API를 사용할 수 있습니다.

string sessionName = NativeMethods.KERNEL_LOGGER_NAME; // KERNEL_LOGGER_NAME == "NT Kernel Logger"

EventTraceProperties prop = new EventTraceProperties(true, sessionName, NativeMethods.SystemTraceControlGuid); // SystemTraceControlGuid == 9e814aad-3204-11d2-9a82-006008a86939

result = NativeMethods.StartTrace(out sessionHandle, sessionName, ref prop);

위의 코드는 (xperf -providers 출력 결과의) ETW Provider 중 "Windows Kernel Trace" (9e814aad-3204-11d2-9a82-006008a86939)를 사용하는 코드로 예를 든 것입니다. 주의할 것은, SystemTraceControlGuid의 경우 반드시 세션 이름을 "NT Kernel Logger"로 해야 한다는 건데, 이런 사실은 다음의 글을 통해 알게 되었습니다.

THE WORST API EVER MADE
; https://caseymuratori.com/blog_0025

Configuring and Starting the NT Kernel Logger Session
; https://learn.microsoft.com/en-us/windows/win32/etw/configuring-and-starting-the-nt-kernel-logger-session

(제목에서 볼 수 있는 것처럼, 저 개인적으로도 ETW 관련 API의 이름이나 사용법이 체계적이지 않음을 100% 공감합니다. ^^;)

저렇게 세션을 생성했으면, (이전에 StartTrace라는 이름의 API를 호출했음에도) "Trace"를 "시작"하기 위해 OpenTrace API를 호출해야 합니다.

EventTraceLogfile logFile = new EventTraceLogfile();
logFile.LoggerName = sessionName;
logFile.EventRecordCallback = EventRecordCallback;

logFile.ProcessTraceMode = NativeMethods.PROCESS_TRACE_MODE_EVENT_RECORD | NativeMethods.PROCESS_TRACE_MODE_REAL_TIME
    | NativeMethods.PROCESS_TRACE_MODE_RAW_TIMESTAMP;
traceHandle = NativeMethods.OpenTrace(ref logFile);

static private void EventRecordCallback([In] ref EventRecord eventRecord)
{
    Console.WriteLine(DateTime.Now + ": " + eventRecord.EventHeader.ProcessId);
}

위의 코드는 이벤트가 발생했을 시 콜백을 실행하라고 등록하는데 원한다면 파일로도 지정할 수 있습니다. 하지만, 이렇게 등록했다고 해서 trace로 인한 콜백이 호출되는 것은 아닙니다. 콜백이 호출되려면 이후 ProcessTrace API를 호출해야 하는데, 이 함수는 호출 스레드를 블록시키기 때문에 보통 새로운 스레드를 생성해 호출하는 식으로 구현합니다.

new Thread((ThreadStart)(
() =>
{
    ProcessTrace(traceHandle);
})).Start();

Console.WriteLine("Press ENTER key to exit...");
Console.ReadLine();

public static int ProcessTrace(ulong traceHandle)
{
    ulong[] handles = { traceHandle };
    int result = NativeMethods.ProcessTrace(handles, (uint)handles.Length, IntPtr.Zero, IntPtr.Zero);
    return result;
}

마지막으로, ProcessTrace의 blocking 상태를 해제하려면 CloseTrace를 호출하고,

NativeMethods.CloseTrace(traceHandle);

세션까지 완전히 종료하려면 ControlTrace 호출로 마무리를 합니다.

// https://www.sysnet.pe.kr/2/0/12292#control_trace
EtwInterop.CloseActiveSession(sessionName);




"Windows Kernel Trace"의 경우, 기본적인 사용법은 위와 같은 순서로 구현할 수 있지만 한 가지 설명해야 할 것이 더 있습니다. 이에 대해서는 EVENT_TRACE_PROPERTIES 구조체 문서를 확인해야 하는데,

EVENT_TRACE_PROPERTIES structure
; https://learn.microsoft.com/en-us/windows/win32/api/evntrace/ns-evntrace-event_trace_properties

위의 글에 보면, "system logger" 유형인 경우 "EnableFlags"에 설정할 수 있는 값들을 설명하고 있습니다.

//
// Enable flags for Kernel Events
//
#define EVENT_TRACE_FLAG_PROCESS            0x00000001  // process start & end
#define EVENT_TRACE_FLAG_THREAD             0x00000002  // thread start & end
#define EVENT_TRACE_FLAG_IMAGE_LOAD         0x00000004  // image load

#define EVENT_TRACE_FLAG_DISK_IO            0x00000100  // physical disk IO
#define EVENT_TRACE_FLAG_DISK_FILE_IO       0x00000200  // requires disk IO

#define EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS 0x00001000  // all page faults
#define EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS 0x00002000  // hard faults only

#define EVENT_TRACE_FLAG_NETWORK_TCPIP      0x00010000  // tcpip send & receive

#define EVENT_TRACE_FLAG_REGISTRY           0x00020000  // registry calls
#define EVENT_TRACE_FLAG_DBGPRINT           0x00040000  // DbgPrint(ex) Calls

//
// Enable flags for Kernel Events on Vista and above
//
#define EVENT_TRACE_FLAG_PROCESS_COUNTERS   0x00000008  // process perf counters
#define EVENT_TRACE_FLAG_CSWITCH            0x00000010  // context switches
#define EVENT_TRACE_FLAG_DPC                0x00000020  // deferred procedure calls
#define EVENT_TRACE_FLAG_INTERRUPT          0x00000040  // interrupts
#define EVENT_TRACE_FLAG_SYSTEMCALL         0x00000080  // system calls

#define EVENT_TRACE_FLAG_DISK_IO_INIT       0x00000400  // physical disk IO initiation
#define EVENT_TRACE_FLAG_ALPC               0x00100000  // ALPC traces
#define EVENT_TRACE_FLAG_SPLIT_IO           0x00200000  // split io traces (VolumeManager)

#define EVENT_TRACE_FLAG_DRIVER             0x00800000  // driver delays
#define EVENT_TRACE_FLAG_PROFILE            0x01000000  // sample based profiling
#define EVENT_TRACE_FLAG_FILE_IO            0x02000000  // file IO
#define EVENT_TRACE_FLAG_FILE_IO_INIT       0x04000000  // file IO initiation

//
// Enable flags for Kernel Events on Win7 and above
//
#define EVENT_TRACE_FLAG_DISPATCHER         0x00000800  // scheduler (ReadyThread)
#define EVENT_TRACE_FLAG_VIRTUAL_ALLOC      0x00004000  // VM operations

//
// Enable flags for Kernel Events on Win8 and above
//
#define EVENT_TRACE_FLAG_VAMAP              0x00008000  // map/unmap (excluding images)
#define EVENT_TRACE_FLAG_NO_SYSCONFIG       0x10000000  // Do not do sys config rundown

//
// Enable flags for Kernel Events on Threshold and above
//
#define EVENT_TRACE_FLAG_JOB                0x00080000  // job start & end
#define EVENT_TRACE_FLAG_DEBUG_EVENTS       0x00400000  // debugger events (break/continue/...)

예를 들어, 이 중에서 EVENT_TRACE_FLAG_PROCESS 플래그는 프로세스의 생성/종료에 대한 이벤트를 받을 수 있게 합니다. 따라서, 다음과 같이 설정해 주면,

EventTraceProperties prop = new EventTraceProperties(true, sessionName, NativeMethods.SystemTraceControlGuid);
prop.SetFlags(NativeMethods.EVENT_TRACE_FLAG_PROCESS);

result = NativeMethods.StartTrace(out sessionHandle, sessionName, ref prop);

이후 (EXE) 프로세스 생성/종료마다 이벤트 콜백 함수가 실행됩니다.

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




참고로 아래의 문서에도 나오지만,

Controlling Event Tracing Sessions
; https://learn.microsoft.com/en-us/windows/win32/etw/controlling-event-tracing-sessions

ETW 세션을 다루는 방식이 여러 가지이므로 자신이 사용하려는 Provider에 따라 저 문서를 보고 어느 유형에 속하는지 선택해 코딩을 해야 합니다.




이 글에서 EVENT_TRACE_FLAG_PROCESS를 설정한 "Windows Kernel Trace" 동작은 지난 글에서 설명한,

C# - 특정 EXE 프로세스를 종료시킨 EXE를 찾아내는 방법
; https://www.sysnet.pe.kr/2/0/11172

"Microsoft-Windows-Kernel-Audit-API-Calls" ETW provider를 통해서도 유사하게 구현할 수 있습니다. 이에 대해서는 다음번 글에서 살펴보겠습니다.




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







[최초 등록일: ]
[최종 수정일: 6/28/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  [113]  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11100정성태11/7/201628884개발 환경 구성: 304. Wi-Fi Direct 지원 여부 확인 방법 [1]
11099정성태11/7/201630791.NET Framework: 620. C#에서 C/C++ 함수로 콜백 함수를 전달하는 예제 코드파일 다운로드1
11098정성태11/7/201620124오류 유형: 368. 빌드 이벤트에서 robocopy 사용 시 $(TargetDir) 매크로를 지정하는 경우 오류 발생
11097정성태11/7/201623066오류 유형: 367. go install: no install location for directory [...경로...] outside GOPATH
11096정성태11/6/201626840디버깅 기술: 83. PDB 파일을 수동으로 다운로드하는 방법
11095정성태11/6/201623104.NET Framework: 619. C# - Cognitive Services 중의 하나인 Face API를 사용해 얼굴 인식 및 흐림(blur) 효과 적용 [1]파일 다운로드1
11094정성태11/5/201624788VC++: 105. Visual Studio 2013/2015 - Ceemple OpenCV 확장을 이용한 웹캠 영상 출력
11093정성태11/4/201624702웹: 34. Edge 브라우저도 지원하는 클립보드 복사를 위한 자바스크립트 코드
11092정성태11/3/201631619.NET Framework: 618. C# - NAudio를 이용한 MP3 파일 재생 [5]파일 다운로드1
11091정성태11/3/201626321VC++: 104. std::call_once를 이용해 thread-safe한 Singleton 객체 생성파일 다운로드1
11090정성태11/1/201627786VC++: 103. C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드 [9]파일 다운로드1
11089정성태11/1/201626769디버깅 기술: 82. Windows 10을 위한 Symbol(PDB) 파일 내려받는 방법 [2]
11088정성태11/1/201630829.NET Framework: 617. C# - AForge.NET을 이용한 MP4 동영상 파일 재생 [7]파일 다운로드1
11087정성태11/1/201625203.NET Framework: 616. AForge.Video.FFMPEG를 최신 버전의 ffmpeg 파일로 의존성을 변경하는 방법파일 다운로드1
11086정성태11/1/201619091오류 유형: 366. The Microsoft Passport Container service terminated with the following error: General access denied error
11085정성태10/27/201633474.NET Framework: 615. C# - AForge.NET을 이용한 웹캠 영상 출력 [2]파일 다운로드1
11084정성태10/26/201621416오류 유형: 365. The User Profile Service service failed to the sign-in.
11083정성태10/26/201627995Windows: 131. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선 순위 조정 기능 [1]
11082정성태10/26/201629936.NET Framework: 614. C# - DateTime.Ticks의 정밀도 [4]파일 다운로드1
11081정성태10/26/201620423오류 유형: 364. You need to fix your Microsoft Account for apps on your other devices to be able to launch apps and continue experiences on this device.
11080정성태10/24/201623569Windows: 130. Windows Server 2016 Nano 서버 설치 방법
11079정성태10/21/201620703Windows: 129. Windows Server 2016 설치 CD에 있는 Convert-WindowsImage.ps1 사용 방법 정리
11078정성태10/21/201622035Windows: 128. Windows Server 2016 Nano 서버 VHD 이미지 만드는 방법 - TP5 기준
11077정성태10/21/201620528오류 유형: 363. Active Directory 서버의 NETLOGON 서비스가 멈췄을 때 발생하는 문제
11076정성태10/21/201620096오류 유형: 362. 윈도우 백업 시 오류 - 0x80780040
11075정성태10/20/201621008Windows: 127. Convert-WindowsImage.ps1 사용 방법 정리
... 106  107  108  109  110  111  112  [113]  114  115  116  117  118  119  120  ...