Harden exception handling in RunawayProcessKiller

pull/744/head
NextTurn 2021-01-02 00:00:00 +08:00
parent ad5f78b3c5
commit 1df29079af
No known key found for this signature in database
GPG Key ID: 6A02A6770B9A88A0
5 changed files with 100 additions and 52 deletions

View File

@ -5,7 +5,7 @@ using static WinSW.Native.HandleApis;
namespace WinSW.Native
{
[StructLayout(LayoutKind.Sequential)]
internal readonly ref struct Handle
internal readonly struct Handle : IDisposable
{
private readonly IntPtr handle;

View File

@ -34,12 +34,20 @@ namespace WinSW.Native
int processInformationLength,
IntPtr returnLength = default);
[DllImport(Libraries.Kernel32)]
internal static extern Handle OpenProcess(ProcessAccess desiredAccess, bool inheritHandle, int processId);
[DllImport(Libraries.Advapi32, SetLastError = true)]
internal static extern bool OpenProcessToken(
IntPtr processHandle,
TokenAccessLevels desiredAccess,
out Handle tokenHandle);
internal enum ProcessAccess : uint
{
QueryInformation = 0x0400,
}
internal enum PROCESSINFOCLASS
{
ProcessBasicInformation = 0,

View File

@ -26,7 +26,11 @@ namespace WinSW.Util
{
foreach (var child in GetChildren(process))
{
StopProcessTree(child, stopTimeout, stopParentProcessFirst);
using (child.Key)
using (child.Value)
{
StopProcessTree(child.Key, stopTimeout, stopParentProcessFirst);
}
}
}
@ -36,7 +40,11 @@ namespace WinSW.Util
{
foreach (var child in GetChildren(process))
{
StopProcessTree(child, stopTimeout, stopParentProcessFirst);
using (child.Key)
using (child.Value)
{
StopProcessTree(child.Key, stopTimeout, stopParentProcessFirst);
}
}
}
}
@ -95,23 +103,33 @@ namespace WinSW.Util
Logger.Debug($"Process {process.Id} has already exited.");
}
private static unsafe List<Process> GetChildren(Process process)
// The handle is to keep a reference to the process.
private static unsafe List<KeyValuePair<Process, Handle>> GetChildren(Process process)
{
var startTime = process.StartTime;
int processId = process.Id;
var children = new List<Process>();
var children = new List<KeyValuePair<Process, Handle>>();
foreach (var other in Process.GetProcesses())
{
var handle = OpenProcess(ProcessAccess.QueryInformation, false, other.Id);
if (handle == IntPtr.Zero)
{
goto Next;
}
try
{
if (other.StartTime <= startTime)
{
goto Next;
}
var handle = other.Handle;
}
catch (Exception e) when (e is InvalidOperationException || e is Win32Exception)
{
goto Next;
}
if (NtQueryInformationProcess(
handle,
@ -125,17 +143,13 @@ namespace WinSW.Util
if ((int)information.InheritedFromUniqueProcessId == processId)
{
Logger.Debug($"Found child process {other.Id}.");
children.Add(other);
children.Add(new(other, handle));
continue;
}
Next:
other.Dispose();
}
catch (Exception e) when (e is InvalidOperationException || e is Win32Exception)
{
other.Dispose();
}
handle.Dispose();
}
return children;

View File

@ -10,6 +10,9 @@ namespace WinSW.Plugins
private const string Kernel32 = "kernel32.dll";
private const string NTDll = "ntdll.dll";
[DllImport(Kernel32)]
internal static extern bool CloseHandle(IntPtr objectHandle);
[DllImport(Kernel32)]
internal static extern int IsWow64Process(IntPtr hProcess, out int Wow64Process);
@ -53,6 +56,14 @@ namespace WinSW.Plugins
long BufferSize,
long NumberOfBytesRead = default);
[DllImport(Kernel32)]
internal static extern IntPtr OpenProcess(ProcessAccess desiredAccess, bool inheritHandle, int processId);
internal enum ProcessAccess : uint
{
QueryInformation = 0x0400,
}
internal enum PROCESSINFOCLASS
{
ProcessBasicInformation = 0,

View File

@ -268,7 +268,17 @@ namespace WinSW.Plugins
// Ensure the process references the service
string expectedEnvVarName = WinSWSystem.EnvVarNameServiceId;
string? affiliatedServiceId = ReadEnvironmentVariable(proc.Handle, expectedEnvVarName);
var processHandle = OpenProcess(ProcessAccess.QueryInformation, false, pid);
if (processHandle == IntPtr.Zero)
{
Logger.Warn("Cannot get process handle of PID=" + pid + ". Assuming that the process has not been started by WinSW.");
return;
}
try
{
string? affiliatedServiceId = ReadEnvironmentVariable(processHandle, expectedEnvVarName);
if (affiliatedServiceId is null && this.CheckWinSWEnvironmentVariable)
{
Logger.Warn("The process " + pid + " has no " + expectedEnvVarName + " environment variable defined. "
@ -302,6 +312,11 @@ namespace WinSW.Plugins
Logger.Warn(bldr.ToString());
ProcessHelper.StopProcessTree(proc, this.StopTimeout, this.StopParentProcessFirst);
}
finally
{
_ = CloseHandle(processHandle);
}
}
/// <summary>
/// Records the started process PID for the future use in OnStart() after the restart.