internal static unsafe JetArchitecture GetProcessArchitecture()

in JetBrains.HabitatDetector/src/Impl/Windows/WindowsHelper.cs [36:82]


    internal static unsafe JetArchitecture GetProcessArchitecture(void* hProcess)
    {
      if (WinApiCalls.GetProcessInformation != null)
      {
        PROCESS_MACHINE_INFORMATION pmi;
        if (WinApiCalls.GetProcessInformation(hProcess, PROCESS_INFORMATION_CLASS.ProcessMachineTypeInfo, &pmi, (uint)sizeof(PROCESS_MACHINE_INFORMATION)) == 0)
        {
          // Note(ww898): PROCESS_INFORMATION_CLASS.ProcessMachineTypeInfo can be not yet implemented. Available since Windows 10.0 Build 22000.
          // Bug(ww898): System.Runtime.InteropServices.Marshal.GetLastWin32Error() under Mono always return 127 here, because no `SetLastError = true` for delegates instead of `DllImportAttribute`!!!
          var error = Kernel32Dll.GetLastError();
          if (error != WinError.ERROR_INVALID_PARAMETER)
            throw new Win32Exception(error);
        }
        else
          return ConvertToArchitecture(pmi.ProcessMachine);
      }

      if (WinApiCalls.IsWow64Process2 != null)
      {
        // Bug(ww898): We can't detect X64 processes on ARM64 OS here!!!
        IMAGE_FILE_MACHINE processImageFileMachine, nativeImageFileMachine;
        // Bug(ww898): System.Runtime.InteropServices.Marshal.GetLastWin32Error() under Mono always return 127 here, because no `SetLastError = true` for delegates instead of `DllImportAttribute`!!!
        if (WinApiCalls.IsWow64Process2(hProcess, &processImageFileMachine, &nativeImageFileMachine) == 0)
          throw new Win32Exception(Kernel32Dll.GetLastError());
        return ConvertToArchitecture(processImageFileMachine == IMAGE_FILE_MACHINE.IMAGE_FILE_MACHINE_UNKNOWN
          ? nativeImageFileMachine
          : processImageFileMachine);
      }

      if (WinApiCalls.IsWow64Process != null)
      {
        int isWow64;
        // Bug(ww898): System.Runtime.InteropServices.Marshal.GetLastWin32Error() under Mono always return 127 here, because no `SetLastError = true` for delegates instead of `DllImportAttribute`!!!
        if (WinApiCalls.IsWow64Process(hProcess, &isWow64) == 0)
          throw new Win32Exception(Kernel32Dll.GetLastError());
        if (isWow64 != 0)
          return JetArchitecture.X86;

        SYSTEM_INFO nativeSystemInfo;
        Kernel32Dll.GetNativeSystemInfo(&nativeSystemInfo);
        return ConvertToArchitecture(nativeSystemInfo.wProcessorArchitecture);
      }

      SYSTEM_INFO systemInfo;
      Kernel32Dll.GetSystemInfo(&systemInfo);
      return ConvertToArchitecture(systemInfo.wProcessorArchitecture);
    }