Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)
(시리즈 글이 2개 있습니다.)
.NET Framework: 314. C++의 inline asm 사용을 .NET으로 포팅하는 방법
; https://www.sysnet.pe.kr/2/0/1267

.NET Framework: 543. C++의 inline asm 사용을 .NET으로 포팅하는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/10889




C++의 inline asm 사용을 .NET으로 포팅하는 방법 - 두 번째 이야기

예전에 한번 이에 대해 다룬 글이 있습니다.

C++의 inline asm 사용을 .NET으로 포팅하는 방법
; https://www.sysnet.pe.kr/2/0/1267

근데, 좀 번잡하군요. ^^; 가상 메모리 할당에 실행 권한까지 변경하는 작업이 너무 복잡합니다. 좀 더 간단하게 할 수 있을까요?

생각해 보니, 변경될 어셈블리 코드를 담을 만큼의 충분한 메서드 크기만 보장된다면 차라리 그것을 재활용하는 방법이 더 나을 듯 합니다. "C++의 inline asm 사용을 .NET으로 포팅하는 방법" 글에서 예제로 든 CpuId 값을 구하는 방법을 예로 들어볼까요? ^^

일단, dummy 용도의 메서드를 하나 만드는데요. 크기는 대충 cpuid 코드를 실행할 정도만 안전하게 포함할수만 있으면 됩니다.

public unsafe static void CpuIdInfo(byte *ptr)
{
    Console.WriteLine(0);
    Console.WriteLine(1);
    Console.WriteLine(0);
    Console.WriteLine(1);
    Console.WriteLine(0);
    Console.WriteLine(1);
    Console.WriteLine(0);
    Console.WriteLine(1);
    Console.WriteLine(0);
    Console.WriteLine(1);
    Console.WriteLine(0);
    Console.WriteLine(1);
    Console.WriteLine(0);
    Console.WriteLine(1);
    Console.WriteLine(0);
    Console.WriteLine(1);
}

그다음 cpuid 호출을 하는 기계어 코드를 다음과 같이 마련해 주고,

private readonly static byte[] x86CpuIdBytes =
    {
        0x55,
        0x8B, 0xEC,
        0x53,
        0x57,

        0x33, 0xDB,
        0x8B, 0xF9, // mov edi,ecx   ; stdcall 호출 관행으로 불리기 때문에 ecx에 첫 번째 인자값이 들어 있음.
        0x33, 0xD2,
        0xB8, 0x00, 0x00, 0x00, 0x00,

        0x0F, 0xA2, // cpuid

//      0x8B, 0x7D, 0x08,            ; cdecl 호출 관행인 경우 필요한 것으로 stdcall인 경우 필요없음.

        0x89, 0x07,
        0x89, 0x5F, 0x04,
        0x89, 0x4F, 0x08,
        0x89, 0x57, 0x0C,

        0x5F,
        0x5B,

        0x5D,
        0xC3, // ret
    };

다음과 같이 GetFunctionPointer로 반환받은 위치에 기계어 코드를 덮어써주면 됩니다.

// 주의: x86 코드에서만 동작!!!!
static unsafe void Main(string[] args)
{
    byte[] cpuIdBytes = new byte[4 * 4];

    fixed(byte* idPtr = cpuIdBytes)
    {
        // CpuIdInfo(idPtr);

        RuntimeMethodHandle mh = typeof(Program).GetMethod("CpuIdInfo", BindingFlags.Static | BindingFlags.Public).MethodHandle;
        RuntimeHelpers.PrepareMethod(mh);

        IntPtr ptr = mh.GetFunctionPointer();
        int offset;

        byte* baseCodes = (byte*)ptr.ToPointer();
        byte* asmCodes;

        if (Debugger.IsAttached == true)
        {
            offset = *(int*)(baseCodes + 1);
            asmCodes = baseCodes + offset + 5; // 5byte == 0xe9 xx xx xx xx
        }
        else
        {
            asmCodes = baseCodes;
        }

        offset = 0;
        foreach (byte aByte in x86CpuIdBytes)
        {
            *(asmCodes + offset) = aByte;
            offset++;
        }

        CpuIdInfo(idPtr);
    }

    Console.WriteLine("Cpu Id: " + BitConverter.ToString(cpuIdBytes));
}

훨씬 간단하긴 하지만, GetFunctionPointer가 반환하는 기계어 코드가 디버거 유무에 따라 달라진다는 점과 5바이트 옵셋값이 하드코딩된다는 점이 좀 그렇긴 합니다.

어쨌든, 원리를 알아두는 차원에서 그냥 읽고 이해하기만 하면 될 듯! ^^

(첨부한 코드는 위의 실습 프로젝트입니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2021]

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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12202정성태3/18/202013032개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202010843오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202011292VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/20209155오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202011865오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202011005VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/20208925오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202010657.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202012989오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/20209608개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202012074개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012446개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208608오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013443개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202015649Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208399오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209473오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202010135오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202011589오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/20209941오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
12182정성태3/11/202011155.NET Framework: 901. C# Windows Forms - Vista/7 이후의 Progress Bar 업데이트가 느린 문제파일 다운로드1
12181정성태3/11/202011961기타: 76. 재현 가능한 최소한의 예제 프로젝트란? - 두 번째 예제파일 다운로드1
12180정성태3/10/20208581오류 유형: 600. "Docker Desktop for Windows" - EXPOSE 포트가 LISTENING 되지 않는 문제
12179정성태3/10/202019983개발 환경 구성: 481. docker - PostgreSQL 컨테이너 실행
12178정성태3/10/202011471개발 환경 구성: 480. Linux 운영체제의 docker를 위한 tcp 바인딩 추가 [1]
12177정성태3/9/202011120개발 환경 구성: 479. docker - MySQL 컨테이너 실행
... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...