From c8a426675198493f21015fcd06567ff61a7847d6 Mon Sep 17 00:00:00 2001 From: emirduran707 Date: Tue, 24 Nov 2026 21:56:06 +0300 Subject: [PATCH] PE loader: an executable loaded as a library does not run its entry point load_game_dll noticed that the image is not a DLL but init_dll still called its entry point with DllMain's arguments, so the program's mainCRTStartup ran on the loading thread (or the load failed when it returned 0). LoadLibrary loads an executable as if with DONT_RESOLVE_DLL_REFERENCES, which does not call DllMain; thread attach/detach already call the entry point only for a DLL. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/loader.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/loader.rs b/crates/xcl/src/loader.rs index 52c49afe78..d3b9f21736 100644 --- a/crates/xcl/src/loader.rs +++ b/crates/xcl/src/loader.rs @@ -257,7 +257,8 @@ unsafe fn run_tls_callbacks(m: &MappedModule, reason: u32) { pub fn init_dll(m: &Arc) -> Result<(), String> { unsafe { run_tls_callbacks(m, 1); - if m.entry_rva != 0 { + // an executable loaded as a library: Windows' loader does not call its entry point + if m.is_dll && m.entry_rva != 0 { let f: DllMain = std::mem::transmute(m.base + m.entry_rva as usize); crate::xlog_info!("DllMain({}, PROCESS_ATTACH)", m.name); if f(m.base as *mut c_void, 1, std::ptr::null_mut()) == 0 { @@ -503,6 +504,19 @@ mod tests { assert_eq!(load_game_dll(&p).unwrap().base, m.base); } + /// An executable loaded as a library is mapped, its entry point is not called as a DllMain + /// (before: its mainCRTStartup ran with DllMain's arguments; here it returns 0, the load failed) + #[test] + fn an_exe_loaded_as_a_library_does_not_run_its_entry_point() { + // xor eax, eax; ret + let mut img = tiny_dll(0x7E54_0000_0000, &[0x31, 0xC0, 0xC3], None); + img[0x56..0x58].copy_from_slice(&0x0022u16.to_le_bytes()); // executable | large address aware, not a DLL + let p = write("xcl_exe_as_library.exe", &img); + let m = load_game_dll(&p).expect("an EXE loads as a library"); + assert!(!m.is_dll); + assert_eq!(load_game_dll(&p).unwrap().base, m.base); + } + /// An import table that does not parse: the load fails and the module – whose memory is /// freed – is not found afterwards (before: still registered over freed memory, and a second /// load returned it).