Skip to content

Commit 804f560

Browse files
v3nn7claude
andcommitted
winrun: SDL3 and SteamUI imports, PE32 static TLS in LoadLibrary
A 32-bit DLL with static TLS (__declspec(thread)) can now be loaded with LoadLibrary: every live 32-bit thread gets its block, as Windows gives one to every existing thread. SteamUI, steamclient, tier0_s, vstdlib_s and video.dll all have TLS directories. New functions: menu items (InsertMenuW, DeleteMenu, CheckMenuItem, GetMenuItemInfoW), icons from resource data, the display-mode and display-device ANSI forms, GetWindowInfo, IsWindowUnicode, SetActiveWindow, layered-window attributes, OpenDesktopA/W, VkKeyScanEx, keybd_event, DialogBoxIndirectParamW, DescribePixelFormat, GetPixelFormat, GetBitmapBits, StretchBlt, brush origins, the missing imm32 calls, setupapi instance ids, class GUIDs and CM_Get_DevNode_Status, DragFinish/DragAcceptFiles, EnumResourceNamesW, console control events (GenerateConsoleCtrlEvent runs the registered handlers), SetThreadExecutionState, FreeLibraryAndExitThread, and VariantChangeType(Ex) with the coercion rules probed on Windows. 32-bit layouts: MENUITEMINFOW, ICONINFO, CURSORINFO, FLASHWINFO, INPUT, TRACKMOUSEEVENT, RAWINPUTDEVICE(LIST), SP_DEVINFO_DATA, WAVEHDR and MIDIHDR, STGMEDIUM, PROPVARIANT, VARIANT copies, token information pointers; winmm, monitor-enumeration and COM callbacks run as 32-bit code, on a runtime thread too (it gets 32-bit state on first use). ReplaceFile reports a missing file as ERROR_FILE_NOT_FOUND, as Windows does (probed with mingw). Not yet run through scripts/win-test.ps1. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2edd077 commit 804f560

20 files changed

Lines changed: 2168 additions & 103 deletions

‎compatibility/win32/src/apiextra.rs‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,31 @@ extern "win64" fn ReadConsoleW(h: u64, buf: *mut u16, n: u32, read: *mut u32, _c
5151
TRUE
5252
}
5353

54-
/// SetConsoleCtrlHandler: accepted; OSyx consoles deliver no Ctrl+C events
55-
/// to Windows programs.
56-
extern "win64" fn SetConsoleCtrlHandler(_handler: u64, _add: Bool) -> Bool {
57-
TRUE
54+
/// The program's console control handlers, in registration order, and
55+
/// whether Ctrl+C is ignored (SetConsoleCtrlHandler(NULL, TRUE)).
56+
pub(crate) static CTRL_HANDLERS: Mutex<(Vec<u64>, bool)> = Mutex::new((Vec::new(), false));
57+
58+
/// SetConsoleCtrlHandler: adds or removes a handler routine; NULL sets
59+
/// whether Ctrl+C is ignored. The handlers run for the console control
60+
/// events the program raises (GenerateConsoleCtrlEvent); OSyx's terminal
61+
/// sends Windows programs none of its own.
62+
extern "win64" fn SetConsoleCtrlHandler(handler: u64, add: Bool) -> Bool {
63+
let mut h = CTRL_HANDLERS.lock().unwrap();
64+
if handler == 0 {
65+
h.1 = add != 0;
66+
return TRUE;
67+
}
68+
if add != 0 {
69+
h.0.push(handler);
70+
return TRUE;
71+
}
72+
match h.0.iter().rposition(|&x| x == handler) {
73+
Some(i) => {
74+
h.0.remove(i);
75+
TRUE
76+
}
77+
None => fail(ERROR_INVALID_PARAMETER, FALSE),
78+
}
5879
}
5980

6081
// ---- locale --------------------------------------------------------------------

‎compatibility/win32/src/clientapi.rs‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -644,6 +644,131 @@ extern "win64" fn CharLowerBuffW(s: *mut u16, n: u32) -> u32 {
644644
n
645645
}
646646

647+
// ---- resources, threads, power ---------------------------------------------------------
648+
649+
/// A resource type or name argument: MAKEINTRESOURCE, "#123" or a string.
650+
fn res_id(p: u64) -> Option<crate::loader::ResId> {
651+
if p < 0x10000 {
652+
return Some(crate::loader::ResId::Id(p as u16));
653+
}
654+
// SAFETY: the caller's NUL-terminated name.
655+
let s = unsafe { path::wide_to_string(p as *const u16) }?;
656+
Some(match s.strip_prefix('#').and_then(|n| n.parse::<u16>().ok()) {
657+
Some(n) => crate::loader::ResId::Id(n),
658+
None => crate::loader::ResId::Name(s.encode_utf16().collect()),
659+
})
660+
}
661+
662+
/// EnumResourceNamesW: calls ENUMRESNAMEPROCW(module, type, name, param)
663+
/// for every resource of the type; a string name is passed as a string,
664+
/// an id as MAKEINTRESOURCE. A FALSE from the callback stops with
665+
/// ERROR_RESOURCE_ENUM_USER_STOP.
666+
extern "win64" fn EnumResourceNamesW(module: u64, kind: u64, proc_: u64, param: u64) -> Bool {
667+
const ERROR_RESOURCE_ENUM_USER_STOP: u32 = 15106;
668+
let Some(k) = res_id(kind) else { return fail(ERROR_INVALID_PARAMETER, FALSE) };
669+
if proc_ == 0 {
670+
return fail(ERROR_NOACCESS, FALSE);
671+
}
672+
let names = match crate::loader::resource_names(module, &k) {
673+
Ok(n) => n,
674+
Err(e) => return fail(e, FALSE),
675+
};
676+
let handle = if module == 0 { crate::loader::get_module_handle(None).unwrap_or(0) } else { module };
677+
for name in names {
678+
let text: Vec<u16>;
679+
let arg = match name {
680+
crate::loader::ResId::Id(id) => id as u64,
681+
crate::loader::ResId::Name(units) => {
682+
text = units.into_iter().chain(core::iter::once(0)).collect();
683+
text.as_ptr() as u64
684+
}
685+
};
686+
if crate::wow64::callback(proc_, &[handle, kind, arg, param]) as u32 == 0 {
687+
return fail(ERROR_RESOURCE_ENUM_USER_STOP, FALSE);
688+
}
689+
}
690+
TRUE
691+
}
692+
693+
/// FreeLibraryAndExitThread: releases the module, then ends the thread.
694+
extern "win64" fn FreeLibraryAndExitThread(module: u64, code: u32) -> ! {
695+
kernel32::FreeLibrary(module);
696+
kernel32::ExitThread(code)
697+
}
698+
699+
/// The arguments of a console control event's dispatch thread.
700+
struct CtrlEvent {
701+
event: u32,
702+
handlers: Vec<u64>,
703+
}
704+
705+
/// GenerateConsoleCtrlEvent: raises CTRL_C_EVENT (0) or CTRL_BREAK_EVENT
706+
/// (1) for this process's group (0, or the process's own id): as on
707+
/// Windows, a new thread calls the handlers, newest first, until one
708+
/// returns TRUE; when none does the process ends with
709+
/// STATUS_CONTROL_C_EXIT. Ctrl+C is dropped while ignored. Other groups
710+
/// are no console group of this program: ERROR_INVALID_PARAMETER.
711+
extern "win64" fn GenerateConsoleCtrlEvent(event: u32, group: u32) -> Bool {
712+
if event > 1 || (group != 0 && group as u64 != kernel32::pid()) {
713+
return fail(ERROR_INVALID_PARAMETER, FALSE);
714+
}
715+
let (handlers, ignore_c) = {
716+
let h = crate::apiextra::CTRL_HANDLERS.lock().unwrap();
717+
(h.0.clone(), h.1)
718+
};
719+
if event == 0 && ignore_c {
720+
return TRUE;
721+
}
722+
let arg = alloc::boxed::Box::into_raw(alloc::boxed::Box::new(CtrlEvent { event, handlers }));
723+
let thread = kernel32::CreateThread(0, 0, ctrl_dispatch as *const () as u64, arg as u64, 0, core::ptr::null_mut());
724+
if thread == 0 {
725+
// SAFETY: not handed to any thread.
726+
drop(unsafe { alloc::boxed::Box::from_raw(arg) });
727+
return FALSE;
728+
}
729+
kernel32::CloseHandle(thread);
730+
TRUE
731+
}
732+
733+
extern "win64" fn ctrl_dispatch(arg: u64) -> u32 {
734+
const STATUS_CONTROL_C_EXIT: u32 = 0xC000_013A;
735+
// SAFETY: the Box made by GenerateConsoleCtrlEvent for this thread.
736+
let CtrlEvent { event, handlers } = *unsafe { alloc::boxed::Box::from_raw(arg as *mut CtrlEvent) };
737+
let handled = if crate::wow64::is_active() {
738+
crate::wow64::with_thread32(|| handlers.iter().rev().any(|&h| crate::wow64::callback(h, &[event as u64]) as u32 != 0)).unwrap_or(false)
739+
} else {
740+
handlers.iter().rev().any(|&h| crate::wow64::callback(h, &[event as u64]) as u32 != 0)
741+
};
742+
if !handled {
743+
kernel32::ExitProcess(STATUS_CONTROL_C_EXIT);
744+
}
745+
0
746+
}
747+
748+
/// The calling thread's execution state (SetThreadExecutionState).
749+
static EXECUTION_STATE: os_std::sync::Mutex<alloc::collections::BTreeMap<u64, u32>> =
750+
os_std::sync::Mutex::new(alloc::collections::BTreeMap::new());
751+
752+
/// SetThreadExecutionState: ES_SYSTEM_REQUIRED (1), ES_DISPLAY_REQUIRED
753+
/// (2), ES_AWAYMODE_REQUIRED (0x40), kept while ES_CONTINUOUS (0x80000000)
754+
/// is set; returns the thread's previous state (0 for invalid flags).
755+
/// OSyx does not suspend or blank the screen on idle, so the requests are
756+
/// already met.
757+
extern "win64" fn SetThreadExecutionState(flags: u32) -> u32 {
758+
const ES_CONTINUOUS: u32 = 0x8000_0000;
759+
const KNOWN: u32 = 0x1 | 0x2 | 0x4 | 0x40 | ES_CONTINUOUS;
760+
if flags & !KNOWN != 0 || (flags & 0x40 != 0 && flags & ES_CONTINUOUS == 0) {
761+
return 0;
762+
}
763+
let tid = os_sys::gettid();
764+
let mut states = EXECUTION_STATE.lock().unwrap();
765+
let previous = states.get(&tid).copied().unwrap_or(ES_CONTINUOUS);
766+
if flags & ES_CONTINUOUS != 0 {
767+
states.insert(tid, flags);
768+
}
769+
previous
770+
}
771+
647772
pub fn kernel32_exports() -> Vec<(&'static str, u64)> {
648773
export_table![
649774
CompareStringA,
@@ -662,6 +787,10 @@ pub fn kernel32_exports() -> Vec<(&'static str, u64)> {
662787
CreateJobObjectA,
663788
DebugActiveProcess,
664789
DebugActiveProcessStop,
790+
EnumResourceNamesW,
791+
FreeLibraryAndExitThread,
792+
GenerateConsoleCtrlEvent,
793+
SetThreadExecutionState,
665794
]
666795
.into_iter()
667796
.chain([

‎compatibility/win32/src/dwmapi.rs‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,8 +392,54 @@ extern "win64" fn ImmGetIMEFileNameW(hkl: u64, _buf: *mut u16, _len: u32) -> u32
392392
0
393393
}
394394

395+
/// The input context each window uses (ImmAssociateContext); a window
396+
/// not listed uses its default context (ImmGetContext).
397+
static ASSOCIATED: Mutex<BTreeMap<u64, u64>> = Mutex::new(BTreeMap::new());
398+
399+
/// ImmAssociateContext: gives `hwnd` the context `himc` (NULL: none);
400+
/// returns the one it had.
401+
extern "win64" fn ImmAssociateContext(hwnd: u64, himc: u64) -> u64 {
402+
if !crate::user32::is_window(hwnd) {
403+
return 0;
404+
}
405+
if himc != 0 && with_context(himc, |_| ()).is_none() {
406+
return 0;
407+
}
408+
let previous = ASSOCIATED.lock().unwrap().insert(hwnd, himc);
409+
match previous {
410+
Some(p) => p,
411+
// The default context, made on demand as ImmGetContext does.
412+
None => ImmGetContext(hwnd),
413+
}
414+
}
415+
416+
/// ImmGetCandidateListW: nothing is ever composed (the only layout has no
417+
/// IME), so no context has a candidate list: 0.
418+
extern "win64" fn ImmGetCandidateListW(himc: u64, _index: u32, _list: *mut u8, _len: u32) -> u32 {
419+
let _ = with_context(himc, |_| ());
420+
0
421+
}
422+
423+
/// ImmSetCompositionStringW: without an IME there is no composition to
424+
/// change; Windows answers FALSE.
425+
extern "win64" fn ImmSetCompositionStringW(himc: u64, _index: u32, _comp: *const u8, _comp_len: u32, _read: *const u8, _read_len: u32) -> i32 {
426+
let _ = with_context(himc, |_| ());
427+
0
428+
}
429+
430+
extern "win64" fn ImmGetIMEFileNameA(hkl: u64, _buf: *mut u8, _len: u32) -> u32 {
431+
if !ime_free_layout(hkl) {
432+
return fail(ERROR_INVALID_HANDLE, 0);
433+
}
434+
0
435+
}
436+
395437
pub fn imm32_exports() -> Vec<(&'static str, u64)> {
396438
export_table![
439+
ImmAssociateContext,
440+
ImmGetCandidateListW,
441+
ImmSetCompositionStringW,
442+
ImmGetIMEFileNameA,
397443
ImmGetContext,
398444
ImmReleaseContext,
399445
ImmAssociateContextEx,

‎compatibility/win32/src/files.rs‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -223,19 +223,18 @@ fn replace_file(old: String, new: String, b: Option<String>, flags: u32) -> i32
223223
if flags & !0x7 != 0 {
224224
return fail(ERROR_INVALID_PARAMETER, 0);
225225
}
226-
if stat_of(&old).is_err() {
227-
return fail(1176, 0); // ERROR_UNABLE_TO_REMOVE_REPLACED
228-
}
229-
if stat_of(&new).is_err() {
226+
// Windows reports a missing file to replace, or a missing replacement,
227+
// as ERROR_FILE_NOT_FOUND.
228+
if stat_of(&old).is_err() || stat_of(&new).is_err() {
230229
return fail(ERROR_FILE_NOT_FOUND, 0);
231230
}
232231
if let Some(b) = b {
233232
if kernel32::move_file(Some(old.clone()), Some(b), 1) == 0 {
234-
return fail(1176, 0);
233+
return fail(1175, 0); // ERROR_UNABLE_TO_REMOVE_REPLACED
235234
}
236235
}
237236
if kernel32::move_file(Some(new), Some(old), 1) == 0 {
238-
return fail(1177, 0); // ERROR_UNABLE_TO_MOVE_REPLACEMENT
237+
return fail(1176, 0); // ERROR_UNABLE_TO_MOVE_REPLACEMENT
239238
}
240239
1
241240
}

‎compatibility/win32/src/kernel32.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3137,7 +3137,7 @@ extern "win64" fn LoadLibraryExW(name: *const u16, _file: u64, _flags: u32) -> u
31373137
LoadLibraryW(name)
31383138
}
31393139

3140-
extern "win64" fn FreeLibrary(h: u64) -> Bool {
3140+
pub(crate) extern "win64" fn FreeLibrary(h: u64) -> Bool {
31413141
loader::free_library(h).map_or_else(|e| fail(e, FALSE), |_| TRUE)
31423142
}
31433143

‎compatibility/win32/src/loader.rs‎

Lines changed: 73 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1274,6 +1274,73 @@ pub fn get_proc_address(h: u64, sym: Symbol<'_>) -> Result<u64, u32> {
12741274
})
12751275
}
12761276

1277+
/// A resource type or name: a 16-bit id or a string.
1278+
#[derive(Clone, PartialEq, Eq)]
1279+
pub(crate) enum ResId {
1280+
Id(u16),
1281+
Name(Vec<u16>),
1282+
}
1283+
1284+
/// The names of the resources of type `kind` in a mapped module (0: the
1285+
/// program), from its resource directory: string names first, then ids,
1286+
/// as the directory sorts them. Err(1813) when the module has no such type.
1287+
pub(crate) fn resource_names(module: u64, kind: &ResId) -> Result<Vec<ResId>, u32> {
1288+
const ERROR_RESOURCE_DATA_NOT_FOUND: u32 = 1812;
1289+
const ERROR_RESOURCE_TYPE_NOT_FOUND: u32 = 1813;
1290+
let base = with(|l| {
1291+
let index = if module == 0 { Some(l.exe) } else { module_by_handle(l, module) };
1292+
index.and_then(|i| matches!(l.linker.modules[i].kind, Kind::Pe { .. }).then(|| l.linker.modules[i].base))
1293+
})
1294+
.ok_or(ERROR_MOD_NOT_FOUND)?;
1295+
// SAFETY: a mapped PE image: its headers, data directories and the
1296+
// resource directory they point to (the image is SizeOfImage bytes,
1297+
// validated when it was loaded).
1298+
unsafe {
1299+
let rd16 = |a: u64| core::ptr::read_unaligned(a as *const u16);
1300+
let rd32 = |a: u64| core::ptr::read_unaligned(a as *const u32);
1301+
let nt = base + rd32(base + 0x3C) as u64;
1302+
let opt = nt + 24;
1303+
let dirs = if rd16(opt) == 0x20B { opt + 112 } else { opt + 96 };
1304+
let rsrc = rd32(dirs + 8 * 2) as u64;
1305+
if rsrc == 0 {
1306+
return Err(ERROR_RESOURCE_DATA_NOT_FOUND);
1307+
}
1308+
let root = base + rsrc;
1309+
// Entries of a directory: (name or id, offset of the entry's data).
1310+
let entries = |dir: u64| -> Vec<(ResId, u32)> {
1311+
let n = rd16(dir + 12) as u64 + rd16(dir + 14) as u64;
1312+
(0..n.min(4096))
1313+
.map(|i| {
1314+
let e = dir + 16 + 8 * i;
1315+
let name = rd32(e);
1316+
let id = if name & 0x8000_0000 != 0 {
1317+
let s = root + (name & 0x7FFF_FFFF) as u64;
1318+
let len = rd16(s) as usize;
1319+
ResId::Name((0..len).map(|k| rd16(s + 2 + 2 * k as u64)).collect())
1320+
} else {
1321+
ResId::Id(name as u16)
1322+
};
1323+
(id, rd32(e + 4))
1324+
})
1325+
.collect()
1326+
};
1327+
let same = |a: &ResId, b: &ResId| match (a, b) {
1328+
(ResId::Id(x), ResId::Id(y)) => x == y,
1329+
(ResId::Name(x), ResId::Name(y)) => {
1330+
String::from_utf16_lossy(x).to_uppercase() == String::from_utf16_lossy(y).to_uppercase()
1331+
}
1332+
_ => false,
1333+
};
1334+
let Some((_, offset)) = entries(root).into_iter().find(|(id, _)| same(id, kind)) else {
1335+
return Err(ERROR_RESOURCE_TYPE_NOT_FOUND);
1336+
};
1337+
if offset & 0x8000_0000 == 0 {
1338+
return Err(ERROR_RESOURCE_TYPE_NOT_FOUND);
1339+
}
1340+
Ok(entries(root + (offset & 0x7FFF_FFFF) as u64).into_iter().map(|(id, _)| id).collect())
1341+
}
1342+
}
1343+
12771344
/// Numeric RT_DIALOG resource from a mapped PE module, copied outside lock.
12781345
pub(crate) fn numeric_resource(module: u64, kind: u16, name: u64) -> Result<Vec<u8>, u32> {
12791346
if name == 0 || name >= 0x10000 { return Err(50); }
@@ -1319,17 +1386,6 @@ pub fn load_library(name: &str) -> Result<u64, u32> {
13191386
_ => 193, // ERROR_BAD_EXE_FORMAT
13201387
}
13211388
})?;
1322-
if wow64::is_active() {
1323-
for dep in l.linker.init_order(i) {
1324-
if let Kind::Pe { file, .. } = &l.linker.modules[dep].kind {
1325-
let pe = PeFile::parse_any(file.as_ref()).map_err(|_| 193u32)?;
1326-
if pe.tls().map_err(|_| 193u32)?.is_some() {
1327-
os_std::eprintln!("winrun: LoadLibrary({name}): PE32 static TLS is not supported in {}", l.linker.modules[dep].name);
1328-
return Err(50);
1329-
}
1330-
}
1331-
}
1332-
}
13331389
let todo = register_new(l, i);
13341390
while l.state.len() < l.linker.modules.len() {
13351391
l.state.push(ModState { ldr: 0, refs: 0, attached: true, tls_callbacks: Vec::new(), no_thread_calls: false });
@@ -1343,6 +1399,12 @@ pub fn load_library(name: &str) -> Result<u64, u32> {
13431399
if !todo.is_empty() && !wow64::is_active() {
13441400
// New TLS indices need blocks for this thread too.
13451401
setup_thread_tls(teb::current());
1402+
} else if !todo.is_empty() {
1403+
// A 32-bit DLL with static TLS gets a block in every thread that
1404+
// runs 32-bit code, as Windows gives one to every existing thread.
1405+
for teb32 in wow64::thread_tebs32() {
1406+
setup_thread_tls32(teb32);
1407+
}
13461408
}
13471409
let attached = if wow64::is_active() {
13481410
todo.iter().all(|(base, entry, callbacks, _)| {

0 commit comments

Comments
 (0)