Skip to content

Commit ec12f8b

Browse files
committed
Add PhTerminateProcessAlternative
1 parent 9b54886 commit ec12f8b

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

phlib/native.c

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,103 @@ NTSTATUS PhTerminateProcessPublic(
474474
);
475475
}
476476

477+
// based on https://www.drdobbs.com/a-safer-alternative-to-terminateprocess/184416547 (dmex)
478+
NTSTATUS PhTerminateProcessAlternative(
479+
_In_ HANDLE ProcessHandle,
480+
_In_ NTSTATUS ExitStatus,
481+
_In_opt_ PLARGE_INTEGER Timeout
482+
)
483+
{
484+
#if (PHNT_VERSION >= PHNT_WIN7)
485+
NTSTATUS status;
486+
#ifdef _WIN64
487+
BOOLEAN isWow64;
488+
#endif
489+
PPH_STRING ntdllFileName = NULL;
490+
PVOID rtlExitUserProcess = NULL;
491+
HANDLE powerRequestHandle = NULL;
492+
HANDLE threadHandle = NULL;
493+
494+
#ifdef _WIN64
495+
if (!NT_SUCCESS(status = PhGetProcessIsWow64(ProcessHandle, &isWow64)))
496+
goto CleanupExit;
497+
498+
if (isWow64)
499+
{
500+
PH_STRINGREF systemRootSr;
501+
502+
PhGetSystemRoot(&systemRootSr);
503+
ntdllFileName = PhConcatStringRefZ(&systemRootSr, L"\\SysWow64\\ntdll.dll");
504+
}
505+
else
506+
{
507+
#endif
508+
PH_STRINGREF systemRootSr;
509+
510+
PhGetSystemRoot(&systemRootSr);
511+
ntdllFileName = PhConcatStringRefZ(&systemRootSr, L"\\System32\\ntdll.dll");
512+
#ifdef _WIN64
513+
}
514+
#endif
515+
516+
if (!NT_SUCCESS(status = PhGetProcedureAddressRemote(
517+
ProcessHandle,
518+
ntdllFileName->Buffer,
519+
"RtlExitUserProcess",
520+
0,
521+
&rtlExitUserProcess,
522+
NULL
523+
)))
524+
{
525+
goto CleanupExit;
526+
}
527+
528+
if (WindowsVersion >= WINDOWS_8)
529+
{
530+
status = PhCreateExecutionRequiredRequest(ProcessHandle, &powerRequestHandle);
531+
532+
if (!NT_SUCCESS(status))
533+
goto CleanupExit;
534+
}
535+
536+
if (!NT_SUCCESS(status = RtlCreateUserThread(
537+
ProcessHandle,
538+
NULL,
539+
FALSE,
540+
0,
541+
0,
542+
0,
543+
rtlExitUserProcess,
544+
LongToPtr(ExitStatus),
545+
&threadHandle,
546+
NULL
547+
)))
548+
{
549+
goto CleanupExit;
550+
}
551+
552+
status = NtWaitForSingleObject(threadHandle, FALSE, Timeout);
553+
554+
CleanupExit:
555+
556+
if (threadHandle)
557+
{
558+
NtClose(threadHandle);
559+
}
560+
561+
if (powerRequestHandle)
562+
{
563+
PhDestroyExecutionRequiredRequest(powerRequestHandle);
564+
}
565+
566+
PhClearReference(&ntdllFileName);
567+
568+
return status;
569+
#else
570+
return STATUS_UNSUCCESSFUL;
571+
#endif
572+
}
573+
477574
/**
478575
* Queries variable-sized information for a process. The function allocates a buffer to contain the
479576
* information.

0 commit comments

Comments
 (0)