Microsoft MVP성태의 닷넷 이야기
C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계 [링크 복사], [링크+제목 복사],
조회: 3388
글쓴 사람
정성태 (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)
13651정성태6/19/20245962닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20245904개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20245632오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20245464오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20246134개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20245173오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20245802개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20246310닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20246030오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20246150스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20245992Linux: 71. Ubuntu 20.04를 22.04로 업데이트
13640정성태6/10/20246385Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager)
13639정성태6/8/20245777오류 유형: 906. C# MAUI - Android Emulator에서 "Waiting For Debugger"로 무한 대기
13638정성태6/8/20246096오류 유형: 905. C# MAUI - 추가한 layout XML 파일이 Resource.Layout 멤버로 나오지 않는 문제
13637정성태6/6/20246354Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법
13636정성태5/30/20246255닷넷: 2264. C# - 형식 인자로 인터페이스를 갖는 제네릭 타입으로의 형변환파일 다운로드1
13635정성태5/29/20246481Phone: 19. C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법
13634정성태5/24/20246648Phone: 18. C# MAUI - 안드로이드 플랫폼에서의 Activity 제어 [1]
13633정성태5/22/20246471스크립트: 64. 파이썬 - ASGI를 만족하는 최소한의 구현 코드
13632정성태5/20/20246715Phone: 17. C# MAUI - Android 내에 Web 서비스 호스팅
13631정성태5/19/20247120Phone: 16. C# MAUI - /Download 등의 공용 디렉터리에 접근하는 방법 [1]
13630정성태5/19/20247046닷넷: 2263. C# - Thread가 Task보다 더 빠르다는 어떤 예제(?)
13629정성태5/18/20246934개발 환경 구성: 710. Android - adb.exe를 이용한 파일 전송
13628정성태5/17/20246325개발 환경 구성: 709. Windows - WHPX(Windows Hypervisor Platform)를 이용한 Android Emulator 가속
13627정성태5/17/20246634오류 유형: 904. 파이썬 - UnicodeEncodeError: 'ascii' codec can't encode character '...' in position ...: ordinal not in range(128)
13626정성태5/15/20246571Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...