Skip to content

Windows: Dynamically loaded functions may not be loaded before user pre-main initializers #97814

Closed
@ChrisDenton

Description

@ChrisDenton

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    O-windowsOperating system: WindowsT-libsRelevant to the library team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions