Microsoft MVP성태의 닷넷 이야기
C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계 [링크 복사], [링크+제목 복사],
조회: 5279
글쓴 사람
정성태 (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)
13917정성태4/30/202544VS.NET IDE: 199. Directory.Build.props에 정의한 속성에 대해 Condition 제약으로 값을 변경하는 방법
13916정성태4/23/2025446디버깅 기술: 221. WinDbg 분석 사례 - ASP.NET HttpCookieCollection을 다중 스레드에서 사용할 경우 무한 루프 현상 - 두 번째 이야기
13915정성태4/13/20251652닷넷: 2331. C# - 실행 시에 메서드 가로채기 (.NET 9)파일 다운로드1
13914정성태4/11/20251973디버깅 기술: 220. windbg 분석 사례 - x86 ASP.NET 웹 응용 프로그램의 CPU 100% 현상 (4)
13913정성태4/10/20251204오류 유형: 950. Process Explorer - 64비트 윈도우에서 32비트 프로세스의 덤프를 뜰 때 "Error writing dump file: Access is denied." 오류
13912정성태4/9/2025863닷넷: 2330. C# - 실행 시에 메서드 가로채기 (.NET 5 ~ .NET 8)파일 다운로드1
13911정성태4/8/20251091오류 유형: 949. WinDbg - .NET Core/5+ 응용 프로그램 디버깅 시 sos 확장을 자동으로 로드하지 못하는 문제
13910정성태4/8/20251257디버깅 기술: 219. WinDbg - 명령어 내에서 환경 변수 사용법
13909정성태4/7/20251725닷넷: 2329. C# - 실행 시에 메서드 가로채기 (.NET Framework 4.8)파일 다운로드1
13908정성태4/2/20252138닷넷: 2328. C# - MailKit: SMTP, POP3, IMAP 지원 라이브러리
13907정성태3/29/20251935VS.NET IDE: 198. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C# 프로젝트의 출력 경로 변경하기
13906정성태3/27/20252190닷넷: 2327. C# - 초기화되지 않은 메모리에 접근하는 버그?파일 다운로드1
13905정성태3/26/20252220Windows: 281. C++ - Windows / Critical Section의 안정화를 위해 도입된 "Keyed Event"파일 다운로드1
13904정성태3/25/20251902디버깅 기술: 218. Windbg로 살펴보는 Win32 Critical Section파일 다운로드1
13903정성태3/24/20251522VS.NET IDE: 197. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C++ 프로젝트의 출력 경로 변경하기
13902정성태3/24/20251737개발 환경 구성: 742. Oracle - 테스트용 hr 계정 및 데이터 생성파일 다운로드1
13901정성태3/9/20252112Windows: 280. Hyper-V의 3가지 Thread Scheduler (Classic, Core, Root)
13900정성태3/8/20252346스크립트: 72. 파이썬 - SQLAlchemy + oracledb 연동
13899정성태3/7/20251806스크립트: 71. 파이썬 - asyncio의 ContextVar 전달
13898정성태3/5/20252124오류 유형: 948. Visual Studio - Proxy Authentication Required: dotnetfeed.blob.core.windows.net
13897정성태3/5/20252367닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)파일 다운로드1
13896정성태3/5/20252178Windows: 279. Hyper-V Manager - VM 목록의 CPU Usage 항목이 항상 0%로 나오는 문제
13895정성태3/4/20252220Linux: 117. eBPF / bpf2go - Map에 추가된 요소의 개수를 확인하는 방법
13894정성태2/28/20252250Linux: 116. eBPF / bpf2go - BTF Style Maps 정의 구문과 데이터 정렬 문제
13893정성태2/27/20252197Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...