/*
* Process Hacker -
* windows handle
*
* Copyright (C) 2008-2009 wj32
*
* This file is part of Process Hacker.
*
* Process Hacker is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Process Hacker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Process Hacker. If not, see .
*/
using System;
using ProcessHacker.Common.Objects;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
using ProcessHacker.Native.Security.AccessControl;
namespace ProcessHacker.Native.Objects
{
///
/// Represents a generic Windows handle which acts as a kernel handle by default.
///
public class NativeHandle : BaseObject, IEquatable, ISecurable, ISynchronizable
{
public static IntPtr Invalid
{
get { return IntPtr.Zero; }
}
public static IntPtr MinusOne
{
get { return (-1).ToIntPtr(); }
}
public static bool IsInvalid(IntPtr handle)
{
return handle == Invalid;
}
public static NtStatus WaitAll(ISynchronizable[] objects)
{
return WaitAll(objects, false, long.MinValue, false);
}
public static NtStatus WaitAll(ISynchronizable[] objects, long timeout)
{
return WaitAll(objects, false, timeout);
}
public static NtStatus WaitAll(ISynchronizable[] objects, bool alertable, long timeout)
{
return WaitAll(objects, alertable, timeout, true);
}
public static NtStatus WaitAll(ISynchronizable[] objects, bool alertable, long timeout, bool relative)
{
return WaitForMultipleObjects(objects, WaitType.WaitAll, alertable, timeout, relative);
}
public static NtStatus WaitAny(ISynchronizable[] objects)
{
return WaitAny(objects, false, long.MinValue, false);
}
public static NtStatus WaitAny(ISynchronizable[] objects, long timeout)
{
return WaitAny(objects, false, timeout);
}
public static NtStatus WaitAny(ISynchronizable[] objects, bool alertable, long timeout)
{
return WaitAny(objects, alertable, timeout, true);
}
public static NtStatus WaitAny(ISynchronizable[] objects, bool alertable, long timeout, bool relative)
{
return WaitForMultipleObjects(objects, WaitType.WaitAny, alertable, timeout, relative);
}
private static NtStatus WaitForMultipleObjects(ISynchronizable[] objects, WaitType waitType, bool alertable, long timeout, bool relative)
{
NtStatus status;
IntPtr[] handles = new IntPtr[objects.Length];
long realTimeout = relative ? -timeout : timeout;
for (int i = 0; i < objects.Length; i++)
handles[i] = objects[i].Handle;
if ((status = Win32.NtWaitForMultipleObjects(
handles.Length,
handles,
waitType,
alertable,
ref realTimeout
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return status;
}
public static implicit operator int(NativeHandle handle)
{
return handle.Handle.ToInt32();
}
public static implicit operator IntPtr(NativeHandle handle)
{
return handle.Handle;
}
private IntPtr _handle;
///
/// Creates a new, invalid handle. You must set the handle using the Handle property.
///
protected NativeHandle()
{ }
///
/// Creates a new handle using the specified value. The handle will be closed when
/// this object is disposed or garbage-collected.
///
/// The handle value.
public NativeHandle(IntPtr handle)
{
_handle = handle;
}
///
/// Creates a new handle using the specified value. If owned is set to false, the
/// handle will not be closed automatically.
///
/// The handle value.
/// Specifies whether the handle will be closed automatically.
public NativeHandle(IntPtr handle, bool owned)
: base(owned)
{
_handle = handle;
}
protected sealed override void DisposeObject(bool disposing)
{
this.Close();
}
///
/// Closes the handle. This method must not be called directly; instead,
/// override this method in a derived class if your handle must be closed
/// with a method other than CloseHandle.
///
protected virtual void Close()
{
if (_handle != IntPtr.Zero && _handle.ToInt32() != -1 && _handle.ToInt32() != -2)
Win32.NtClose(_handle);
}
///
/// Gets the handle value.
///
public IntPtr Handle
{
get { return _handle; }
protected set { _handle = value; }
}
///
/// Determines if the specified object is equal to the current handle.
///
/// The object to compare.
/// Whether the two objects are equal.
public override bool Equals(object obj)
{
return this.Equals(obj as NativeHandle);
}
///
/// Determines if the specified handle is equal to the current handle.
///
/// The handle to compare.
/// Whether the two handles are equal.
public bool Equals(NativeHandle obj)
{
if (obj == null)
return false;
return obj.Handle == this.Handle;
}
///
/// Gets certain information about the handle.
///
/// A HANDLE_FLAGS value.
public virtual Win32HandleFlags GetHandleFlags()
{
Win32HandleFlags flags;
if (!Win32.GetHandleInformation(this, out flags))
Win32.ThrowLastError();
return flags;
}
///
/// Gets a unique hash code for the handle.
///
/// A hash code.
public override int GetHashCode()
{
return _handle.ToInt32();
}
///
/// Gets the handle's name.
///
/// A string.
public virtual string GetObjectName()
{
NtStatus status;
int retLength;
status = Win32.NtQueryObject(this, ObjectInformationClass.ObjectNameInformation,
IntPtr.Zero, 0, out retLength);
if (retLength > 0)
{
using (MemoryAlloc oniMem = new MemoryAlloc(retLength))
{
if ((status = Win32.NtQueryObject(this, ObjectInformationClass.ObjectNameInformation,
oniMem, oniMem.Size, out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
var oni = oniMem.ReadStruct();
return oni.Name.Read();
}
}
else
{
Win32.ThrowLastError(status);
}
return null;
}
///
/// Gets the handle's type name.
///
/// A string.
public virtual string GetObjectTypeName()
{
NtStatus status;
int retLength;
status = Win32.NtQueryObject(this, ObjectInformationClass.ObjectTypeInformation,
IntPtr.Zero, 0, out retLength);
if (retLength > 0)
{
using (MemoryAlloc otiMem = new MemoryAlloc(retLength))
{
if ((status = Win32.NtQueryObject(this, ObjectInformationClass.ObjectTypeInformation,
otiMem, otiMem.Size, out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
var oni = otiMem.ReadStruct();
return oni.Name.Read();
}
}
else
{
Win32.ThrowLastError(status);
}
return null;
}
///
/// Gets the security descriptor of the object.
///
/// The information to retrieve.
/// A security descriptor.
public virtual SecurityDescriptor GetSecurity(SecurityInformation securityInformation)
{
return SecurityDescriptor.GetSecurity(this, securityInformation);
}
///
/// Gets the security descriptor of the object.
///
/// The type of the object.
/// The information to retrieve.
/// A security descriptor.
protected SecurityDescriptor GetSecurity(SeObjectType objectType, SecurityInformation securityInformation)
{
return SecurityDescriptor.GetSecurity(this, objectType, securityInformation);
}
///
/// Makes the object referenced by the handle permanent.
///
public virtual void MakeObjectPermanent()
{
NtStatus status;
if ((status = Win32.NtMakePermanentObject(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
///
/// Makes the object referenced by the handle temporary. The object
/// will be deleted once the last handle to it is closed. This function
/// requires Delete access.
///
public virtual void MakeObjectTemporary()
{
NtStatus status;
if ((status = Win32.NtMakeTemporaryObject(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
///
/// Marks the handle as invalid. This method must only be called from
/// within a derived class constructor.
///
protected void MarkAsInvalid()
{
this.DisableOwnership(false);
}
///
/// Sets certain information about the handle.
///
/// Specifies which flags to set.
/// The values of the flags to set.
public virtual void SetHandleFlags(Win32HandleFlags mask, Win32HandleFlags flags)
{
if (!Win32.SetHandleInformation(this, mask, flags))
Win32.ThrowLastError();
}
///
/// Sets the security descriptor of the object.
///
/// The information to modify.
/// The security descriptor.
public virtual void SetSecurity(SecurityInformation securityInformation, SecurityDescriptor securityDescriptor)
{
SecurityDescriptor.SetSecurity(this, securityInformation, securityDescriptor);
}
///
/// Sets the security descriptor of the object.
///
/// The type of the object.
/// The information to modify.
/// The security descriptor.
protected void SetSecurity(SeObjectType objectType, SecurityInformation securityInformation, SecurityDescriptor securityDescriptor)
{
SecurityDescriptor.SetSecurity(this, objectType, securityInformation, securityDescriptor);
}
///
/// Signals the object and waits for another.
///
public virtual NtStatus SignalAndWait(ISynchronizable waitObject)
{
return this.SignalAndWait(waitObject, false);
}
///
/// Signals the object and waits for another.
///
public virtual NtStatus SignalAndWait(ISynchronizable waitObject, bool alertable)
{
return this.SignalAndWait(waitObject, alertable, long.MinValue, false);
}
///
/// Signals the object and waits for another.
///
public virtual NtStatus SignalAndWait(ISynchronizable waitObject, bool alertable, long timeout)
{
return this.SignalAndWait(waitObject, alertable, timeout, true);
}
///
/// Signals the object and waits for another.
///
public virtual NtStatus SignalAndWait(ISynchronizable waitObject, bool alertable, long timeout, bool relative)
{
NtStatus status;
long realTimeout = relative ? -timeout : timeout;
if ((status = Win32.NtSignalAndWaitForSingleObject(
this,
waitObject.Handle,
alertable,
ref timeout
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return status;
}
///
/// Closes the current handle and assigns a new handle to the NativeHandle instance.
///
/// The new handle value.
protected void SwapHandle(IntPtr newHandle)
{
if (!this.Owned || this.Disposed)
throw new InvalidOperationException();
this.Close();
_handle = newHandle;
}
///
/// Gets a string that represents the handle.
///
/// A string.
public override string ToString()
{
return this.GetType().Name + ": " + _handle.ToString("x");
}
///
/// Waits for the object to be signaled.
///
public virtual NtStatus Wait()
{
return this.Wait(false);
}
///
/// Waits for the object to be signaled.
///
///
/// Whether user-mode APCs can be delivered during the wait.
///
public virtual NtStatus Wait(bool alertable)
{
/* Note that in order to wait for an infinite amount of time
* NULL should be passed as the timeout parameter to
* KeWaitForSingleObject/MultipleObjects. However,
* long.MinValue = -9223372036854775808
* = 9223372036854775808 100ns (relative)
* = 922337203685477580.8 microseconds
* = 922337203685477.5808 ms
* = 922337203685.4775808 s
* = 15372286728.091293013333333333333 minutes
* = 256204778.80152155022222222222222 hours
* = 10675199.116730064592592592592593 days
* = 7306.7755761328299743960250462646 4 years (including one leap year)
* = 29227.102304531319897584100185058 years (average)
* = 29.227102304531319897584100185058 millennia
* That's long enough, I think...
*/
return this.Wait(alertable, long.MinValue, false);
}
///
/// Waits for the object to be signaled.
///
/// The timeout, in 100ns units.
public NtStatus Wait(long timeout)
{
return this.Wait(false, timeout);
}
///
/// Waits for the object to be signaled.
///
///
/// Whether user-mode APCs can be delivered during the wait.
///
/// The timeout, in 100ns units.
public virtual NtStatus Wait(bool alertable, long timeout)
{
return this.Wait(alertable, timeout, true);
}
///
/// Waits for the object to be signaled.
///
/// The timeout, in 100ns units.
/// Whether the timeout value is relative.
public NtStatus Wait(long timeout, bool relative)
{
return this.Wait(false, timeout, relative);
}
///
/// Waits for the object to be signaled.
///
///
/// Whether user-mode APCs can be delivered during the wait.
///
/// The timeout, in 100ns units.
/// Whether the timeout value is relative.
public virtual NtStatus Wait(bool alertable, long timeout, bool relative)
{
NtStatus status;
long realTimeout = relative ? -timeout : timeout;
if ((status = Win32.NtWaitForSingleObject(
this,
alertable,
ref realTimeout
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return status;
}
}
///
/// Represents a generic Windows handle which acts as a kernel handle by default.
///
public class NativeHandle : NativeHandle
where TAccess : struct
{
///
/// Creates a new, invalid handle. You must set the handle using the Handle property.
///
protected NativeHandle()
{ }
///
/// Creates a new handle using the specified value. The handle will be closed when
/// this object is disposed or garbage-collected.
///
/// The handle value.
public NativeHandle(IntPtr handle)
: base(handle)
{ }
///
/// Creates a new handle using the specified value. If owned is set to false, the
/// handle will not be closed automatically.
///
/// The handle value.
/// Specifies whether the handle will be closed automatically.
public NativeHandle(IntPtr handle, bool owned)
: base(handle, owned)
{ }
///
/// Creates a new handle by duplicating an existing handle.
///
/// The existing handle.
/// The desired access to the object.
public NativeHandle(IntPtr handle, TAccess access)
{
IntPtr newHandle;
Win32.DuplicateObject(ProcessHandle.Current, handle, ProcessHandle.Current, out newHandle,
(int)Convert.ChangeType(access, typeof(int)), 0, 0);
this.Handle = newHandle;
}
///
/// Creates a new handle by duplicating an existing handle from another process.
///
/// A handle to a process. It must have the PROCESS_DUP_HANDLE permission.
/// The existing handle.
/// The desired access to the object.
public NativeHandle(ProcessHandle processHandle, IntPtr handle, TAccess access)
{
IntPtr newHandle;
Win32.DuplicateObject(processHandle, handle, ProcessHandle.Current, out newHandle,
(int)Convert.ChangeType(access, typeof(int)), 0, 0);
this.Handle = newHandle;
}
///
/// Attempts to duplicate the handle with different access rights.
///
/// The new access rights.
public void ChangeAccess(TAccess access)
{
IntPtr newHandle;
Win32.DuplicateObject(ProcessHandle.Current, this, ProcessHandle.Current, out newHandle,
(int)Convert.ChangeType(access, typeof(int)), 0, 0);
this.SwapHandle(newHandle);
}
///
/// Duplicates the handle.
///
/// The desired access to the object.
/// A handle.
public NativeHandle Duplicate(TAccess access)
{
return new NativeHandle(ProcessHandle.Current, this, access);
}
}
///
/// Represents a generic Windows handle which acts as a kernel handle by default.
///
public class GenericHandle : NativeHandle
{
///
/// Creates a new, invalid handle. You must set the handle using the Handle property.
///
protected GenericHandle()
: base()
{ }
///
/// Creates a new handle using the specified value. The handle will be closed when
/// this object is disposed or garbage-collected.
///
/// The handle value.
public GenericHandle(IntPtr handle)
: base(handle)
{ }
///
/// Creates a new handle using the specified value. If owned is set to false, the
/// handle will not be closed automatically.
///
/// The handle value.
/// Specifies whether the handle will be closed automatically.
public GenericHandle(IntPtr handle, bool owned)
: base(handle, owned)
{ }
///
/// Creates a new handle by duplicating an existing handle.
///
/// The existing handle.
/// The desired access to the object.
public GenericHandle(IntPtr handle, int desiredAccess)
: base(handle, desiredAccess)
{ }
///
/// Creates a new handle by duplicating an existing handle from another process.
///
/// A handle to a process. It must have the PROCESS_DUP_HANDLE permission.
/// The existing handle.
/// The desired access to the object.
public GenericHandle(ProcessHandle processHandle, IntPtr handle, int desiredAccess)
: base(processHandle, handle, desiredAccess)
{ }
}
}