MiCreateHardwareEnclave

INT64 __fastcall MiCreateHardwareEnclave(INT64 a1, INT64 a2, UINT64 a3, VOID *a4){
  _ETHREAD *CurrentThread; 
  __int64 v7; 
  unsigned __int64 v8; 
  _MI_PARTITION *VmPartition; 
  int Enclave; 
  UINT64 EnclavePage; 
  INT64 v13; 
  UINT64 v14; 
  __int64 v15; 
  __int16 v16; 
  bool v17; 
  int v18; 
  _QWORD *v19; 
  _QWORD *v20; 
  UINT64 *v21; 
  UINT64 *ReturnedError; 
  PVOID EnclaveBaseAddress; 
  CurrentThread = (_ETHREAD *)KeGetCurrentThread();
  v7 = *((_QWORD *)CurrentThread + 23);
  EnclaveBaseAddress = (PVOID)((*(unsigned int *)(a2 + 24) | ((unsigned __int64)*(unsigned __int8 *)(a2 + 32) << 32)) << 12);
  v8 = ((*(unsigned int *)(a2 + 28) | ((unsigned __int64)*(unsigned __int8 *)(a2 + 33) << 32)) << 12) | 0xFFF;
  VmPartition = MiGetVmPartition((_MMSUPPORT_INSTANCE *)(v7 + 1664));
  if( !ExAcquireRundownProtection((PEX_RUNDOWN_REF)&stru_140C4EC00) )
    return 3221225738i64;
  if( !a3
    || (Enclave = MiReserveEnclavePages(a2, (UINT64 *)VmPartition, (a3 >> 12) + ((a3 & 0xFFF) != 0)), Enclave >= 0) )
  {
    EnclavePage = MiGetEnclavePage(VmPartition, 0i64);
    v13 = EnclavePage;
    if( EnclavePage == -1i64 )
    {
      Enclave = -1073741801;
    }
    else
    {
      v14 = *(_QWORD *)(a2 + 80);
      MiInitializeEnclavePfn(EnclavePage, (MMPTE *)v14, 4ui64);
      *(_QWORD *)v14 = MiMakeValidPte(v14, v13, 2684354564i64);
      v15 = *(_QWORD *)(v7 + 1408);
      v17 = 0;
      if( v15 )
      {
        v16 = *(_WORD *)(v15 + 8);
        if( v16 == 332 || v16 == 452 )
          v17 = 1;
      }
      v18 = ((*(_DWORD *)(a2 + 72) & 1) << 8) | 1;
      if( v17 )
        v18 = (*(_DWORD *)(a2 + 72) & 1) << 8;
      LODWORD(ReturnedError) = v18;
      Enclave = KeCreateEnclave(
                  (PVOID)((__int64)((v14 << 25) - ((_QWORD)MmGetPteBase() << 25)) >> 16),
                  EnclaveBaseAddress,
                  v8 - (_QWORD)EnclaveBaseAddress + 1,
                  a4,
                  v21,
                  ReturnedError);
      if( Enclave >= 0 )
      {
        *(_QWORD *)(a2 + 112) = v7;
        --*((_WORD *)CurrentThread + 243);
        ExAcquirePushLockExclusiveEx((UINT64)&qword_140C4EBF8, 0i64);
        v19 = (_QWORD *)qword_140C4EBF0;
        v20 = (_QWORD *)(a2 + 120);
        if( *(__int64 **)qword_140C4EBF0 != &qword_140C4EBE8 )
          __fastfail(3u);
        *v20 = &qword_140C4EBE8;
        v20[1] = v19;
        *v19 = v20;
        qword_140C4EBF0 = (__int64)v20;
        if( (_InterlockedExchangeAdd64((volatile signed __int64 *)&qword_140C4EBF8, 0xFFFFFFFFFFFFFFFFui64) & 6) == 2 )
          ExfTryToWakePushLock((volatile INT64 *)&qword_140C4EBF8);
        KeAbPostRelease(&qword_140C4EBF8);
        KiLeaveGuardedRegionUnsafe((__int64)CurrentThread);
        Enclave = 0;
      }
    }
  }
  ExReleaseRundownProtection((PEX_RUNDOWN_REF)&stru_140C4EC00);
  return(unsigned int)Enclave;
}

Referenced by:

MiCreateEnclave