### Single Process Tracing (New) with wtrace Source: https://context7.com/lowleveldesign/wtrace/llms.txt Examples of starting a new process with wtrace and immediately beginning to trace its activities. This covers starting processes like notepad or powershell, tracing specific handlers, running in a new console, and saving the trace output to a file. ```bash # Start and trace notepad opening test.txt wtrace notepad c:\\temp\\test.txt # Trace PowerShell script execution with File I/O and registry wtrace --handlers file,registry powershell.exe -File script.ps1 # Start process in new console and trace with children wtrace --newconsole -c cmd.exe /c dir # Save trace output to file wtrace --save trace.json --output json notepad.exe ``` -------------------------------- ### Install wtrace using Chocolatey Source: https://github.com/lowleveldesign/wtrace/blob/master/README.md This code snippet demonstrates how to install the wtrace tool using the Chocolatey package manager. Chocolatey is a popular package manager for Windows, simplifying software installation and management. ```powershell choco install wtrace ``` -------------------------------- ### Start wtrace with Registry and TCP Handlers Source: https://github.com/lowleveldesign/wtrace/blob/master/README.md This command initiates a system-wide trace using the 'registry' and 'tcp' handlers. It captures events related to both registry access and TCP network activity. ```bash wtrace --handlers registry,tcp ``` -------------------------------- ### Tracing a Single Process by PID or Executable Source: https://github.com/lowleveldesign/wtrace/blob/master/README.md Demonstrates how to trace a specific running process by its ID or by starting a new process. Includes tracing child processes. ```bash # Trace File I/O operations of the process with id 1234 and its children wtrace -f “name >= FileIO/” -c 1234 # Start and trace the opening of the test.txt file by notepad.exe wtrace notepad c:\temp\test.txt ``` -------------------------------- ### System-wide Tracing with Event Filters Source: https://github.com/lowleveldesign/wtrace/blob/master/README.md Examples of tracing system-wide with specific event handlers and filters. Useful for monitoring file write or RPC events across all processes. ```bash # show File write events from all the processes wtrace --handlers file -f ‘eventname=FileIO/Write’ # show RPC events from all the processes wtrace --handlers rpc ``` -------------------------------- ### Example wtrace Output and Disassembly Source: https://github.com/lowleveldesign/wtrace/wiki/Tracing-RPC Demonstrates the typical output format of wtrace for RPC client calls and breaks down a sample log entry. This helps in understanding the various components of a traced RPC event, including timestamps, process/thread IDs, event names, protocols, interface UUIDs, endpoints, and procedure numbers. ```text 4317.5999 (8424.15088) RpcClientCall/Stop --- NamedPipes --> 6bffd098-a112-3610-9833-46c3f87e345a (\PIPE\wkssvc) 11 4317.7007 (8424.15088) RpcClientCall/Start --- LRPC --> 53825514-1183-4934-a0f4-cfdc51c3389b (LSMApi) 0 NULL 4317.8605 (8424.15088) RpcServerCall/Start <-- LRPC --- 53825514-1183-4934-a0f4-cfdc51c3389b (LSMApi) 0 NULL (96.5612) 4317.9506 (96.5612) RpcServerCall/Stop <-- LRPC --- 53825514-1183-4934-a0f4-cfdc51c3389b (LSMApi) 0 NULL (96.5612) 4317.9738 (8424.15088) RpcClientCall/Stop --- LRPC --> 53825514-1183-4934-a0f4-cfdc51c3389b (LSMApi) 0 NULL 4318.0247 (8424.15088) RpcClientCall/Start --- NamedPipes --> c8cb7687-e6d3-11d2-a958-00c04f682e16 (\PIPE\DAV RPC SERVICE) 17 4318.3643 (8424.15088) RpcClientCall/Stop --- NamedPipes --> c8cb7687-e6d3-11d2-a958-00c04f682e16 (\PIPE\DAV RPC SERVICE) 17 4318.3937 (8424.15088) RpcClientCall/Start --- NamedPipes --> c8cb7687-e6d3-11d2-a958-00c04f682e16 (\PIPE\DAV RPC SERVICE) 17 4318.4732 (8424.15088) RpcClientCall/Stop --- NamedPipes --> c8cb7687-e6d3-11d2-a958-00c04f682e16 (\PIPE\DAV RPC SERVICE) 17 4318.4821 (8424.15088) RpcClientCall/Start --- NamedPipes --> c8cb7687-e6d3-11d2-a958-00c04f682e16 (\PIPE\DAV RPC SERVICE) 5 4318.5838 (8424.15088) RpcClientCall/Stop --- NamedPipes --> c8cb7687-e6d3-11d2-a958-00c04f682e16 (\PIPE\DAV RPC SERVICE) 5 ``` ```text 4317.5999 - time in ms from the trace start (8424.15088) - process and thread ID of the client RpcClientCall/Stop - event name NamedPipes - protocol used in the RPC communication 6bffd098-a112-3610-9833-46c3f87e345a - InterfaceUuid (\PIPE\wkssvc) - RPC endpoint name 11 - procedure number ``` -------------------------------- ### JSON Output Format with wtrace Source: https://context7.com/lowleveldesign/wtrace/llms.txt Examples of configuring wtrace to output captured trace events in JSON format. This is useful for programmatic processing of trace data. Includes examples for outputting to the console and saving directly to a file, with automatic detection of JSON format via file extension. ```bash # Output to console in JSON format wtrace --output json --handlers tcp notepad.exe # Save JSON output to file wtrace --save events.json --output json --handlers file,tcp chrome.exe # JSON format auto-detected by file extension wtrace --save trace.json notepad.exe ``` -------------------------------- ### System-Wide Tracing with wtrace Source: https://context7.com/lowleveldesign/wtrace/llms.txt Examples of tracing all processes on the system using wtrace. This includes tracing specific event types like File I/O or RPC calls, setting output format to JSON, and filtering events based on criteria such as IP address ranges. ```bash # Trace all File I/O write operations system-wide wtrace --handlers file -f "name=FileIO/Write" # Trace all RPC calls with JSON output wtrace --handlers rpc --output json # Trace TCP/IP and UDP events with path filtering wtrace --handlers tcp,udp -f "path >= 192.168" ``` -------------------------------- ### RPC Tracing and Symbol Resolution with wtrace Source: https://context7.com/lowleveldesign/wtrace/llms.txt Shows how to trace Remote Procedure Call (RPC) events using wtrace and resolve procedure names using debug symbols. This includes examples with automatic symbol resolution via environment variables and explicit symbol path specification. ```bash # Trace RPC with automatic symbol resolution (requires _NT_SYMBOL_PATH env var) wtrace --handlers rpc,image notepad.exe # Trace RPC with explicit symbol path wtrace --handlers rpc,image --symbols "SRV*C:\\symbols*https://msdl.microsoft.com/download/symbols" -v notepad.exe # Output shows resolved procedure names in summary: # fb8a0729-2d04-4658-be93-27b4ad553fac (ncalrpc:[lsapolicylookup]) [5]{LsaLookuprGetDomainInfo} calls: 2 ``` -------------------------------- ### F# RPC ETW Handler Creation and Event Handling Source: https://context7.com/lowleveldesign/wtrace/llms.txt This F# code defines how to create an ETW (Event Tracing for Windows) handler for RPC (Remote Procedure Call) events. It includes setting up providers, initializing state for pending RPC calls, and handling the start of an RPC client call by capturing binding information, UUID, and procedure number. ```fsharp // F# code example from wtrace.cmd/Events/Rpc.fs // Create RPC ETW handler let createEtwHandler () = { KernelFlags = NtKeywords.None KernelStackFlags = NtKeywords.None KernelRundownFlags = NtKeywords.None Providers = Array.singleton { Id = MicrosoftWindowsRPCTraceEventParser.ProviderGuid Name = "Microsoft-Windows-RPC" Level = TraceEventLevel.Verbose Keywords = UInt64.MaxValue RundownLevel = TraceEventLevel.Verbose RundownKeywords = 0UL } Initialize = fun broadcast -> ({ Broadcast = broadcast PendingRpcCalls = DataCache>(256) } :> obj) Subscribe = subscribe } // Handle RPC client call start let handleRpcClientCallStart id state (ev : RpcClientCallStartArgs) = let binding = constructBindingString ev.Endpoint ev.Protocol ev.Options let fields = [| struct ("Binding", FText binding) struct ("InterfaceUuid", FGuid ev.InterfaceUuid) struct ("ProcNum", FI32 ev.ProcNum) |] let path = sprintf "%s (%s) [%d]" (ev.InterfaceUuid.ToString()) binding ev.ProcNum let activityId = sprintf "RPC#%s" (ev.ActivityID.ToString()) let rpcev = (toEvent ev id "RPC/ClientCallStart" activityId path "" WinApi.eventStatusUndefined) state.PendingRpcCalls.[ev.ActivityID] <- (rpcev, fields) TraceEventWithFields (rpcev, fields |> Array.map (toEventField id)) |> state.Broadcast.publishTraceEvent ``` -------------------------------- ### Event Filtering with wtrace Source: https://context7.com/lowleveldesign/wtrace/llms.txt Illustrates the use of wtrace's event filtering capabilities to reduce the volume of captured data. Examples include filtering by process name, event name patterns, path prefixes, and combining multiple filter types using AND logic. ```bash # Filter by process name (multiple filters OR-ed) wtrace -f "pname = notepad" -f "pname = notepad2" # Filter by event name pattern wtrace -f "name ~ FileIO" -f "name >= tcp" # Filter by path with start pattern wtrace -f "path >= d:\\temp" # Combine multiple filter types (AND-ed when different keywords) wtrace -f "pname = chrome" -f "name >= tcp" -f "level <= 4" # Filter by process ID wtrace -f "pid = 1234" -f "name <> Process/Start" ``` -------------------------------- ### F# Event Filtering System Source: https://context7.com/lowleveldesign/wtrace/llms.txt This F# code outlines the event filtering system, focusing on parsing filter expressions from command-line arguments. It demonstrates how to extract filter strings, parse them into individual filter functions, and then build a composite filter function. The comments explain the syntax for filter keywords (like 'pid', 'pname') and operators, and provide examples. ```fsharp // F# code example - filter parsing from wtrace.cmd/Program.fs // Parse filters from command line let parseFilters args = try let filters = args |> Map.tryFind "f" |> Option.defaultValue [] let filterFunctions = filters |> List.map EventFilter.parseFilter // Filters with same keyword are OR-ed, different keywords are AND-ed // Example: -f "pname = notepad" -f "pname = chrome" -f "name >= tcp" Ok (EventFilter.buildFilterFunction filterFunctions) with | EventFilter.ParseError msg -> Error msg // Filter keywords: pid, pname, name, level, path, details // Operators: =, <>, <=, >=, ~ // Example filter: -f "pid = 1234", -f "name ~ FileIO", -f "level <= 4" ``` -------------------------------- ### F# File I/O Event Handler for ETW Source: https://context7.com/lowleveldesign/wtrace/llms.txt Defines an F# handler for capturing File I/O operations through ETW. It configures kernel flags and stack flags for File I/O events and provides an example of handling a File I/O Create event, including mapping file names and queuing pending events. ```fsharp // F# code example from wtrace.cmd/Events/FileIO.fs // Create File I/O ETW handler let createEtwHandler () = { KernelFlags = NtKeywords.FileIOInit ||| NtKeywords.FileIO KernelStackFlags = NtKeywords.FileIO KernelRundownFlags = NtKeywords.DiskFileIO ||| NtKeywords.DiskIO Providers = Array.empty Initialize = fun broadcast -> ({ Broadcast = broadcast PendingFileIo = DataCache>(256) FileIdToName = Dictionary() } :> obj) Subscribe = subscribe } // Example handling FileIO Create event let handleFileIoCreate state (ev : FileIOCreateTraceData) = mapFileNameToFileId state ev.FileObject ev.FileName let createDisposition = sprintf "%A" ev.CreateDisposition let createOptions = int32 ev.CreateOptions let fields = [| struct (nameof ev.CreateDisposition, FText createDisposition) struct (nameof ev.CreateOptions, FI32 createOptions) struct (nameof ev.FileAttributes, FText (sprintf "%A" ev.FileAttributes)) struct (nameof ev.ShareAccess, FText (fileShareStr ev.ShareAccess)) |] let details = sprintf "disposition: %s, options: 0x%X" createDisposition createOptions queuePendingEvent state ev ev.IrpPtr ev.FileObject ev.FileName fields details ``` -------------------------------- ### F# TCP/IP Event Handler for ETW Source: https://context7.com/lowleveldesign/wtrace/llms.txt An F# handler designed for capturing network TCP/IP events via ETW. It sets the necessary kernel flags for network events and provides an example of handling a TCP connect event, including extracting connection details and publishing trace events. ```fsharp // F# code example from wtrace.cmd/Events/TcpIp.fs // Create TCP/IP ETW handler let createEtwHandler () = { KernelFlags = NtKeywords.NetworkTCPIP KernelStackFlags = NtKeywords.NetworkTCPIP KernelRundownFlags = NtKeywords.None Providers = Array.empty Initialize = fun broadcast -> ({ Broadcast = broadcast } :> obj) Subscribe = subscribe } // Handle TCP connect event let handleTcpIpConnect id state (ev : TcpIpConnectTraceData) = let fields = [| struct (nameof ev.connid, FUI64 ev.connid) struct (nameof ev.seqnum, FI32 ev.seqnum) struct (nameof ev.mss, FI32 ev.mss) struct (nameof ev.size, FI32 ev.size) |] let details = sprintf "conn: %d, seq: %d" ev.connid ev.seqnum let path = sprintf "%s:%d -> %s:%d" (ev.saddr.ToString()) ev.sport (ev.daddr.ToString()) ev.dport let activityId = sprintf "conn#%d" ev.connid let ev = toEvent ev id activityId path details WinApi.eventStatusUndefined state.Broadcast.publishTraceEvent (TraceEventWithFields (ev, fields |> Array.map (toEventField id))) ``` -------------------------------- ### Advanced Event Filtering in Wtrace Source: https://github.com/lowleveldesign/wtrace/blob/master/README.md Illustrates complex filtering scenarios using multiple -f options to specify process names, paths, and event types. ```bash # Trace system-wide and filter events for processes which name # is either notepad or notepad2 and the path starts with "d:\temp" wtrace -f “pname = notepad” -f “pname = notepad2” -f “path >= d:\temp” # Trace a process with id 12572 and its children and show only TCP/IP events wtrace -f "name >= tcp" -c 12572 ``` -------------------------------- ### F# Command-Line Argument Parsing Source: https://context7.com/lowleveldesign/wtrace/llms.txt This F# code demonstrates parsing command-line arguments. It defines a set of recognized flags and uses a library function to parse them from the `argv`. It also includes a helper function to check if a specific flag is enabled and shows how to extract handler configurations, with error handling for invalid configurations. ```fsharp // F# code example - command line parsing from wtrace.cmd/Commons/CommandLine.fs // Parse command line with defined flags let flags = [| "s"; "system"; "c"; "children"; "newconsole"; "nosummary"; "v"; "verbose"; "h"; "?"; "help" |] let args = argv |> CommandLine.parseArgs flags // Check if flag is enabled let isSystemTrace args = [| "s"; "system" |] |> isFlagEnabled args // Extract handler configuration match args |> Map.tryFind "handlers" with | None -> createHandlers "process,image,file,rpc,tcp,udp" | Some [ handler ] -> createHandlers handler | _ -> Error ("Handlers can be specified only once.") ``` -------------------------------- ### Handler Selection with wtrace Source: https://context7.com/lowleveldesign/wtrace/llms.txt Demonstrates how to select specific ETW event handlers to enable during a trace session with wtrace. This includes enabling only registry and TCP handlers, tracing file and RPC events, and enabling the image handler for symbol resolution. ```bash # Enable only registry and TCP handlers wtrace --handlers registry,tcp # Trace file and RPC events wtrace --handlers file,rpc notepad.exe # Enable image handler for RPC method name resolution wtrace --handlers rpc,image --symbols "SRV*C:\\symbols*https://msdl.microsoft.com/download/symbols" ``` -------------------------------- ### wtrace Command-line Usage and Options Source: https://github.com/lowleveldesign/wtrace/blob/master/README.md This section details the command-line interface for wtrace, outlining available options for filtering events, specifying handlers, controlling tracing scope (system-wide, single process, children), and managing output. It also describes the syntax for defining filters based on keywords, operators, and values. ```bash Usage: wtrace [OPTIONS] [pid|imagename args] Options: -f, --filter=FILTER Displays only events which satisfy a given FILTER. (Does not impact the summary) --handlers=HANDLERS Displays only events coming from the specified HANDLERS. -c, --children Collects traces from the selected process and all its children. --newconsole Starts the process in a new console window. -s, --system Collect only system statistics (Processes and DPC/ISR) - shown in the summary. --nosummary Prints only ETW events - no summary at the end. -v, --verbose Shows wtrace diagnostics logs. -h, --help Shows this message and exits. The HANDLERS parameter is a list of handler names, separated with a comma. Accepted handlers include: process - only Process/Thread events (this handler is always enabled) file - File I/O events registry - Registry events (voluminous, disabled by default) rpc - RPC events (enable image handler to allow RPC method name resolution) tcp - TCP/IP events udp - UDP events image - image (module) events (load/unload) Example: --handlers 'tcp,file,registry' Each FILTER is built from a keyword, an operator, and a value. You may define multiple events (filters with the same keywords are OR-ed). Keywords include: pid - filtering on the proces ID pname - filtering on on the process name name - filtering on the event name level - filtering on the event level (1 [critical] - 5 [debug]) path - filtering on the event path details - filtering on the event details Operators include: =, <> (does not equal), <= (ends with), >= (starts with), ~ (contains) Example: -f 'pid = 1234', -f 'name ~ FileIO', -f 'level <= 4' ``` -------------------------------- ### Configure wtrace with Symbols for RPC Procedure Resolution Source: https://github.com/lowleveldesign/wtrace/blob/master/README.md This command runs wtrace for a specific executable ('notepad.exe') and configures the debugging symbols path. This is crucial for wtrace to resolve RPC procedure names, providing more context in the output. ```bash wtrace.exe --symbols="SRV*C:\\symbols\\*https://msdl.microsoft.com/download/symbols" -v notepad.exe ``` -------------------------------- ### Single Process Tracing (Existing) with wtrace Source: https://context7.com/lowleveldesign/wtrace/llms.txt Demonstrates how to attach wtrace to an already running process to capture its events. This includes tracing file operations and child processes, filtering by event name, and tracing all default events for a given PID. ```bash # Trace File I/O operations of process 1234 and its children wtrace --handlers file -c 1234 # Trace TCP connections of a specific process wtrace --handlers tcp -f "name >= tcp" 1234 # Trace all events (default handlers) for process 5678 wtrace 5678 ``` -------------------------------- ### F# TraceControl Module Functions for System Tracing Source: https://context7.com/lowleveldesign/wtrace/llms.txt Provides F# functions for managing trace sessions programmatically. It includes functionality to initiate system-only tracing and trace new processes, handling various configurations and dependencies. ```fsharp // F# code example from wtrace.cmd/TraceControl.fs // System-only tracing let traceSystemOnly ct = result { let settings = { Handlers = [| ProcessThread.createEtwHandler(); IsrDpc.createEtwHandler() |] EnableStacks = false } let etwObservable = createEtwObservable settings let tstate = TraceEventProcessor.init ProcessFilter.Everything Ignore ct.ProcessingCancellationToken let counters = TraceCounters.init () etwObservable |> Observable.subscribe (TraceCounters.update tstate counters) |> ignore use sub = initiateEtwSession etwObservable ct.TracingCancellationToken WaitHandle.WaitAny([| ct.TracingCancellationToken.WaitHandle; sessionWaitEvent |]) |> ignore return (tstate, counters) } // Trace a new process let traceNewProcess ct handlers filter showSummary debugSymbols outputFormat newConsole includeChildren args = result { let! processIds = WinApi.startProcessSuspended args newConsole return! ProcessApi.traceProcess ct handlers filter showSummary debugSymbols outputFormat includeChildren processIds } ``` -------------------------------- ### PowerShell Integration with wtrace Source: https://context7.com/lowleveldesign/wtrace/llms.txt Demonstrates how to integrate wtrace with PowerShell for real-time data filtering and analysis. This includes piping wtrace output to cmdlets like Select-String and using wtrace as a PowerShell module after renaming its executable. ```powershell # Filter FileIO/Write events using Select-String .\wtrace notepad | Select-String -SimpleMatch "FileIO/Write" # Use as PowerShell module (rename wtrace.exe to wtrace.dll) Import-Module .\wtrace.dll Invoke-Wtrace -Handlers "file,tcp" -ProcessName "notepad.exe" # IMPORTANT: Use Ctrl+Break (not Ctrl+C) to stop when using pipelines ``` -------------------------------- ### Piping wtrace Output to send2procmon Source: https://github.com/lowleveldesign/wtrace/wiki/Tracing-RPC This PowerShell command demonstrates how to capture wtrace output for RPC calls and send it directly to procmon for real-time analysis. Ensure procmon is running and recording before executing this command. It filters for lines containing 'Rpc.*Call' and pipes them to the send2procmon utility. ```powershell > .\wtrace notepad | select-string "Rpc.*Call" | send2procmon ``` -------------------------------- ### System Statistics Mode with wtrace Source: https://context7.com/lowleveldesign/wtrace/llms.txt Shows how to use wtrace in a statistics-only mode to collect system performance data such as Interrupt Service Routine (ISR) and Deferred Procedure Call (DPC) statistics, as well as process tree information, without logging detailed events. ```bash # Collect system statistics for performance analysis wtrace -s # The output includes process tree and DPC/ISR statistics at the end ``` -------------------------------- ### Filter wtrace output using Select-String in PowerShell Source: https://github.com/lowleveldesign/wtrace/wiki/PowerShell-support This method demonstrates a basic way to filter wtrace output in real-time using the `Select-String` cmdlet. It pipes the output of `wtrace.exe` directly to `Select-String` to filter specific event types like 'FileIO/Write'. Press Ctrl+Break to stop tracing when using pipelines. ```powershell > .\wtrace notepad | select-string -SimpleMatch "FileIO/Write" ``` -------------------------------- ### Define PowerShellWtraceEvent object for wtrace module in C# Source: https://github.com/lowleveldesign/wtrace/wiki/PowerShell-support This C# code defines the `PowerShellWtraceEvent` class, which represents the structure of events generated when `wtrace.exe` is loaded as a module (`wtrace.dll`). It includes properties for timestamp, process ID, thread ID, event name, and event details. ```csharp public class PowerShellWtraceEvent { public double TimeStampRelativeInMSec { get; set; } public int ProcessId { get; set; } public int ThreadId { get; set; } public string EventName { get; set; } public string EventDetails { get; set; } } ``` -------------------------------- ### Stop a Running wtrace ETW Session Source: https://github.com/lowleveldesign/wtrace/blob/master/README.md This command uses the 'logman' utility to stop a lingering wtrace ETW session named 'wtrace-rt'. This is a recovery step for when a wtrace session does not finish correctly and remains active. ```bash logman stop wtrace-rt -ets ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.