Newer
Older
TIASShot / scripts / verify / release_check_uia.ps1
# Helper for scripts/verify/run_release_check.py (release build check from outside the process).
# Uses System.Windows.Automation (UIAutomationClient, part of .NET Framework), MSAA (oleacc) and Get-WinEvent.
# No new dependencies. Output is one JSON document on stdout (UTF-8). The JSON tells whether the action succeeded.
#
# This file is ASCII only on purpose: Windows PowerShell 5.1 reads BOM-less scripts as the ANSI code page.
#
# Actions:
#   controls    -Hwnd <main window>  : list direct children of the main window (UI Automation), each with
#                                      automation_id, hwnd, and control_name (WinForms Control.Name read with the
#                                      WinForms message WM_GETCONTROLNAME; UI Automation does not always report
#                                      Control.Name as AutomationId for WinForms, it may report the window handle)
#   invoke      -Hwnd <button>       : press a button. UI Automation InvokePattern when the element supports it,
#                                      otherwise the MSAA default action (accDoDefaultAction, what the UIA MSAA
#                                      bridge does for Invoke). "method" in the JSON tells which one was used.
#   fileversion -Path <exe>          : FileVersion / ProductVersion of a file
#   events      -Since <yyyy-MM-ddTHH:mm:ss> : Application log events 1000/1002/1026 since the time
param(
    [Parameter(Mandatory = $true)][ValidateSet('controls', 'invoke', 'fileversion', 'events')][string]$Action,
    [long]$Hwnd = 0,
    [string]$Path = '',
    [string]$Since = ''
)

$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false

function Write-Json($obj) {
    $json = ConvertTo-Json -InputObject $obj -Depth 5 -Compress
    [Console]::Out.Write($json)
    [Console]::Out.Flush()
}

$nativeSource = @"
using System;
using System.Runtime.InteropServices;
using System.Text;

public static class ReleaseCheckNative {
    [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern uint RegisterWindowMessage(string name);
    [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint pid);
    [DllImport("user32.dll")] static extern IntPtr SendMessageTimeout(IntPtr hwnd, uint msg, IntPtr wp, IntPtr lp, uint flags, uint timeout, out IntPtr result);
    [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
    [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr VirtualAllocEx(IntPtr proc, IntPtr addr, UIntPtr size, uint type, uint protect);
    [DllImport("kernel32.dll", SetLastError = true)] static extern bool VirtualFreeEx(IntPtr proc, IntPtr addr, UIntPtr size, uint type);
    [DllImport("kernel32.dll", SetLastError = true)] static extern bool ReadProcessMemory(IntPtr proc, IntPtr addr, byte[] buf, UIntPtr size, out UIntPtr read);
    [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
    [DllImport("oleacc.dll")] static extern int AccessibleObjectFromWindow(IntPtr hwnd, uint id, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);

    const uint PROCESS_VM_OPERATION = 0x0008, PROCESS_VM_READ = 0x0010, PROCESS_VM_WRITE = 0x0020, PROCESS_QUERY_INFORMATION = 0x0400;
    const uint MEM_COMMIT = 0x1000, MEM_RESERVE = 0x2000, MEM_RELEASE = 0x8000, PAGE_READWRITE = 0x04;
    const uint SMTO_ABORTIFHUNG = 0x0002;
    const uint OBJID_CLIENT = 0xFFFFFFFC;
    const int MaxChars = 512;

    // WinForms Control.WndProc answers the registered message WM_GETCONTROLNAME by copying Control.Name
    // into the buffer at lParam (an address in the WinForms process), wParam = buffer size in chars.
    public static string GetControlName(IntPtr hwnd) {
        uint msg = RegisterWindowMessage("WM_GETCONTROLNAME");
        uint pid;
        GetWindowThreadProcessId(hwnd, out pid);
        IntPtr proc = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, false, pid);
        if (proc == IntPtr.Zero) return null;
        try {
            UIntPtr size = new UIntPtr((uint)(MaxChars * 2));
            IntPtr remote = VirtualAllocEx(proc, IntPtr.Zero, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
            if (remote == IntPtr.Zero) return null;
            try {
                IntPtr result;
                IntPtr ok = SendMessageTimeout(hwnd, msg, new IntPtr(MaxChars), remote, SMTO_ABORTIFHUNG, 2000, out result);
                if (ok == IntPtr.Zero || result.ToInt64() <= 0) return null;
                byte[] buf = new byte[MaxChars * 2];
                UIntPtr read;
                if (!ReadProcessMemory(proc, remote, buf, size, out read)) return null;
                string s = Encoding.Unicode.GetString(buf);
                int nul = s.IndexOf('\0');
                return nul >= 0 ? s.Substring(0, nul) : s;
            } finally {
                VirtualFreeEx(proc, remote, UIntPtr.Zero, MEM_RELEASE);
            }
        } finally {
            CloseHandle(proc);
        }
    }

    public static void DoDefaultAction(IntPtr hwnd) {
        Guid iid = new Guid("618736E0-3C3D-11CF-810C-00AA00389B71");   // IAccessible
        object o;
        int hr = AccessibleObjectFromWindow(hwnd, OBJID_CLIENT, ref iid, out o);
        if (hr != 0) throw new InvalidOperationException("AccessibleObjectFromWindow failed: 0x" + hr.ToString("X8"));
        Accessibility.IAccessible acc = (Accessibility.IAccessible)o;
        acc.accDoDefaultAction(0);
    }
}
"@

function Use-Native {
    if (-not ('ReleaseCheckNative' -as [type])) {
        Add-Type -TypeDefinition $nativeSource -ReferencedAssemblies Accessibility
    }
}

try {
    switch ($Action) {
        'controls' {
            if ($Hwnd -eq 0) { throw 'Hwnd is required' }
            Add-Type -AssemblyName UIAutomationClient
            Add-Type -AssemblyName UIAutomationTypes
            Use-Native
            $main = [System.Windows.Automation.AutomationElement]::FromHandle([IntPtr]$Hwnd)
            $children = $main.FindAll([System.Windows.Automation.TreeScope]::Children,
                [System.Windows.Automation.Condition]::TrueCondition)
            $list = @()
            foreach ($e in $children) {
                $c = $e.Current
                $h = [long]$c.NativeWindowHandle
                $name = $null
                if ($h -ne 0) { $name = [ReleaseCheckNative]::GetControlName([IntPtr]$h) }
                $list += [ordered]@{
                    automation_id = $c.AutomationId
                    control_name  = $name
                    control_type  = $c.ControlType.ProgrammaticName
                    class_name    = $c.ClassName
                    hwnd          = $h
                    enabled       = [bool]$c.IsEnabled
                }
            }
            Write-Json ([ordered]@{ ok = $true; controls = @($list) })
        }
        'invoke' {
            if ($Hwnd -eq 0) { throw 'Hwnd is required' }
            Add-Type -AssemblyName UIAutomationClient
            Add-Type -AssemblyName UIAutomationTypes
            $el = [System.Windows.Automation.AutomationElement]::FromHandle([IntPtr]$Hwnd)
            if (-not $el.Current.IsEnabled) {
                Write-Json ([ordered]@{ ok = $false; error = "control is disabled (hwnd $Hwnd)" })
                break
            }
            $pattern = $null
            $hasInvoke = $el.TryGetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern, [ref]$pattern)
            $sw = [System.Diagnostics.Stopwatch]::StartNew()
            # For WinForms buttons the call may not return until the click handler returns
            # (the shot loop runs on the UI thread). The caller does not wait for this process.
            if ($hasInvoke) {
                $pattern.Invoke()
                $method = 'uia-invoke'
            } else {
                Use-Native
                [ReleaseCheckNative]::DoDefaultAction([IntPtr]$Hwnd)
                $method = 'msaa-default-action'
            }
            $sw.Stop()
            Write-Json ([ordered]@{ ok = $true; method = $method; elapsed_ms = [long]$sw.ElapsedMilliseconds })
        }
        'fileversion' {
            if (-not $Path) { throw 'Path is required' }
            $vi = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($Path)
            Write-Json ([ordered]@{ ok = $true; file_version = $vi.FileVersion; product_version = $vi.ProductVersion })
        }
        'events' {
            if (-not $Since) { throw 'Since is required' }
            $start = [datetime]::ParseExact($Since, 'yyyy-MM-ddTHH:mm:ss', [System.Globalization.CultureInfo]::InvariantCulture)
            $list = @()
            try {
                $events = Get-WinEvent -FilterHashtable @{ LogName = 'Application'; Id = @(1000, 1002, 1026); StartTime = $start } -ErrorAction Stop
            } catch {
                # No matching events is reported as an exception by Get-WinEvent
                if ($_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') { $events = @() } else { throw }
            }
            foreach ($ev in $events) {
                $msg = $null
                try { $msg = $ev.Message } catch { $msg = $null }
                if (-not $msg) { $msg = (($ev.Properties | ForEach-Object { [string]$_.Value }) -join ' | ') }
                $list += [ordered]@{
                    time     = $ev.TimeCreated.ToString('yyyy-MM-ddTHH:mm:ss.fff', [System.Globalization.CultureInfo]::InvariantCulture)
                    id       = [int]$ev.Id
                    provider = $ev.ProviderName
                    message  = $msg
                }
            }
            Write-Json ([ordered]@{ ok = $true; events = @($list) })
        }
    }
    exit 0
} catch {
    Write-Json ([ordered]@{ ok = $false; error = ($_.Exception.GetType().FullName + ': ' + $_.Exception.Message) })
    exit 0
}