Who calls lang_start?

I am very interested in knowing the internal mechanisms of rust application initialization. In Windows, I know the application entry point is mainCRTStartup, and in the std source code I found that it is lang_start that calls user-written main. So my question is:

Who calls lang_start? mainCRTStartup or a function called by mainCRTStartup?

Where can we find the source code, or the binary of mainCRTStartup (if the source is not provided)?

1 Like

The entry point is generated here:

In short, yes mainCRTStartup calls lang_start.

The long version

On Windows, mainCRTStartup is just one of the conventional names for the entry point that sets up the C runtime. There are others that do slightly different things but all have a signature like this (translated into Rust):

extern "stdcall" fn entry_point() -> i32;

If you don't set the entry point explicitly (which Rust doesn't) then the linker environment sets the entry point function depending on which options are chosen (e.g. if you're compiling an exe or dll, or if you using the console subsystem or not). Typically the entry point chosen is mainCRTStartup.

This is implemented by a static library (in the case of msvc, this is in the VCRuntime). This mainCRTStartup entry point does things like initialize a security cookie, setup the C runtime, gather command line arguments, etc. It then calls the C application's main which it simply expects to be there. As jschievink's link shows, Rust generates a C style main function for it to call. This in turn calls lang_start which then finally calls your application's main.

Also note that in the case of Windows, lang_start doesn't actually do very much. It essentially just sets up something to catch stackoverflow exceptions and print a friendly error message.


If you're looking for the source code to mainCRTStartup then I believe Microsoft provides it inside your Visual Studio folder. You might have to search a bit though because I'm not sure off hand where it is.

2 Likes

Thank you!

I am so surprised to see that the main function is dynamically generated by rustc.

Thank you Chrisd!

I know mainCRTStartup quite well, as I write C programs very often. Your answer enlightened me. If it were not for your answer, I would never have thought of the possibility that the linker actually links code written in Rust to code written in C and residing in the MSVC lib folder.

I'm never sure how much detail to give because people know different things. Sorry if I over explained what you already knew!

But I'm glad I helped anyway.