A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! Porte de src\janelas\gancho.cpp (WacOSGancho.dll): a DLL que o Windows põe nos apps pelo SetWindowsHookEx.
//! Lê no mapa compartilhado do Shell (Local\WacOSGanchoMapa1, src\comum\gancho_mapa.h) qual WacOSWindow.dll usar,
//! carrega com LoadLibraryW e repassa o GetMsgProc para ela.
//!
//! ESTE TESTE NÃO É INSTALADO NEM REGISTRADO COMO GANCHO. Ele só mostra que a carregadora sem CRT cabe em Rust:
//! - `#![no_std]`, sem alocação, só kernel32/user32 (windows-sys);
//! - `panic = "abort"` no perfil e nenhum caminho de pânico no código (sem índices com checagem);
//! - sem memcpy/memset: com /NODEFAULTLIB não há CRT para fornecê-los. Este código não gera chamadas a eles; se
//! um dia gerar, a ligação falha com "unresolved external memcpy" (erro de compilação, não de execução). Definir
//! os dois aqui funciona, mas o Rust os exporta da DLL (todo #[no_mangle] vira exportação numa cdylib).
//! - o mesmo vale para a DllMain: fica exportada (aviso LNK4216 do ligador). Inofensivo; a de C++ não exporta.
#![no_std]
#![allow(non_snake_case)]
use core::ffi::c_void;
use core::ptr::{addr_of_mut, null_mut, read_volatile, write_volatile};
use core::sync::atomic::{AtomicI32, AtomicPtr, Ordering};
use windows_sys::Win32::Foundation::{CloseHandle, BOOL, HINSTANCE, LPARAM, LRESULT, TRUE, WPARAM};
use windows_sys::Win32::System::LibraryLoader::{DisableThreadLibraryCalls, GetProcAddress, LoadLibraryW};
use windows_sys::Win32::System::Memory::{
MapViewOfFile, OpenFileMappingW, UnmapViewOfFile, FILE_MAP_READ, MEMORY_MAPPED_VIEW_ADDRESS,
};
use windows_sys::Win32::System::SystemServices::DLL_PROCESS_ATTACH;
use windows_sys::Win32::System::Threading::{AcquireSRWLockExclusive, ReleaseSRWLockExclusive, SRWLOCK, SRWLOCK_INIT};
use windows_sys::Win32::UI::WindowsAndMessaging::CallNextHookEx;
const CAMINHO: usize = 520;
/// Mesmo formato do struct GanchoMapa do C++ (só DWORD e wchar_t: igual em 32 e 64 bits)
#[repr(C)]
struct GanchoMapa {
tamanho: u32,
gen: i32,
real64: [u16; CAMINHO],
real32: [u16; CAMINHO],
gancho32: [u16; CAMINHO],
}
// "Local\WacOSGanchoMapa1" em UTF-16 com o zero do fim (sem alocar)
const NOME_MAPA: [u16; 23] = {
let s = b"Local\\WacOSGanchoMapa1\0";
let mut w = [0u16; 23];
let mut i = 0;
while i < 23 {
w[i] = s[i] as u16;
i += 1;
}
w
};
const NOME_PROC: &[u8] = b"GetMsgProc\0";
type HookProc = unsafe extern "system" fn(i32, WPARAM, LPARAM) -> LRESULT;
static MAPA: AtomicPtr<GanchoMapa> = AtomicPtr::new(null_mut());
static GEN: AtomicI32 = AtomicI32::new(0); // o gen do mapa que já foi aplicado
static PROC: AtomicPtr<c_void> = AtomicPtr::new(null_mut()); // GetMsgProc da WacOSWindow.dll atual
static mut TRAVA: SRWLOCK = SRWLOCK_INIT;
unsafe fn mapa() -> *mut GanchoMapa {
let m = MAPA.load(Ordering::Acquire);
if !m.is_null() {
return m;
}
let h = OpenFileMappingW(FILE_MAP_READ, 0, NOME_MAPA.as_ptr());
if h.is_null() {
return null_mut();
}
let v = MapViewOfFile(h, FILE_MAP_READ, 0, 0, core::mem::size_of::<GanchoMapa>());
CloseHandle(h); // a vista mantém o mapa vivo
let p = v.Value as *mut GanchoMapa;
if p.is_null() {
return null_mut();
}
if read_volatile(addr_of_mut!((*p).tamanho)) != core::mem::size_of::<GanchoMapa>() as u32 {
UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: p as *mut c_void });
return null_mut();
}
match MAPA.compare_exchange(null_mut(), p, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => p,
Err(outro) => {
UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: p as *mut c_void });
outro
}
}
}
unsafe fn atualiza(m: *mut GanchoMapa) {
AcquireSRWLockExclusive(addr_of_mut!(TRAVA));
let gen = read_volatile(addr_of_mut!((*m).gen));
if gen != GEN.load(Ordering::Relaxed) {
// copia o caminho (o Shell pode reescrever o mapa enquanto isso), sem memcpy e sem pânico
#[cfg(target_pointer_width = "64")]
let origem = addr_of_mut!((*m).real64) as *const u16;
#[cfg(not(target_pointer_width = "64"))]
let origem = addr_of_mut!((*m).real32) as *const u16;
let mut p = core::mem::MaybeUninit::<[u16; CAMINHO]>::uninit();
let dst = p.as_mut_ptr() as *mut u16;
let mut i = 0;
while i < CAMINHO - 1 {
let c = read_volatile(origem.add(i));
write_volatile(dst.add(i), c);
if c == 0 {
break;
}
i += 1;
}
write_volatile(dst.add(i), 0); // como o lstrcpynW: sempre termina em zero
// a WacOSWindow.dll recusa carregar dentro de jogos (DllMain FALSE): aí não há proc e o gancho só passa adiante
let dll = if read_volatile(dst) != 0 { LoadLibraryW(dst) } else { null_mut() };
let f = if dll.is_null() { None } else { GetProcAddress(dll, NOME_PROC.as_ptr()) };
PROC.store(f.map_or(null_mut(), |f| f as *mut c_void), Ordering::Release);
GEN.store(gen, Ordering::Relaxed);
}
ReleaseSRWLockExclusive(addr_of_mut!(TRAVA));
}
#[no_mangle]
pub unsafe extern "system" fn GetMsgProc(code: i32, w: WPARAM, l: LPARAM) -> LRESULT {
let m = mapa();
if !m.is_null() {
if read_volatile(addr_of_mut!((*m).gen)) != GEN.load(Ordering::Relaxed) {
atualiza(m);
}
let p = PROC.load(Ordering::Acquire);
if !p.is_null() {
let f: HookProc = core::mem::transmute(p);
return f(code, w, l); // ela mesma chama o próximo gancho
}
}
CallNextHookEx(null_mut(), code, w, l)
}
#[no_mangle]
unsafe extern "system" fn DllMain(h: HINSTANCE, motivo: u32, _r: *mut c_void) -> BOOL {
if motivo == DLL_PROCESS_ATTACH {
DisableThreadLibraryCalls(h);
}
TRUE
}
#[panic_handler]
fn panico(_: &core::panic::PanicInfo) -> ! {
// dentro do app dos outros não dá para mostrar nada; o código acima não tem caminho de pânico
loop {
core::hint::spin_loop();
}
}