Microsoft MVP성태의 닷넷 이야기
C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계 [링크 복사], [링크+제목 복사],
조회: 3929
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13885정성태2/14/2025258닷넷: 2319. ASP.NET Core Web API / Razor 페이지에서 발생할 수 있는 async void 메서드의 부작용
13884정성태2/13/2025398닷넷: 2318. C# - (async Task가 아닌) async void 사용 시의 부작용파일 다운로드1
13883정성태2/12/2025507닷넷: 2317. C# - Memory Mapped I/O를 이용한 PCI Configuration Space 정보 열람파일 다운로드1
13882정성태2/10/2025967스크립트: 70. 파이썬 - oracledb 패키지 연동 시 Thin / Thick 모드
13881정성태2/7/20251077닷넷: 2316. C# - Port I/O를 이용한 PCI Configuration Space 정보 열람파일 다운로드1
13880정성태2/5/2025911오류 유형: 947. sshd - Failed to start OpenSSH server daemon.
13879정성태2/5/20251147오류 유형: 946. Ubuntu - N: Updating from such a repository can't be done securely, and is therefore disabled by default.
13878정성태2/3/20251021오류 유형: 945. Windows - 최대 절전 모드 시 DRIVER_POWER_STATE_FAILURE 발생 (pacer.sys)
13877정성태1/25/20251121닷넷: 2315. C# - PCI 장치 열거 (레지스트리, SetupAPI)파일 다운로드1
13876정성태1/25/20251310닷넷: 2314. C# - ProcessStartInfo 타입의 Arguments와 ArgumentList파일 다운로드1
13875정성태1/24/20251317스크립트: 69. 파이썬 - multiprocessing 패키지의 spawn 모드로 동작하는 uvicorn의 workers
13874정성태1/24/20251262스크립트: 68. 파이썬 - multiprocessing Pool의 기본 프로세스 시작 모드(spawn, fork)
13873정성태1/23/20251147디버깅 기술: 217. WinDbg - PCI 장치 열거
13872정성태1/23/20251149오류 유형: 944. WinDbg - 원격 커널 디버깅이 연결은 되지만 Break (Ctrl + Break) 키를 눌러도 멈추지 않는 현상
13871정성태1/22/20251231Windows: 278. Windows - 윈도우를 다른 모니터 화면으로 이동시키는 단축키 (Window + Shift + 화살표)
13870정성태1/18/20251308개발 환경 구성: 741. WinDbg - 네트워크 커널 디버깅이 가능한 NIC 카드 지원 확대
13869정성태1/18/20251348개발 환경 구성: 740. WinDbg - _NT_SYMBOL_PATH 환경 변수에 설정한 경로로 심벌 파일을 다운로드하지 않는 경우
13868정성태1/17/20251303Windows: 277. Hyper-V - Windows 11 VM의 Enhanced Session 모드로 로그인을 할 수 없는 문제
13867정성태1/17/20251426오류 유형: 943. Hyper-V에 Windows 11 설치 시 "This PC doesn't currently meet Windows 11 system requirements" 오류
13866정성태1/16/20251418개발 환경 구성: 739. Windows 10부터 바뀐 device driver 서명 방법
13865정성태1/15/20251521오류 유형: 942. C# - .NET Framework 4.5.2 이하의 버전에서 HttpWebRequest로 https 호출 시 "System.Net.WebException" 예외 발생
13864정성태1/15/20251475Linux: 114. eBPF를 위해 필요한 SELinux 보안 정책
13863정성태1/14/20251558Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정
13862정성태1/13/20251560Linux: 112. Linux - 데몬을 위한 SELinux 보안 정책 설정
13861정성태1/11/20251855Windows: 276. 명령행에서 원격 서비스를 동기/비동기로 시작/중지
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...