Description
first reported at estk/log4rs#263 and mmastrac/rust-ctor#219
The Problem
On Windows, code can run functions before main by using special link sections. Placing function pointers in .CRT$XCU
allows the runtime to find and call the functions before it calls main()
. More info.
User code can take advantage of this to do pre-main initializations. However, the standard library also uses this mechanism to dynamically load some essential functions on startup. This can be a problem because there is no guaranteed order to functions placed in .CRT$XCU
. So initializers in the std may be run before, after or in between those created by user code. If a user's initializer happens to be run before the initializer that loads an essential function, it will act as though that function failed to load. This can cause errors or a panic.
Possible solutions
- Load delayed imports using C initializers instead of C++ initializers. These C initializers will be run first.
- Use the
.CRT$XCT
section as this will ensure functions run before those in the.CRT$XCU
section. However, "the names .CRT$XCT and .CRT$XCV aren't used by either the compiler or the CRT library right now, but there's no guarantee that they'll remain unused in the future". Source. I'm not sure it would matter if they were used for something as we don't rely on any features of the C or C++ runtimes when dynamically loading functions.
Activity
compat_fn
init before C++ init #97816NtWriteFile
cannot be imported #95786Rollup merge of rust-lang#97844 - ChrisDenton:dont-panic, r=JohnTitor
CodesInChaos commentedon Jul 19, 2022
Doesn't such user code violate the "no life before main" principle and is thus unsupported?
thomcc commentedon Jul 19, 2022
I think it's not really supported, but a problem here is that it's not equally unsupported on all targets -- It's easy for someone to write code that works fine before main on non-windows, but is broken on windows because of this. That seems unfortunate for portability (portability of naively written code, admittedly), if nothing else.
ChrisDenton commentedon Jul 1, 2023
This has now been implemented. The init function is now placed in
$XCT
which will run before user code in$XCU
. There is also appropriate documentation to explain this.Furthermore, most functions are now loaded lazily instead of pre-main, only
WaitOnAddress
andWakeByAddress
remain. Once we have a target that has Windows 8 as its minimum requirement then we could turn these into normal imports.