Microsoft MVP성태의 닷넷 이야기
C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계 [링크 복사], [링크+제목 복사],
조회: 5317
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

(시리즈 글이 5개 있습니다.)
C/C++: 170. Windows - STARTUPINFO의 cbReserved2, lpReserved2 멤버 사용자 정의
; https://www.sysnet.pe.kr/2/0/13723

C/C++: 171. C/C++ - 윈도우 운영체제에서의 file descriptor와 HANDLE
; https://www.sysnet.pe.kr/2/0/13726

C/C++: 172. Windows - C 런타임에서 STARTUPINFO의 cbReserved2, lpReserved2 멤버를 사용하는 이유
; https://www.sysnet.pe.kr/2/0/13728

C/C++: 174. C/C++ - 윈도우 운영체제에서의 file descriptor, FILE*
; https://www.sysnet.pe.kr/2/0/13738

C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계
; https://www.sysnet.pe.kr/2/0/13750




C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계

예를 하나 들어 볼까요? 프로젝트를 Windows Application으로 만들거나, 혹은 Console 프로젝트를 만든 후 "Linker" / "System"의 "Subsystem"을 "Console (/SUBSYSTEM:CONSOLE)" 대신 "Windows (/SUBSYSTEM:WINDOWS)"로 바꾼 후 WinMain/wWinMain으로 코드를 변경하면,

#include <iostream>
#include <Windows.h>

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    std::cout << "Hello World!: " << result << std::endl;
    getchar();
    return 0;
}

실행 시 콘솔 없이 뜨는 윈도우 응용 프로그램이 됩니다. 이런 상황에서 CRT와 함께 링킹이 된 경우, WinMain/wWinMain이 실행되기까지의 단계를 간단하게 정리해 보겠습니다. (이후 Multi-threaded Debug DLL (/MDd) + Debug 모드로 가정)




일반적으로는, 우리가 알고 있는 main 함수가 가장 먼저 실행되는 것은 아닙니다. EXE가 실행이 되면, 원래는 Entry Point가 (Visual C++의 경우) wWinMainCRTStartup으로 지정되기 때문에 이 함수가 가장 먼저 실행됩니다.

// How does the linker decide whether to call WinMain or wWinMain?
// https://devblogs.microsoft.com/oldnewthing/20241004-00/?p=110338

//  * mainCRTStartup     => main  (C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.41.34120\crt\src\vcruntime\exe_main.cpp)
//  * wmainCRTStartup    => wmain (C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.41.34120\crt\src\vcruntime\exe_wmain.cpp)
//  * WinMainCRTStartup  => WinMain (C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.41.34120\crt\src\vcruntime\exe_winmain.cpp)
//  * wWinMainCRTStartup => wWinMain

// C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.41.34120\crt\src\vcruntime\exe_wwinmain.cpp

extern "C" DWORD wWinMainCRTStartup(LPVOID)
{
    return __scrt_common_main();
}

wWinMainCRTStartup은 CRT에서 제공하는 진입점 함수로써, 본격적으로 (사용자가 제공한 main을) 실행하기 전 CRT를 초기화하는 역할을 겸합니다. 이어서 코드를 계속 보면,

// C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.41.34120\crt\src\vcruntime\exe_common.inl

// This is the common main implementation to which all of the CRT main functions
// delegate (for executables; DLLs are handled separately).
static __forceinline int __cdecl __scrt_common_main()
{
    // The /GS security cookie must be initialized before any exception handling
    // targeting the current image is registered.  No function using exception
    // handling can be called in the current image until after this call:
    __security_init_cookie();

    return __scrt_common_main_seh();
}

static __declspec(noinline) int __cdecl __scrt_common_main_seh()
{
    if (!__scrt_initialize_crt(__scrt_module_type::exe))
        __scrt_fastfail(FAST_FAIL_FATAL_APP_EXIT);

    // ...[생략]...
    __try
    {
        // ...[생략]...
            __scrt_current_native_startup_state = __scrt_native_startup_state::initializing;

            if (_initterm_e(__xi_a, __xi_z) != 0)
                return 255;

            _initterm(__xc_a, __xc_z);

            __scrt_current_native_startup_state = __scrt_native_startup_state::initialized;
        // ...[생략]...

        // ...[생략]...
        _tls_callback_type const* const tls_init_callback = __scrt_get_dyn_tls_init_callback();
        if (*tls_init_callback != nullptr && __scrt_is_nonwritable_in_current_image(tls_init_callback))
        {
            (*tls_init_callback)(nullptr, DLL_THREAD_ATTACH, nullptr);
        }

        // If this module has any thread-local destructors, register the
        // callback function with the Unified CRT to run on exit.
        _tls_callback_type const * const tls_dtor_callback = __scrt_get_dyn_tls_dtor_callback();
        if (*tls_dtor_callback != nullptr && __scrt_is_nonwritable_in_current_image(tls_dtor_callback))
        {
            _register_thread_local_exe_atexit_callback(*tls_dtor_callback);
        }

        //
        // Initialization is complete; invoke main...
        //

        int const main_result = invoke_main();

        //
        // main has returned; exit somehow...
        //

        if (!__scrt_is_managed_app())
            exit(main_result);

        if (!has_cctor)
            _cexit();

        // Finally, we terminate the CRT:
        __scrt_uninitialize_crt(true, false);
        return main_result;
    }
    __except (_seh_filter_exe(GetExceptionCode(), GetExceptionInformation()))
    {
        // ...[생략]...
    }
}

__scrt_common_main_seh 함수가 사실상 CRT의 main 역할을 하게 되는데요, 대충 다음과 같은 작업을 수행합니다.

  1. CRT 초기화 (__scrt_initialize_crt)
  2. _initterm_e, _initterm를 통한 기타 초기화 함수 호출
  3. TLS 초기화
  4. main 함수 호출 (invoke_main)
  5. exit 호출로 종료

main 함수의 호출과 이어서 exit 호출을 하는 부분이 재미있는데요,

int const main_result = invoke_main();

if (!__scrt_is_managed_app())
    exit(main_result);

Windows 운영체제의 경우 엄밀히 EXE의 모든 스레드가 종료해야만 해당 EXE 프로세스가 종료하게 됩니다. 즉, main을 실행하는 스레드와 그것에 더해 새롭게 생성한 스레드 간에는 별다르게 주종 관계가 없이 동등한 1개의 스레드 자원으로 대우를 받습니다.

그런데, 보통은 main을 벗어나게 되면 그 내부에서 어떤 스레드를 생성했느냐에 상관없이 무조건 프로세스 자체가 종료하게 됩니다. 바로 그 이유를 위의 코드에서 설명하고 있는데요, 보는 바와 같이 exit() 함수를 호출하기 때문입니다.

반면, "managed app"인 경우에는 exit를 직접 호출하지 않는데요, 이럴 때는 .NET Managed 환경의 규칙에 따라 행동하기 때문에 (Background가 아닌) foreground 스레드가 살아 있는 경우에는 여전히 EXE 프로세스도 살아 있어야 하므로 exit 호출을 하지 않게 된 것입니다.




본론으로 돌아와서, __scrt_initialize_crt 함수는,

// C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.41.34120\crt\src\vcruntime\utility.cpp

extern "C" bool __cdecl __scrt_initialize_crt(__scrt_module_type const module_type)
{
    if (module_type == __scrt_module_type::dll)
    {
        is_initialized_as_dll = true;
    }

    __isa_available_init();

    // Notify the CRT components of the process attach, bottom-to-top:
    if (!__vcrt_initialize())
    {
        return false;
    }

    if (!__acrt_initialize())
    {
        __vcrt_uninitialize(false);
        return false;
    }

    return true;
}

각각 2개의 initialize 함수를 호출하는데요, exe 실행 모듈의 경우 이 함수 2개는 동일하게 stub 함수를 호출하는 정도로 끝납니다.

// C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.41.34120\crt\src\vcruntime\ucrt_stubs.cpp

extern "C" bool __cdecl __scrt_stub_for_acrt_initialize() // exe 실행 모듈인 경우 __vcrt_initialize, __acrt_initialize가 가리키는 빈 함수
{
    return true;
}

이뿐만이 아니라, 이 함수는 msvcp140.dll(msvcp140d.dll)을 로드하는 중에도 유사하게 DllMain을 호출하는 _DllMainCRTStartup 단계에서도 실행되는데, 그때 역시 마찬가지로 아무 일도 하지 않는 __scrt_stub_for_acrt_initialize 함수를 호출합니다.

아니, 그럼 언제 CRT를 초기화는 걸까요?

그러고 보니, 이전 글에서 __acrt_initialize를 한 번 다룬 적이 있습니다.

Windows - C 런타임에서 STARTUPINFO의 cbReserved2, lpReserved2 멤버를 사용하는 이유
; https://www.sysnet.pe.kr/2/0/13728

즉, ucrtbase.dll(ucrtbased.dll)의 __acrt_DllMain 초기화하는 과정 중에 __acrt_initialize가 호출됐었습니다. 다시 말해, EXE 프로세스 공간 내에서 이뤄지는 단 한 번의 CRT 초기화는 ucrtbase.dll이 로드되는 순간 끝나는 것입니다.

이후의 msvcp140.dll이나 기타 CRT를 사용하는 DLL 및 EXE 실행 모듈에서는 ucrtbase.dll에서 이미 CRT 초기화를 마쳤으므로 그냥 dummy 호출로만 수행하고 그 단계를 벗어나는 것입니다.




이전 글에서는 __acrt_execute_initializers 함수에 전달된 __acrt_initializers 함수 포인터 목록을 단순히 나열만 했었는데요, 이에 대해서는 소스코드를 통해 다음과 같이 초기화 목록을 확인할 수 있습니다.

// C:\Program Files (x86)\Windows Kits\10\Source\10.0.22621.0\ucrt\internal\initialization.cpp

// AppCRT initialization.  Initializers are run first-to-last during AppCRT
// initialization, and uninitializers are run last-to-first during termination.
static __acrt_initializer const __acrt_initializers[] =
{
    // Init globals that can't be set at compile time because they have c'tors
    { initialize_global_variables,             nullptr                                  },

    // Global pointers are stored in encoded form; they must be dynamically
    // initialized to the encoded nullptr value before they are used by the CRT.
    { initialize_pointers,                     nullptr                                  },
    // Enclaves only require initializers for supported features.
#ifndef _UCRT_ENCLAVE_BUILD
    { __acrt_initialize_winapi_thunks,         __acrt_uninitialize_winapi_thunks        },
#endif

    // Configure CRT's global state isolation system.  This system calls FlsAlloc
    // and thus must occur after the initialize_pointers initialization, otherwise
    // it will fall back to call TlsAlloc, then try to use the allocated TLS slot
    // with the FLS functions.  This does not turn out well.  By running this
    // initialization after the initialize_pointers step, we ensure that it can
    // call FlsAlloc.
    { initialize_global_state_isolation,       uninitialize_global_state_isolation      },

    // The heap and locks must be initialized before most other initialization
    // takes place, as other initialization steps rely on the heap and locks:
    { __acrt_initialize_locks,                 __acrt_uninitialize_locks                },
    { __acrt_initialize_heap,                  __acrt_uninitialize_heap                 },

    // During uninitialization, before the heap is uninitialized, the AppCRT
    // needs to notify all VCRuntime instances in the process to allow them to
    // release any memory that they allocated via the AppCRT heap.
    //
    // First, we notify all modules that registered for shutdown notification.
    // This only occurs in the AppCRT DLL, because the static CRT is only ever
    // used by a single module, so this notification is never required.
    //
    // Then, we notify our own VCRuntime instance.  Note that after this point
    // during uninitialization, no exception handling may take place in any
    // CRT module.
    { nullptr,                                 uninitialize_vcruntime                   },

    { __acrt_initialize_ptd,                   __acrt_uninitialize_ptd                  },
    // Enclaves only require initializers for supported features.
#ifndef _UCRT_ENCLAVE_BUILD
    { __acrt_initialize_lowio,                 __acrt_uninitialize_lowio                },
    { __acrt_initialize_command_line,          __acrt_uninitialize_command_line         },
#endif
    { __acrt_initialize_multibyte,             nullptr                                  },
    { nullptr,                                 report_memory_leaks                      },
    // Enclaves only require initializers for supported features.
#ifndef _UCRT_ENCLAVE_BUILD
    { nullptr,                                 uninitialize_allocated_io_buffers        },
#endif
    { nullptr,                                 uninitialize_allocated_memory            },
    // Enclaves only require initializers for supported features.
#ifndef _UCRT_ENCLAVE_BUILD
    { initialize_environment,                  uninitialize_environment                 },
#endif
    { initialize_c,                            uninitialize_c                           },
};

이 중에서 "__acrt_initialize_lowio"의 경우에는 이전에 설명한 내용을 따릅니다.




예전에 해당 EXE/DLL이 Managed App인지 구분하는 방법을 소개했었는데요,

해당 DLL이 Managed인지 / Unmanaged인지 확인하는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1296

그와 유사한 코드가 본문에서 언급했던 __scrt_is_managed_app 함수에서 찾을 수 있습니다.

// C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.41.34120\crt\src\vcruntime\utility_desktop.cpp

extern "C" bool __cdecl __scrt_is_managed_app()
{
    PIMAGE_DOS_HEADER const dos_header = reinterpret_cast<PIMAGE_DOS_HEADER>(GetModuleHandleW(nullptr));
    if (dos_header == nullptr)
        return false;

    if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
        return false;

    PIMAGE_NT_HEADERS const pe_header = reinterpret_cast<PIMAGE_NT_HEADERS>(
        reinterpret_cast<BYTE*>(dos_header) + dos_header->e_lfanew);

    if (pe_header->Signature != IMAGE_NT_SIGNATURE)
        return false;

    if (pe_header->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
        return false;

    // prefast assumes we are overrunning __ImageBase
    #pragma warning(push)
    #pragma warning(disable: 26000)

    if (pe_header->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR)
        return false;

    #pragma warning(pop)

    if (pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress == 0)
        return false;

    return true;
}

다행히, C#으로 작성한 코드와 크게 다르지 않군요. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 10/7/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 181  182  183  184  185  186  187  188  189  190  191  [192]  193  194  195  ...
NoWriterDateCnt.TitleFile(s)
135정성태3/31/200520887VS.NET IDE: 26. SQL Server 2000구성이 실패
134정성태3/31/200518095COM 개체 관련: 16. Microsoft.XMLHTTP 개체에서 Microsoft.XMLDOM 개체를 전송할 때 charset 지정 문제? [2]
128정성태3/30/200516458.NET Framework: 34. VC++에서 Managed 타입의 메서드에 BSTR을 넘기는 경우의 오류(!)
129정성태3/30/200518553    답변글 .NET Framework: 34.1. 위의 질문에 대한 답변으로 나온 것입니다.
130정성태3/30/200515884        답변글 .NET Framework: 34.2. 다시... 제가 질문한 내용입니다. ^^
131정성태3/30/200516379            답변글 .NET Framework: 34.3. 다시... 정봉겸님이 하신... 명확한 답변입니다.
126정성태3/26/200516231.NET Framework: 33. Proxy 환경에서의 Smart Client 업데이트 문제 [1]
133정성태3/31/200517374    답변글 .NET Framework: 33.1. [추가]: Proxy 환경에서의 Smart Client 업데이트 문제 [2]
125정성태3/26/200516353VC++: 15. VC++ Keyword
124정성태3/25/200516872.NET Framework: 32. 네트워크 공유 없이 상대 컴퓨터에 프로그램 설치
119정성태3/21/200516464.NET Framework: 31. 소스세이프 오류현상: 웹 프로젝트를 열수 없습니다.
120정성태3/21/200517756    답변글 .NET Framework: 31.1. 소스세이프 오류현상: PDB 파일이 잠기는 문제
121정성태3/21/200517825    답변글 .NET Framework: 31.2. 소스세이프 오류현상: VS.NET 2003 IDE 와 연동되는 소스세이프 버전 문제
122정성태3/21/200516514    답변글 .NET Framework: 31.3. 소스세이프 관련 사이트
160정성태11/14/200519398    답변글 VS.NET IDE: 31.4. [추가]: 웹 애플리케이션 로드시 "_1"을 붙여서 묻는 경우. [1]
196이문석12/23/200516212        답변글 .NET Framework: 31.8. [답변]: [추가]: 웹 애플리케이션 로드시 "_1" 을 붙여서 묻는 경우.
167정성태10/10/200515787    답변글 .NET Framework: 31.5. [추가]: 삭제한 웹 가상 디렉터리에 대해 동일한 이름으로 웹 공유를 설정할 때 - 이미 있다고 오류발생
190정성태12/11/200515096    답변글 VC++: 31.6. ASP.NET 소스세이프 오류현상: 다른 사람이 체크아웃 한 것을 또 다른 사람이 체크아웃 가능!
191정성태12/11/200517534    답변글 VC++: 31.7. 소스 세이프 사용 시, 특정 프로젝트의 빌드 체크가 솔루션 로드할 때마다 해제되는 경우
118정성태3/30/200623294VC++: 14. TCP through HTTP tunneling: 기업 내 Proxy 서버 제한에서 벗어나는 방법 [2]
117정성태3/19/200524408.NET Framework: 30. Process.Start에서의 인자 길이 제한 [4]
116정성태3/14/200516933.NET Framework: 29. [.NET WebService] 자동생성되는 WSDL 을 막는 방법.
115정성태3/13/200517439VS.NET IDE: 25. [IIS 서버] ODBC 로그 남기기 [1]
195정성태12/21/200516702    답변글 VC++: 25.1. ODBC 로그를 못 남길 때의 오류 화면
113정성태3/13/200517509VS.NET IDE: 24. [VPC] 타이머 동기화 기능 제거
110정성태11/14/200516448.NET Framework: 28. VS.NET 2005 / SQL Server 2005 베타 버전 재설치 또는 업그레이드 [1]
... 181  182  183  184  185  186  187  188  189  190  191  [192]  193  194  195  ...