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

비밀번호

댓글 작성자
 




... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13439정성태11/10/202311563닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/202311069닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/202311279닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/202311361닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/202310617닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/202310623스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20239442스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/202310240오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/202310764스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/202310964닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/202311119닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/202311265닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/202310752닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/202311265스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/202311137닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/202311044스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/202310780닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리 [1]
13421정성태10/4/202311032닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/202319288스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/202310890스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/202312513닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/202311802닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/202310404오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/202311836닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions) [2]
13414정성태9/16/202311165디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/202312015닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...