Skip to content

armgit / WacOS

Public Imported from GitHub
0

A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.

Rust
6.3 KB
Raw Blame
//! sentinela.cpp: a thread da interface do Shell parou (issue #32)? Uma thread própria manda WM_NULL para a janela de
//! mensagens a cada 250 ms; sem resposta em 1 s, copia a pilha da thread da interface (suspensa só durante a cópia) e
//! grava no shell.log "interface parada", com a mensagem que estava sendo tratada e a pilha em módulo+deslocamento.
#![allow(dead_code)]

use std::ffi::c_void;
use std::sync::atomic::{AtomicIsize, AtomicU32, Ordering};

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::System::Diagnostics::Debug::*;
use comum::windows::Win32::System::LibraryLoader::*;
use comum::windows::Win32::System::Memory::*;
use comum::windows::Win32::System::SystemInformation::GetTickCount;
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::from_w;

use crate::log;

/// o laço principal anota a mensagem que vai tratar
pub static ULTIMA_MSG: AtomicU32 = AtomicU32::new(0);
pub static ULTIMA_JANELA: AtomicIsize = AtomicIsize::new(0);
/// o topo da pilha basta para as ~30 chamadas de cima
const COPIA: usize = 96 * 1024;

/// pilha da thread (endereços de retorno)
#[cfg(target_arch = "x86_64")]
unsafe fn pilha(t: HANDLE, max: usize) -> Vec<u64> {
    let mut copia = vec![0u8; COPIA];
    #[repr(align(16))]
    struct Ctx(CONTEXT);
    let mut c = Ctx(CONTEXT { ContextFlags: CONTEXT_FULL_AMD64, ..Default::default() });
    if SuspendThread(t) == u32::MAX {
        return Vec::new();
    }
    let ok = GetThreadContext(t, &mut c.0).is_ok();
    let mut n = 0usize;
    let orig = c.0.Rsp;
    if ok {
        let mut mbi = MEMORY_BASIC_INFORMATION::default();
        if VirtualQuery(Some(orig as *const c_void), &mut mbi, std::mem::size_of::<MEMORY_BASIC_INFORMATION>()) != 0 {
            let fim = mbi.BaseAddress as u64 + mbi.RegionSize as u64;
            n = (COPIA as u64).min(fim - orig) as usize;
            std::ptr::copy_nonoverlapping(orig as *const u8, copia.as_mut_ptr(), n);
        }
    }
    let _ = ResumeThread(t);
    if !ok || n == 0 {
        return Vec::new();
    }
    let base = copia.as_ptr() as u64;
    let delta = base.wrapping_sub(orig);
    let mudar = |r: &mut u64| {
        if *r >= orig && *r < orig + n as u64 {
            *r = r.wrapping_add(delta);
        }
    };
    let dentro = |a: u64| a >= base && a + 8 <= base + n as u64;
    let mut out = Vec::new();
    mudar(&mut c.0.Rsp);
    mudar(&mut c.0.Rbp);
    while out.len() < max && c.0.Rip != 0 {
        out.push(c.0.Rip);
        let mut img = 0u64;
        let fe = RtlLookupFunctionEntry(c.0.Rip, &mut img, None);
        if fe.is_null() {
            // função folha: o retorno está no topo
            if !dentro(c.0.Rsp) {
                break;
            }
            c.0.Rip = *(c.0.Rsp as *const u64);
            c.0.Rsp += 8;
        } else {
            let (mut hd, mut ef) = (std::ptr::null_mut(), 0u64);
            RtlVirtualUnwind(UNW_FLAG_NHANDLER, img, c.0.Rip, fe, &mut c.0, &mut hd, &mut ef, None);
        }
        mudar(&mut c.0.Rsp);
        mudar(&mut c.0.Rbp);
        if !dentro(c.0.Rsp) {
            break;
        }
    }
    out
}
#[cfg(not(target_arch = "x86_64"))]
unsafe fn pilha(_t: HANDLE, _max: usize) -> Vec<u64> {
    Vec::new()
}
fn nome(pc: u64) -> String {
    unsafe {
        let mut m = HMODULE::default();
        let mut b = [0u16; 260];
        let tem = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, PCWSTR(pc as *const u16), &mut m).is_ok() && !m.0.is_null();
        let nm = if tem {
            GetModuleFileNameW(m, &mut b);
            let s = from_w(&b);
            s.rsplit('\\').next().unwrap_or("?").to_string()
        } else {
            "?".into()
        };
        format!("{nm}+0x{:X}", if tem { pc - m.0 as u64 } else { pc })
    }
}
fn texto(pcs: &[u64]) -> String {
    pcs.iter().map(|&p| nome(p)).collect::<Vec<_>>().join(" < ")
}
fn responde(alvo: HWND, ms: u32) -> bool {
    let mut r = 0usize;
    unsafe { SendMessageTimeoutW(alvo, WM_NULL, WPARAM(0), LPARAM(0), SMTO_NORMAL, ms, Some(&mut r)).0 != 0 }
}
fn vigiar(alvo: isize, tid: u32) {
    let alvo = HWND(alvo as *mut c_void);
    unsafe {
        let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
        let t = match OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, false, tid) {
            Ok(t) => t,
            Err(e) => {
                log!("sentinela: sem acesso à thread da interface ({})", e.code().0);
                return;
            }
        };
        let mut registros = 0;
        loop {
            std::thread::sleep(std::time::Duration::from_millis(250));
            let t0 = GetTickCount();
            if responde(alvo, 1000) {
                continue;
            }
            if !IsWindow(alvo).as_bool() {
                return; // o Shell está saindo
            }
            if registros >= 30 {
                while !responde(alvo, 1000) && IsWindow(alvo).as_bool() {}
                continue;
            }
            let (msg, jan) = (ULTIMA_MSG.load(Ordering::Relaxed), HWND(ULTIMA_JANELA.load(Ordering::Relaxed) as *mut c_void));
            let pcs = pilha(t, 40);
            let mut cls = [0u16; 64];
            let n = if jan.0.is_null() { 0 } else { GetClassNameW(jan, &mut cls) };
            let cls = if n > 0 { String::from_utf16_lossy(&cls[..n as usize]) } else { "?".into() };
            registros += 1;
            log!("sentinela: interface parada há 1 s (mensagem 0x{msg:04X} em {cls}); pilha: {}", texto(&pcs));
            let mut segunda = false;
            while !responde(alvo, 500) {
                if !IsWindow(alvo).as_bool() {
                    return;
                }
                if !segunda && GetTickCount().wrapping_sub(t0) > 4000 {
                    segunda = true;
                    log!("sentinela: ainda parada ({} ms); pilha: {}", GetTickCount().wrapping_sub(t0), texto(&pilha(t, 40)));
                }
            }
            log!("sentinela: a interface voltou depois de {} ms", GetTickCount().wrapping_sub(t0));
        }
    }
}
pub fn start(alvo: HWND) {
    let tid = unsafe { GetWindowThreadProcessId(alvo, None) };
    let a = alvo.0 as isize;
    std::thread::spawn(move || vigiar(a, tid));
}