Microsoft MVP성태의 닷넷 이야기
C/C++: 167. Visual C++ - 윈도우 환경에서 _execv 동작 [링크 복사], [링크+제목 복사],
조회: 6744
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 3개 있습니다.)
Linux: 44. 윈도우 개발자를 위한 리눅스 fork 동작 방식 설명 (파이썬 코드)
; https://www.sysnet.pe.kr/2/0/12811

스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작
; https://www.sysnet.pe.kr/2/0/12843

C/C++: 167. Visual C++ - 윈도우 환경에서 _execv 동작
; https://www.sysnet.pe.kr/2/0/13716




Visual C++ - 윈도우 환경에서 _execv 동작

Windows의 CreateProcess 기능을 리눅스에서는 fork + exec로 표현할 수 있습니다.

그리고 exec... 계열의 함수는 자신의 프로세스 공간에 대상 프로그램을 로딩하는 건데요, 재미있는 건 Visual C++의 CRT 함수에도 동일한 이름의 함수들이 제공됩니다.

하지만, 당연히 리눅스처럼 현재 프로세스 공간에 이미지를 로드하지는 못하고, 대신 자식 프로세스를 생성하는 식으로 우회합니다. 재미있는 건, 이 함수의 사용법인데요, 예를 들어 _execv 함수로,

_execv, _wexecv
; https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/execv-wexecv

다음과 같이 코딩을 할 수 있을 텐데요,

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

#pragma comment(lib, "Shlwapi.lib")

int main(int argc, char** argv)
{
    const char* const argMark[] = {
          "1",
          0 };

    if (argc == 1) // 인자가 1개인 경우에만, 즉 최초 실행했을 때만 자신을 다시 실행
    {
        char path[4096] = { 0 };
        GetModuleFileNameA(nullptr, path, 4096);

        auto result = _execv(path, argMark);
        if (result == -1)
        {
            std::cout << "result: " << errno << "\n";
        }
    }

    std::cout << "Hello World!\n";
}

하지만, 위의 프로그램을 실행하면 errno 값이 12(ENOMEM)로 나오면서 실패합니다. 이유는, 2번째 인자에 넘겨주는 값(위의 경우 argMark)의 형식이, 자신의 경로를 [0]번째 인자에 포함시키는 형식으로 전달해야 하기 때문입니다.

그러니까, 위에서처럼 정말 "1" 인자만 전달한 경우에는 argc 값이 1이 되므로 CreateProcess를 무한정 반복해 말 그대로 ENOMEM 오류가 발생하는 것입니다. 결국, 위의 코드는 아래와 같이 수정해야 합니다.

char path[4096] = { 0 };
GetModuleFileNameA(nullptr, path, 4096);

const char* const argMark[] = { path, "1", 0 };

_execv(path, argMark);

참고로, 윈도우 환경에서의 exec... 함수들은 마치 자신의 프로세스 공간에 이미지를 로드하는 것처럼 흉내 내기 위해 저 함수를 성공적으로 실행한 경우에는 호출 측 프로세스가 바로 종료합니다.




기왕 해본 김에, _execv 함수의 구현을 따라가 볼까요?

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

extern "C" intptr_t __cdecl _execv(
    char const*        const file_name,
    char const* const* const arguments
    )
{
    return common_spawnv(_P_OVERLAY, file_name, arguments, static_cast<char const* const*>(nullptr));
}

template <typename Character>
static intptr_t __cdecl common_spawnv(
    int                     const mode,
    Character const*        const file_name,
    Character const* const* const arguments,
    Character const* const* const environment
    ) throw()
{
    // ...[생략]...

    if (traits::tcsrchr(end_of_directory, '.'))
    {
        // If an extension was provided, just invoke the path:
        if (traits::taccess_s(mutated_file_name, 0) == 0)
        {
            return execute_command(mode, mutated_file_name, arguments, environment);
        }
    }
    else
    {
        // ...[생략]...
    }

    return -1;
}

보는 바와 같이 common_spawnv는 약간의 validation 과정을 거친 후 execute_command로 전달하는데,

// C:\Program Files (x86)\Windows Kits\10\Source\10.0.10240.0\ucrt\exec\spawnv.cpp

// Spawns a child process.  The mode must be one of the _P-modes from <process.h>.
// The return value depends on the mode:
// * _P_OVERLAY:  On success, calls _exit() and does not return. Returns -1 on failure.
// * _P_WAIT:     Returns (termination_code << 8 + result_code)
// * _P_DETACH:   Returns 0 on success; -1 on failure
// * Others:      Returns a handle to the process. The caller must close the handle.
template <typename Character>
static intptr_t __cdecl execute_command(
    int                     const mode,
    Character const*        const file_name,
    Character const* const* const arguments,
    Character const* const* const environment
    ) throw()
{
    // ...[생략]...

    __crt_unique_heap_ptr<BYTE> handle_data;
    size_t                      handle_data_size;
    if (!accumulate_inheritable_handles(handle_data.get_address_of(), &handle_data_size, mode != _P_DETACH))
        return -1;

    DWORD creation_flags = 0;
    if (mode == _P_DETACH)
        creation_flags |= DETACHED_PROCESS;

    if (should_create_unicode_environment(Character()))
        creation_flags |= CREATE_UNICODE_ENVIRONMENT;

    _doserrno = 0;

    STARTUPINFOW startup_info = { };
    startup_info.cb          = sizeof(startup_info);
    startup_info.cbReserved2 = static_cast<WORD>(handle_data_size);
    startup_info.lpReserved2 = handle_data.get();

    PROCESS_INFORMATION process_info;
    BOOL const create_process_status = traits::create_process(
        const_cast<Character*>(file_name),
        command_line.get(),
        nullptr,
        nullptr,
        TRUE,
        creation_flags,
        environment_block.get(),
        nullptr,
        &startup_info,
        &process_info);

    __crt_unique_handle process_handle(process_info.hProcess);
    __crt_unique_handle thread_handle(process_info.hThread);

    if (!create_process_status)
    {
        __acrt_errno_map_os_error(GetLastError());
        return -1;
    }

    if (mode == _P_OVERLAY)
    {
        // Destroy ourselves:
        _exit(0);
    }
    else if (mode == _P_WAIT)
    {
        WaitForSingleObject(process_info.hProcess, static_cast<DWORD>(-1));

        // ...[생략]...
    }
    else if (mode == _P_DETACH)
    {
        /* like totally detached asynchronous spawn, dude,
            close process handle, return 0 for success */
        return 0;
    }
    else
    {
        // Asynchronous spawn:  return process handle:
        return reinterpret_cast<intptr_t>(process_handle.detach());
    }
}

이때 execute_command의 첫 번째 mode 인자에 따라,

1) _P_OVERLAY인 경우, 호출 측, 즉 부모를 exit(0) 함수로 종료하거나 2) _P_WAIT인 경우 자식 프로세스의 종료까지 대기하거나, 3) _P_DETACH인 경우 곧바로 반환을 합니다.

exec... 함수는 저 모드가 무조건 _P_OVERLAY로 고정된 반면 spawn... 계열 함수들은 mode를 선택할 수 있습니다. 일례로,

_spawnv, _wspawnv
; https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/spawnv-wspawnv

intptr_t _spawnv(
   int mode,
   const char *cmdname,
   const char *const *argv
);
intptr_t _wspawnv(
   int mode,
   const wchar_t *cmdname,
   const wchar_t *const *argv
);

저 함수들의 mode로 가능한 값이 _P_OVERLAY, _P_WAIT, _P_DETACH인 것입니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/21/2024]

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

비밀번호

댓글 작성자
 



2025-01-24 11시34분
Linux의 경우 Shell Script에서도 exec 명령어를 통해 현재의 shell 프로세스를 대상 프로세스로 교체하는 기능을 제공합니다.

$ exec --help
exec: exec [-cl] [-a name] [command [arguments ...]] [redirection ...]
    Replace the shell with the given command.

    Execute COMMAND, replacing this shell with the specified program.
    ARGUMENTS become the arguments to COMMAND. If COMMAND is not specified,
    any redirections take effect in the current shell.

    Options:
      -a name pass NAME as the zeroth argument to COMMAND
      -c execute COMMAND with an empty environment
      -l place a dash in the zeroth argument to COMMAND

    If the command cannot be executed, a non-interactive shell exits, unless
    the shell option `execfail' is set.

    Exit Status:
    Returns success unless COMMAND is not found or a redirection error occurs.
정성태

1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13868정성태1/17/20253096Windows: 277. Hyper-V - Windows 11 VM의 Enhanced Session 모드로 로그인을 할 수 없는 문제
13867정성태1/17/20254033오류 유형: 943. Hyper-V에 Windows 11 설치 시 "This PC doesn't currently meet Windows 11 system requirements" 오류
13866정성태1/16/20254230개발 환경 구성: 739. Windows 10부터 바뀐 device driver 서명 방법
13865정성태1/15/20253930오류 유형: 942. C# - .NET Framework 4.5.2 이하의 버전에서 HttpWebRequest로 https 호출 시 "System.Net.WebException" 예외 발생
13864정성태1/15/20253878Linux: 114. eBPF를 위해 필요한 SELinux 보안 정책
13863정성태1/14/20253330Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정
13862정성태1/13/20253601Linux: 112. Linux - 데몬을 위한 SELinux 보안 정책 설정
13861정성태1/11/20253907Windows: 276. 명령행에서 원격 서비스를 동기/비동기로 시작/중지
13860정성태1/10/20253586디버깅 기술: 216. WinDbg - 2가지 유형의 식 평가 방법(MASM, C++)
13859정성태1/9/20253939디버깅 기술: 215. Windbg - syscall 이후 실행되는 KiSystemCall64 함수 및 SSDT 디버깅
13858정성태1/8/20254091개발 환경 구성: 738. PowerShell - 원격 호출 시 "powershell.exe"가 아닌 "pwsh.exe" 환경으로 명령어를 실행하는 방법
13857정성태1/7/20254122C/C++: 187. Golang - 콘솔 응용 프로그램을 Linux 데몬 서비스를 지원하도록 변경파일 다운로드1
13856정성태1/6/20253698디버깅 기술: 214. Windbg - syscall 단계까지의 Win32 API 호출 (예: Sleep)
13855정성태12/28/20244428오류 유형: 941. Golang - os.StartProcess() 사용 시 오류 정리
13854정성태12/27/20244528C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20244012디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20244453디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20244215디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20244711오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20244859디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20244806디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20244823오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20245038디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20244512디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/20245176디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20244366오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...