* moved native API definitions into separate files

* added remaining NT objects
* added NtStatus enum
* added Semaphore properties
* added ObjectFlags to every object
* other refactoring

git-svn-id: svn://svn.code.sf.net/p/processhacker/code@1301 21ef857c-d57f-4fe0-8362-d861dc6d29cd
This commit is contained in:
wj32
2009-05-20 07:05:02 +00:00
parent 396e0538e4
commit 2199520ed5
41 changed files with 4394 additions and 1989 deletions
Binary file not shown.
+8
View File
@@ -37,6 +37,14 @@
/* FUNCTION DEFS */
struct _OBJECT_HANDLE_FLAG_INFORMATION;
typedef struct _OBJECT_TYPE_INITIALIZER OBJECT_TYPE_INITIALIZER, *POBJECT_TYPE_INITIALIZER;
NTSTATUS NTAPI ObCreateObjectType(
PUNICODE_STRING TypeName,
POBJECT_TYPE_INITIALIZER ObjectTypeInitializer,
PSECURITY_DESCRIPTOR SecurityDescriptor,
POBJECT_TYPE *ObjectType
);
NTSTATUS NTAPI ObOpenObjectByName(
POBJECT_ATTRIBUTES ObjectAttributes,
+62 -445
View File
@@ -52,21 +52,6 @@ namespace ProcessHacker.Native.Api
NonZeroLPtr = LMemFixed
}
[Flags]
public enum ContextFlags : int
{
I386 = 0x00010000,
I486 = 0x00010000,
Control = I386 | 0x00000001,
Integer = I386 | 0x00000002,
Segments = I386 | 0x00000004,
FloatingPoint = I386 | 0x00000008,
DebugRegisters = I386 | 0x00000010,
ExtendedRegisters = I386 | 0x00000020,
Full = Control | Integer | Segments,
All = Control | Integer | Segments | FloatingPoint | DebugRegisters | ExtendedRegisters
}
[Flags]
public enum CreationFlags : uint
{
@@ -102,12 +87,6 @@ namespace ProcessHacker.Native.Api
CreateIgnoreSystemDefault = 0x80000000
}
[Flags]
public enum DebugObjectFlags : uint
{
KillOnClose = 0x1
}
public enum DepFlags : uint
{
Disable = 0x00000000,
@@ -123,17 +102,6 @@ namespace ProcessHacker.Native.Api
OptOut
}
public enum EventInformationClass : int
{
EventBasicInformation
}
public enum EventType : int
{
NotificationEvent,
SynchronizationEvent
}
[Flags]
public enum ExitWindowsFlags : uint
{
@@ -146,13 +114,6 @@ namespace ProcessHacker.Native.Api
ForceIfHung = 0x10
}
[Flags]
public enum HandleFlags : byte
{
ProtectFromClose = 0x1,
Inherit = 0x2
}
[Flags]
public enum HeapEntry32Flags : int
{
@@ -161,6 +122,38 @@ namespace ProcessHacker.Native.Api
Moveable = 0x00000004
}
[Flags]
public enum JobObjectLimitFlags : uint
{
WorkingSet = 0x1,
ProcessTime = 0x2,
JobTime = 0x4,
ActiveProcess = 0x8,
Affinity = 0x10,
PriorityClass = 0x20,
PreserveJobTime = 0x40,
SchedulingClass = 0x80,
ProcessMemory = 0x100,
JobMemory = 0x200,
DieOnUnhandledException = 0x400,
BreakawayOk = 0x800,
SilentBreakawayOk = 0x1000,
KillOnJobClose = 0x2000,
}
[Flags]
public enum JobObjectBasicUiRestrictions : uint
{
Handles = 0x1,
ReadClipboard = 0x2,
WriteClipboard = 0x4,
SystemParameters = 0x8,
DisplaySettings = 0x10,
GlobalAtoms = 0x20,
Desktop = 0x40,
ExitWindows = 0x80
}
public enum KWaitReason : int
{
Executive = 0,
@@ -235,32 +228,6 @@ namespace ProcessHacker.Native.Api
Amd64 = 0x8664
}
[Flags]
public enum MemExecuteOptions : int
{
ExecuteDisable = 0x1,
ExecuteEnable = 0x2,
DisableThunkEmulation = 0x4,
Permanent = 0x8
}
[Flags]
public enum MemoryProtection : uint
{
AccessDenied = 0x0,
Execute = 0x10,
ExecuteRead = 0x20,
ExecuteReadWrite = 0x40,
ExecuteWriteCopy = 0x80,
Guard = 0x100,
NoCache = 0x200,
WriteCombine = 0x400,
NoAccess = 0x01,
ReadOnly = 0x02,
ReadWrite = 0x04,
WriteCopy = 0x08
}
[Flags]
public enum MemoryState : uint
{
@@ -278,7 +245,6 @@ namespace ProcessHacker.Native.Api
Release = 0x8000,
Free = 0x10000,
Reset = 0x80000,
TopDown = 0x100000,
Physical = 0x400000,
LargePages = 0x20000000
}
@@ -306,34 +272,6 @@ namespace ProcessHacker.Native.Api
DeleteTcb
}
public enum MutantInformationClass : int
{
MutantBasicInformation
}
public enum ObjectFlags : uint
{
Inherit = 0x2,
Permanent = 0x10,
Exclusive = 0x20,
CaseInsensitive = 0x40,
OpenIf = 0x80,
OpenLink = 0x100,
KernelHandle = 0x200,
ForceAccessCheck = 0x400,
ValidAttributes = 0x7f2
}
public enum ObjectInformationClass : int
{
ObjectBasicInformation = 0,
ObjectNameInformation = 1,
ObjectTypeInformation = 2,
ObjectTypesInformation = 3,
ObjectHandleFlagInformation = 4,
ObjectSessionInformation = 5
}
public enum PeekMessageFlags : int
{
NoRemove = 0,
@@ -352,58 +290,6 @@ namespace ProcessHacker.Native.Api
NonPagedPoolCacheAlignedMustS
}
public enum ProcessInformationClass : int
{
ProcessBasicInformation, // 0
ProcessQuotaLimits,
ProcessIoCounters,
ProcessVmCounters,
ProcessTimes,
ProcessBasePriority,
ProcessRaisePriority,
ProcessDebugPort,
ProcessExceptionPort,
ProcessAccessToken,
ProcessLdtInformation, // 10
ProcessLdtSize,
ProcessDefaultHardErrorMode,
ProcessIoPortHandlers,
ProcessPooledUsageAndLimits,
ProcessWorkingSetWatch,
ProcessUserModeIOPL,
ProcessEnableAlignmentFaultFixup,
ProcessPriorityClass,
ProcessWx86Information,
ProcessHandleCount, // 20
ProcessAffinityMask,
ProcessPriorityBoost,
ProcessDeviceMap,
ProcessSessionInformation,
ProcessForegroundInformation,
ProcessWow64Information,
ProcessImageFileName,
ProcessLUIDDeviceMapsEnabled,
ProcessBreakOnTermination,
ProcessDebugObjectHandle, // 30
ProcessDebugFlags,
ProcessHandleTracing,
ProcessIoPriority,
ProcessExecuteFlags,
ProcessResourceManagement,
ProcessCookie,
ProcessImageInformation,
ProcessCycleTime,
ProcessPagePriority,
ProcessInstrumentationCallback, // 40
ProcessThreadStackAllocation,
ProcessWorkingSetWatchEx,
ProcessImageFileNameWin32,
ProcessImageFileMapping,
ProcessAffinityUpdateMode,
ProcessMemoryAllocationMode,
MaxProcessInfoClass
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct ProfileInformation
{
@@ -417,6 +303,35 @@ namespace ProcessHacker.Native.Api
public int ProfileHandle;
}
[Flags]
public enum RunFileDialogFlags : uint
{
/// <summary>
/// Don't use any of the flags (only works alone)
/// </summary>
None = 0x0000,
/// <summary>
/// Removes the browse button
/// </summary>
NoBrowse = 0x0001,
/// <summary>
/// No default item selected
/// </summary>
NoDefault = 0x0002,
/// <summary>
/// Calculates the working directory from the file name
/// </summary>
CalcDirectory = 0x0004,
/// <summary>
/// Removes the edit box label
/// </summary>
NoLabel = 0x0008,
/// <summary>
/// Removes the seperate memory space checkbox (Windows NT only)
/// </summary>
NoSeparateMemory = 0x0020
}
public enum ScActionType : int
{
None = 0,
@@ -435,38 +350,6 @@ namespace ProcessHacker.Native.Api
UsedForAccess = 0x80000000
}
[Flags]
public enum SectionAttributes : uint
{
File = 0x800000,
Image = 0x1000000,
Reserve = 0x4000000,
Commit = 0x8000000,
NoCache = 0x10000000,
Global = 0x20000000,
LargePages = 0x80000000
}
[Flags]
public enum SectionInformationClass : int
{
SectionBasicInformation,
SectionImageInformation
}
public enum SecurityImpersonationLevel : int
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
public enum SemaphoreInformationClass : int
{
SemaphoreBasicInformation
}
public enum ShowWindowType : uint
{
Hide = 0,
@@ -486,43 +369,6 @@ namespace ProcessHacker.Native.Api
Max = 11
}
public enum SidAttributes : uint
{
Mandatory = 0x00000001,
EnabledByDefault = 0x00000002,
Enabled = 0x00000004,
Owner = 0x00000008,
UseForDenyOnly = 0x00000010,
Integrity = 0x00000020,
IntegrityEnabled = 0x00000040,
LogonId = 0xc0000000,
Resource = 0x20000000
}
public enum SidNameUse : int
{
User = 1,
Group,
Domain,
Alias,
WellKnownGroup,
DeletedAccount,
Invalid,
Unknown,
Computer,
Label
}
[Flags]
public enum SiRequested : uint
{
OwnerSecurityInformation = 0x1,
GroupSecurityInformation = 0x2,
DaclSecurityInformation = 0x4,
SaclSecurityInformation = 0x8,
LabelSecurityInformation = 0x10
}
[Flags]
public enum SmtoFlags : int
{
@@ -620,117 +466,6 @@ namespace ProcessHacker.Native.Api
ParentWin = 0x80,
}
public enum SystemInformationClass : int
{
SystemBasicInformation,
SystemProcessorInformation,
SystemPerformanceInformation,
SystemTimeOfDayInformation,
SystemPathInformation,
SystemProcessInformation,
SystemCallCountInformation,
SystemDeviceInformation,
SystemProcessorPerformanceInformation,
SystemFlagsInformation,
SystemCallTimeInformation, // 10
SystemModuleInformation,
SystemLocksInformation,
SystemStackTraceInformation,
SystemPagedPoolInformation,
SystemNonPagedPoolInformation,
SystemHandleInformation,
SystemObjectInformation,
SystemPageFileInformation,
SystemVdmInstemulInformation,
SystemVdmBopInformation, // 20
SystemFileCacheInformation,
SystemPoolTagInformation,
SystemInterruptInformation,
SystemDpcBehaviorInformation,
SystemFullMemoryInformation,
SystemLoadGdiDriverInformation,
SystemUnloadGdiDriverInformation,
SystemTimeAdjustmentInformation,
SystemSummaryMemoryInformation,
SystemMirrorMemoryInformation, // 30
SystemPerformanceTraceInformation,
SystemCrashDumpInformation,
SystemExceptionInformation,
SystemCrashDumpStateInformation,
SystemKernelDebuggerInformation,
SystemContextSwitchInformation,
SystemRegistryQuotaInformation,
SystemExtendServiceTableInformation, // used to be SystemLoadAndCallImage
SystemPrioritySeparation,
SystemVerifierAddDriverInformation, // 40
SystemVerifierRemoveDriverInformation,
SystemProcessorIdleInformation,
SystemLegacyDriverInformation,
SystemCurrentTimeZoneInformation,
SystemLookasideInformation,
SystemTimeSlipNotification,
SystemSessionCreate,
SystemSessionDetach,
SystemSessionInformation,
SystemRangeStartInformation, // 50
SystemVerifierInformation,
SystemVerifierThunkExtend,
SystemSessionProcessInformation,
SystemLoadGdiDriverInSystemSpace,
SystemNumaProcessorMap,
SystemPrefetcherInformation,
SystemExtendedProcessInformation,
SystemRecommendedSharedDataAlignment,
SystemComPlusPackage,
SystemNumaAvailableMemory, // 60
SystemProcessorPowerInformation,
SystemEmulationBasicInformation,
SystemEmulationProcessorInformation,
SystemExtendedHandleInformation,
SystemLostDelayedWriteInformation,
SystemBigPoolInformation,
SystemSessionPoolTagInformation,
SystemSessionMappedViewInformation,
SystemHotpatchInformation,
SystemObjectSecurityMode, // 70
SystemWatchdogTimerHandler, // doesn't seem to be implemented
SystemWatchdogTimerInformation,
SystemLogicalProcessorInformation,
SystemWow64SharedInformation,
SystemRegisterFirmwareTableInformationHandler,
SystemFirmwareTableInformation,
SystemModuleInformationEx,
SystemVerifierTriageInformation,
SystemSuperfetchInformation,
SystemMemoryListInformation, // 80
SystemFileCacheInformationEx,
SystemNotImplemented19,
SystemProcessorDebugInformation,
SystemVerifierInformation2,
SystemNotImplemented20,
SystemRefTraceInformation,
SystemSpecialPoolTag, // MmSpecialPoolTag, then MmSpecialPoolCatchOverruns != 0
SystemProcessImageName,
SystemNotImplemented21,
SystemBootEnvironmentInformation, // 90
SystemEnlightenmentInformation,
SystemVerifierInformationEx,
SystemNotImplemented22,
SystemNotImplemented23,
SystemCovInformation,
SystemNotImplemented24,
SystemNotImplemented25,
SystemPartitionInformation,
SystemSystemDiskInformation, // this and SystemPartitionInformation both call IoQuerySystemDeviceName
SystemPerformanceDistributionInformation, // 100
SystemNumaProximityNodeInformation,
SystemTimeZoneInformation2,
SystemCodeIntegrityInformation,
SystemNotImplemented26,
SystemUnknownInformation, // No symbols for this case, very strange...
SystemVaInformation // 106, calls MmQuerySystemVaInformation
}
public enum TcpTableClass : int
{
BasicListener,
@@ -744,96 +479,6 @@ namespace ProcessHacker.Native.Api
OwnerModuleAll
}
public enum ThreadInformationClass : uint
{
ThreadBasicInformation,
ThreadTimes,
ThreadPriority,
ThreadBasePriority,
ThreadAffinityMask,
ThreadImpersonationToken,
ThreadDescriptorTableEntry,
ThreadEnableAlignmentFaultFixup,
ThreadEventPair,
ThreadQuerySetWin32StartAddress,
ThreadZeroTlsCell,
ThreadPerformanceCount,
ThreadAmILastThread,
ThreadIdealProcessor,
ThreadPriorityBoost,
ThreadSetTlsArrayAddress,
ThreadIsIoPending,
ThreadHideFromDebugger,
ThreadBreakOnTermination,
ThreadSwitchLegacyState,
ThreadIsTerminated,
ThreadLastSystemCall,
ThreadIoPriority,
ThreadCycleTime,
ThreadPagePriority,
ThreadActualBasePriority,
ThreadTebInformation,
ThreadCSwitchMon,
MaxThreadInfoClass
}
public enum TimerInformationClass : int
{
TimerBasicInformation
}
public enum TimerType : int
{
NotificationTimer,
SynchronizationTimer
}
public enum TokenElevationType : int
{
Default = 1,
Full,
Limited
}
public enum TokenInformationClass
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum
}
public enum TokenType : int
{
Primary = 1,
Impersonation
}
public enum UipiFilterFlag : uint
{
Add = 1,
@@ -852,7 +497,7 @@ namespace ProcessHacker.Native.Api
Object0 = 0x0,
Abandoned = 0x80,
Timeout = 0x102,
Failed = 0xFFFFFFFF
Failed = 0xffffffff
}
[Flags]
@@ -1178,32 +823,4 @@ namespace ProcessHacker.Native.Api
IncomingFrames,
OutgoingFrames
}
[Flags]
public enum RunFileDialogFlags : uint
{
/// <summary>
/// Don't use any of the flags (only works alone)
/// </summary>
None = 0x0000,
/// <summary>
/// Removes the browse button
/// </summary>
NoBrowse = 0x0001,
/// <summary>
/// No default item selected
/// </summary>
NoDefault = 0x0002,
/// <summary>
/// Calculates the working directory from the file name
/// </summary>
CalcDirectory = 0x0004,
/// <summary>
/// Removes the edit box label
/// </summary>
NoLabel = 0x0008,
/// <summary>
/// Removes the seperate memory space checkbox (Windows NT only)
/// </summary>
NoSeperateMemory = 0x0020
}
}
+5 -8
View File
@@ -117,9 +117,6 @@ namespace ProcessHacker.Native.Api
#region Error Handling
[DllImport("ntdll.dll")]
public static extern int RtlNtStatusToDosError([In] int Status);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int FormatMessage(
[In] int Flags,
@@ -752,12 +749,12 @@ namespace ProcessHacker.Native.Api
#region LSA
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LsaFreeMemory(
public static extern NtStatus LsaFreeMemory(
[In] IntPtr Memory
);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LsaEnumerateAccountsWithUserRight(
public static extern NtStatus LsaEnumerateAccountsWithUserRight(
[In] IntPtr PolicyHandle,
[In] IntPtr UserRights,
[Out] out IntPtr SIDs,
@@ -765,7 +762,7 @@ namespace ProcessHacker.Native.Api
);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LsaAddAccountRights(
public static extern NtStatus LsaAddAccountRights(
[In] IntPtr PolicyHandle,
[In] IntPtr AccountSid,
[In] UnicodeString[] UserRights,
@@ -773,7 +770,7 @@ namespace ProcessHacker.Native.Api
);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LsaOpenPolicy(
public static extern NtStatus LsaOpenPolicy(
[In] IntPtr SystemName,
[In] ref ObjectAttributes ObjectAttributes,
[In] PolicyAccess DesiredAccess,
@@ -781,7 +778,7 @@ namespace ProcessHacker.Native.Api
);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LsaClose(
public static extern NtStatus LsaClose(
[In] IntPtr Handle
);
@@ -0,0 +1,44 @@
/*
* Process Hacker -
* native API consts and delegates
*
* 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ProcessHacker.Native.Api
{
public delegate void TimerApcRoutine(IntPtr context, int lowValue, int highValue);
public partial class Win32
{
public const int MaximumSupportedExtension = 512;
public const int SecurityDescriptorMinLength = 20;
public const int SecurityDescriptorRevision = 1;
public readonly int SecurityMaxSidSize =
Marshal.SizeOf(typeof(Sid)) - sizeof(int) + (SidMaxSubAuthorities * sizeof(int));
public const int SidMaxSubAuthorities = 15;
public const int SidRecommendedSubAuthorities = 1;
public const int SidRevision = 1;
public const int SizeOf80387Registers = 80;
}
}
@@ -0,0 +1,569 @@
/*
* Process Hacker -
* native API enumerations
*
* Copyright (C) 2009 Flavio Erlich
* 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace ProcessHacker.Native.Api
{
[Flags]
public enum ContextFlags : int
{
I386 = 0x00010000,
I486 = 0x00010000,
Control = I386 | 0x00000001,
Integer = I386 | 0x00000002,
Segments = I386 | 0x00000004,
FloatingPoint = I386 | 0x00000008,
DebugRegisters = I386 | 0x00000010,
ExtendedRegisters = I386 | 0x00000020,
Full = Control | Integer | Segments,
All = Control | Integer | Segments | FloatingPoint | DebugRegisters | ExtendedRegisters
}
[Flags]
public enum DebugObjectFlags : uint
{
KillOnClose = 0x1
}
[Flags]
public enum DuplicateOptions : int
{
CloseSource = 0x1,
SameAccess = 0x2,
SameAttributes = 0x4
}
public enum EventInformationClass : int
{
EventBasicInformation
}
public enum EventType : int
{
NotificationEvent,
SynchronizationEvent
}
[Flags]
public enum HandleFlags : byte
{
ProtectFromClose = 0x1,
Inherit = 0x2
}
[Flags]
public enum HashStringAlgorithm : int
{
Default = 0,
X65599 = 1,
Invalid = -1
}
public enum JobObjectInformationClass : int
{
JobObjectBasicAccountingInformation = 1,
JobObjectBasicLimitInformation,
JobObjectBasicProcessIdList,
JobObjectBasicUIRestrictions,
JobObjectSecurityLimitInformation,
JobObjectEndOfJobTimeInformation,
JobObjectAssociateCompletionPortInformation,
JobObjectBasicAndIoAccountingInformation,
JobObjectExtendedLimitInformation,
JobObjectJobSetInformation
}
public enum KProfileSource : int
{
ProfileTime,
ProfileAlignmentFixup,
ProfileTotalIssues,
ProfilePipelineDry,
ProfileLoadInstructions,
ProfilePipelineFrozen,
ProfileBranchInstructions,
ProfileTotalNonissues,
ProfileDcacheMisses,
ProfileIcacheMisses,
ProfileCacheMisses,
ProfileBranchMispredictions,
ProfileStoreInstructions,
ProfileFpInstructions,
ProfileIntegerInstructions,
Profile2Issue,
Profile3Issue,
Profile4Issue,
ProfileSpecialInstructions,
ProfileTotalCycles,
ProfileIcacheIssues,
ProfileDcacheAccesses,
ProfileMemoryBarrierCycles,
ProfileLoadLinkedIssues,
ProfileMaximum
}
[Flags]
public enum MemExecuteOptions : int
{
ExecuteDisable = 0x1,
ExecuteEnable = 0x2,
DisableThunkEmulation = 0x4,
Permanent = 0x8
}
[Flags]
public enum MemoryFlags : uint
{
Commit = 0x1000,
Reserve = 0x2000,
Decommit = 0x4000,
Release = 0x8000,
Free = 0x10000,
Private = 0x20000,
Mapped = 0x40000,
Reset = 0x80000,
TopDown = 0x100000,
WriteWatch = 0x200000,
Physical = 0x400000,
LargePages = 0x20000000,
DosLimit = 0x40000000,
FourMbPages = 0x80000000
}
public enum MemoryInformationClass : int
{
MemoryBasicInformation,
MemoryWorkingSetInformation,
MemoryMappedFilenameInformation,
MemoryRegionInformation,
MemoryWorkingSetExInformation
}
[Flags]
public enum MemoryProtection : uint
{
AccessDenied = 0x0,
Execute = 0x10,
ExecuteRead = 0x20,
ExecuteReadWrite = 0x40,
ExecuteWriteCopy = 0x80,
Guard = 0x100,
NoCache = 0x200,
WriteCombine = 0x400,
NoAccess = 0x01,
ReadOnly = 0x02,
ReadWrite = 0x04,
WriteCopy = 0x08
}
public enum MutantInformationClass : int
{
MutantBasicInformation
}
public enum ObjectFlags : uint
{
Inherit = 0x2,
Permanent = 0x10,
Exclusive = 0x20,
CaseInsensitive = 0x40,
OpenIf = 0x80,
OpenLink = 0x100,
KernelHandle = 0x200,
ForceAccessCheck = 0x400,
ValidAttributes = 0x7f2
}
public enum ObjectInformationClass : int
{
ObjectBasicInformation = 0,
ObjectNameInformation = 1,
ObjectTypeInformation = 2,
ObjectTypesInformation = 3,
ObjectHandleFlagInformation = 4,
ObjectSessionInformation = 5
}
public enum ProcessInformationClass : int
{
ProcessBasicInformation, // 0
ProcessQuotaLimits,
ProcessIoCounters,
ProcessVmCounters,
ProcessTimes,
ProcessBasePriority,
ProcessRaisePriority,
ProcessDebugPort,
ProcessExceptionPort,
ProcessAccessToken,
ProcessLdtInformation, // 10
ProcessLdtSize,
ProcessDefaultHardErrorMode,
ProcessIoPortHandlers,
ProcessPooledUsageAndLimits,
ProcessWorkingSetWatch,
ProcessUserModeIOPL,
ProcessEnableAlignmentFaultFixup,
ProcessPriorityClass,
ProcessWx86Information,
ProcessHandleCount, // 20
ProcessAffinityMask,
ProcessPriorityBoost,
ProcessDeviceMap,
ProcessSessionInformation,
ProcessForegroundInformation,
ProcessWow64Information,
ProcessImageFileName,
ProcessLUIDDeviceMapsEnabled,
ProcessBreakOnTermination,
ProcessDebugObjectHandle, // 30
ProcessDebugFlags,
ProcessHandleTracing,
ProcessIoPriority,
ProcessExecuteFlags,
ProcessResourceManagement,
ProcessCookie,
ProcessImageInformation,
ProcessCycleTime,
ProcessPagePriority,
ProcessInstrumentationCallback, // 40
ProcessThreadStackAllocation,
ProcessWorkingSetWatchEx,
ProcessImageFileNameWin32,
ProcessImageFileMapping,
ProcessAffinityUpdateMode,
ProcessMemoryAllocationMode,
MaxProcessInfoClass
}
[Flags]
public enum RtlDuplicateUnicodeStringFlags : int
{
NullTerminate = 0x1,
AllocateNullString = 0x2
}
[Flags]
public enum RtlUserProcessFlags : uint
{
ParamsNormalized = 0x00000001,
ProfileUser = 0x00000002,
ProfileKernel = 0x00000004,
ProfileServer = 0x00000008,
Reserve1Mb = 0x00000020,
Reserve16Mb = 0x00000040,
CaseSensitive = 0x00000080,
DisableHeapDecommit = 0x00000100,
DllRedirectionLocal = 0x00001000,
AppManifestPresent = 0x00002000,
ImageKeyMissing = 0x00004000,
OptInProcess = 0x00020000
}
[Flags]
public enum SectionAttributes : uint
{
Based = 0x200000,
NoChange = 0x400000,
File = 0x800000,
Image = 0x1000000,
Reserve = 0x4000000,
Commit = 0x8000000,
NoCache = 0x10000000,
Global = 0x20000000,
LargePages = 0x80000000
}
[Flags]
public enum SectionInformationClass : int
{
SectionBasicInformation,
SectionImageInformation
}
public enum SectionInherit : int
{
ViewShare = 1,
ViewUnmap = 2
}
public enum SecurityImpersonationLevel : int
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
public enum SemaphoreInformationClass : int
{
SemaphoreBasicInformation
}
public enum SidAttributes : uint
{
Mandatory = 0x00000001,
EnabledByDefault = 0x00000002,
Enabled = 0x00000004,
Owner = 0x00000008,
UseForDenyOnly = 0x00000010,
Integrity = 0x00000020,
IntegrityEnabled = 0x00000040,
LogonId = 0xc0000000,
Resource = 0x20000000
}
public enum SidNameUse : int
{
User = 1,
Group,
Domain,
Alias,
WellKnownGroup,
DeletedAccount,
Invalid,
Unknown,
Computer,
Label
}
[Flags]
public enum SiRequested : uint
{
OwnerSecurityInformation = 0x1,
GroupSecurityInformation = 0x2,
DaclSecurityInformation = 0x4,
SaclSecurityInformation = 0x8,
LabelSecurityInformation = 0x10
}
public enum SystemInformationClass : int
{
SystemBasicInformation,
SystemProcessorInformation,
SystemPerformanceInformation,
SystemTimeOfDayInformation,
SystemPathInformation,
SystemProcessInformation,
SystemCallCountInformation,
SystemDeviceInformation,
SystemProcessorPerformanceInformation,
SystemFlagsInformation,
SystemCallTimeInformation, // 10
SystemModuleInformation,
SystemLocksInformation,
SystemStackTraceInformation,
SystemPagedPoolInformation,
SystemNonPagedPoolInformation,
SystemHandleInformation,
SystemObjectInformation,
SystemPageFileInformation,
SystemVdmInstemulInformation,
SystemVdmBopInformation, // 20
SystemFileCacheInformation,
SystemPoolTagInformation,
SystemInterruptInformation,
SystemDpcBehaviorInformation,
SystemFullMemoryInformation,
SystemLoadGdiDriverInformation,
SystemUnloadGdiDriverInformation,
SystemTimeAdjustmentInformation,
SystemSummaryMemoryInformation,
SystemMirrorMemoryInformation, // 30
SystemPerformanceTraceInformation,
SystemCrashDumpInformation,
SystemExceptionInformation,
SystemCrashDumpStateInformation,
SystemKernelDebuggerInformation,
SystemContextSwitchInformation,
SystemRegistryQuotaInformation,
SystemExtendServiceTableInformation, // used to be SystemLoadAndCallImage
SystemPrioritySeparation,
SystemVerifierAddDriverInformation, // 40
SystemVerifierRemoveDriverInformation,
SystemProcessorIdleInformation,
SystemLegacyDriverInformation,
SystemCurrentTimeZoneInformation,
SystemLookasideInformation,
SystemTimeSlipNotification,
SystemSessionCreate,
SystemSessionDetach,
SystemSessionInformation,
SystemRangeStartInformation, // 50
SystemVerifierInformation,
SystemVerifierThunkExtend,
SystemSessionProcessInformation,
SystemLoadGdiDriverInSystemSpace,
SystemNumaProcessorMap,
SystemPrefetcherInformation,
SystemExtendedProcessInformation,
SystemRecommendedSharedDataAlignment,
SystemComPlusPackage,
SystemNumaAvailableMemory, // 60
SystemProcessorPowerInformation,
SystemEmulationBasicInformation,
SystemEmulationProcessorInformation,
SystemExtendedHandleInformation,
SystemLostDelayedWriteInformation,
SystemBigPoolInformation,
SystemSessionPoolTagInformation,
SystemSessionMappedViewInformation,
SystemHotpatchInformation,
SystemObjectSecurityMode, // 70
SystemWatchdogTimerHandler, // doesn't seem to be implemented
SystemWatchdogTimerInformation,
SystemLogicalProcessorInformation,
SystemWow64SharedInformation,
SystemRegisterFirmwareTableInformationHandler,
SystemFirmwareTableInformation,
SystemModuleInformationEx,
SystemVerifierTriageInformation,
SystemSuperfetchInformation,
SystemMemoryListInformation, // 80
SystemFileCacheInformationEx,
SystemNotImplemented19,
SystemProcessorDebugInformation,
SystemVerifierInformation2,
SystemNotImplemented20,
SystemRefTraceInformation,
SystemSpecialPoolTag, // MmSpecialPoolTag, then MmSpecialPoolCatchOverruns != 0
SystemProcessImageName,
SystemNotImplemented21,
SystemBootEnvironmentInformation, // 90
SystemEnlightenmentInformation,
SystemVerifierInformationEx,
SystemNotImplemented22,
SystemNotImplemented23,
SystemCovInformation,
SystemNotImplemented24,
SystemNotImplemented25,
SystemPartitionInformation,
SystemSystemDiskInformation, // this and SystemPartitionInformation both call IoQuerySystemDeviceName
SystemPerformanceDistributionInformation, // 100
SystemNumaProximityNodeInformation,
SystemTimeZoneInformation2,
SystemCodeIntegrityInformation,
SystemNotImplemented26,
SystemUnknownInformation, // No symbols for this case, very strange...
SystemVaInformation // 106, calls MmQuerySystemVaInformation
}
public enum ThreadInformationClass : uint
{
ThreadBasicInformation,
ThreadTimes,
ThreadPriority,
ThreadBasePriority,
ThreadAffinityMask,
ThreadImpersonationToken,
ThreadDescriptorTableEntry,
ThreadEnableAlignmentFaultFixup,
ThreadEventPair,
ThreadQuerySetWin32StartAddress,
ThreadZeroTlsCell,
ThreadPerformanceCount,
ThreadAmILastThread,
ThreadIdealProcessor,
ThreadPriorityBoost,
ThreadSetTlsArrayAddress,
ThreadIsIoPending,
ThreadHideFromDebugger,
ThreadBreakOnTermination,
ThreadSwitchLegacyState,
ThreadIsTerminated,
ThreadLastSystemCall,
ThreadIoPriority,
ThreadCycleTime,
ThreadPagePriority,
ThreadActualBasePriority,
ThreadTebInformation,
ThreadCSwitchMon,
MaxThreadInfoClass
}
public enum TimerInformationClass : int
{
TimerBasicInformation
}
public enum TimerType : int
{
NotificationTimer,
SynchronizationTimer
}
public enum TokenElevationType : int
{
Default = 1,
Full,
Limited
}
public enum TokenInformationClass
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum
}
public enum TokenType : int
{
Primary = 1,
Impersonation
}
public enum WaitType : int
{
WaitAll,
WaitAny
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+131
View File
@@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace ProcessHacker.Native.Api
{
public enum NtStatus : uint
{
// Success
Success = 0x00000000,
Wait0 = 0x00000000,
Wait1 = 0x00000001,
Wait2 = 0x00000002,
Wait3 = 0x00000003,
Wait63 = 0x0000003f,
Abandoned = 0x00000080,
AbandonedWait0 = 0x00000080,
AbandonedWait1 = 0x00000081,
AbandonedWait2 = 0x00000082,
AbandonedWait3 = 0x00000083,
AbandonedWait63 = 0x000000bf,
UserApc = 0x000000c0,
KernelApc = 0x00000100,
Alerted = 0x00000101,
Timeout = 0x00000102,
Pending = 0x00000103,
Reparse = 0x00000104,
MoreEntries = 0x00000105,
NotAllAssigned = 0x00000106,
SomeNotMapped = 0x00000107,
OpLockBreakInProgress = 0x00000108,
VolumeMounted = 0x00000109,
PageFaultTransition = 0x00000110,
PageFaultDemandZero = 0x00000111,
PageFaultCopyOnWrite = 0x00000112,
PageFaultGuardPage = 0x00000113,
PageFaultPagingFile = 0x00000114,
CrashDump = 0x00000116,
ReparseObject = 0x00000118,
NothingToTerminate = 0x00000122,
ProcessNotInJob = 0x00000123,
ProcessInJob = 0x00000124,
ProcessCloned = 0x00000129,
// Informational
Informational = 0x40000000,
ObjectNameExists = 0x40000000,
ThreadWasSuspended = 0x40000001,
// Warning
Warning = 0x80000000,
GuardPageViolation = 0x80000001,
DatatypeMisalignment = 0x80000002,
Breakpoint = 0x80000003,
SingleStep = 0x80000004,
BufferOverflow = 0x80000005,
NoMoreFiles = 0x80000006,
HandlesClosed = 0x8000000a,
PartialCopy = 0x8000000d,
DeviceBusy = 0x80000011,
InvalidEaName = 0x80000013,
EaListInconsistent = 0x80000014,
LongJump = 0x80000026,
DllMightBeInsecure = 0x8000002b,
// Error
Error = 0xc0000000,
Unsuccessful = 0xc0000001,
NotImplemented = 0xc0000002,
InvalidInfoClass = 0xc0000003,
InfoLengthMismatch = 0xc0000004,
AccessViolation = 0xc0000005,
InPageError = 0xc0000006,
PagefileQuota = 0xc0000007,
InvalidHandle = 0xc0000008,
BadInitialStack = 0xc0000009,
BadInitialPc = 0xc000000a,
InvalidCid = 0xc000000b,
TimerNotCanceled = 0xc000000c,
InvalidParameter = 0xc000000d,
NoSuchDevice = 0xc000000e,
NoSuchFile = 0xc000000f,
InvalidDeviceRequest = 0xc0000010,
EndOfFile = 0xc0000011,
WrongVolume = 0xc0000012,
NoMediaInDevice = 0xc0000013,
NoMemory = 0xc0000017,
NotMappedView = 0xc0000019,
UnableToFreeVm = 0xc000001a,
UnableToDeleteSection = 0xc000001b,
IllegalInstruction = 0xc000001d,
AlreadyCommitted = 0xc0000021,
AccessDenied = 0xc0000022,
BufferTooSmall = 0xc0000023,
ObjectTypeMismatch = 0xc0000024,
NonContinuableException = 0xc0000025,
BadStack = 0xc0000028,
NotLocked = 0xc000002a,
NotCommitted = 0xc000002d,
InvalidParameterMix = 0xc0000030,
ObjectNameInvalid = 0xc0000033,
ObjectNameNotFound = 0xc0000034,
ObjectNameCollision = 0xc0000035,
ObjectPathInvalid = 0xc0000039,
ObjectPathSyntaxBad = 0xc000003b,
QuotaExceeded = 0xc0000044,
InvalidPageProtection = 0xc0000045,
MutantNotOwned = 0xc0000046,
SemaphoreLimitExceeded = 0xc0000047,
SuspendCountExceeded = 0xc000004a,
ThreadIsTerminating = 0xc000004b,
NotSameDevice = 0xc00000d4,
FileRenamed = 0xc00000d5,
CantWait = 0xc00000d8,
PipeEmpty = 0xc00000d9,
CantTerminateSelf = 0xc00000db,
InternalError = 0xc00000e5,
InvalidParameter1 = 0xc00000ef,
InvalidParameter2 = 0xc00000f0,
InvalidParameter3 = 0xc00000f1,
InvalidParameter4 = 0xc00000f2,
InvalidParameter5 = 0xc00000f3,
InvalidParameter6 = 0xc00000f4,
InvalidParameter7 = 0xc00000f5,
InvalidParameter8 = 0xc00000f6,
InvalidParameter9 = 0xc00000f7,
InvalidParameter10 = 0xc00000f8,
InvalidParameter11 = 0xc00000f9,
InvalidParameter12 = 0xc00000fa,
}
}
File diff suppressed because it is too large Load Diff
+9 -9
View File
@@ -271,8 +271,8 @@ namespace ProcessHacker.Native
int targetProcessHandle,
out int targetHandle,
int desiredAccess,
int handleAttributes,
int options
HandleFlags handleAttributes,
DuplicateOptions options
)
{
int handle;
@@ -296,8 +296,8 @@ namespace ProcessHacker.Native
int targetProcessHandle,
int targetHandle,
int desiredAccess,
int handleAttributes,
int options
HandleFlags handleAttributes,
DuplicateOptions options
)
{
byte[] data = new byte[7 * sizeof(int)];
@@ -309,8 +309,8 @@ namespace ProcessHacker.Native
*(int*)(dataPtr + 0x8) = targetProcessHandle;
*(int*)(dataPtr + 0xc) = targetHandle;
*(int*)(dataPtr + 0x10) = desiredAccess;
*(int*)(dataPtr + 0x14) = handleAttributes;
*(int*)(dataPtr + 0x18) = options;
*(int*)(dataPtr + 0x14) = (int)handleAttributes;
*(int*)(dataPtr + 0x18) = (int)options;
_fileHandle.IoControl(CtlCode(Control.KphDuplicateObject), data, null);
}
@@ -646,7 +646,7 @@ namespace ProcessHacker.Native
return _fileHandle.IoControl(CtlCode(Control.Write), inData, data.Length + 4, null, 0);
}
public int ZwQueryObject(
public NtStatus ZwQueryObject(
ProcessHandle processHandle,
IntPtr handle,
ObjectInformationClass objectInformationClass,
@@ -665,11 +665,11 @@ namespace ProcessHacker.Native
_fileHandle.IoControl(CtlCode(Control.ZwQueryObject), inData, 12, outData);
int status;
NtStatus status;
fixed (byte* outDataPtr = outData)
{
status = *(int*)outDataPtr;
status = *(NtStatus*)outDataPtr;
returnLength = *(int*)(outDataPtr + 4);
baseAddress = *(int*)(outDataPtr + 8);
}
@@ -0,0 +1,60 @@
/*
* Process Hacker -
* PEB memory allocation
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.Memory
{
/// <summary>
/// Represents a memory allocation from the PEB.
/// </summary>
public class PebMemoryAlloc : MemoryAlloc
{
public PebMemoryAlloc(int size)
{
NtStatus status;
IntPtr block;
if ((status = Win32.RtlAllocateFromPeb(size, out block)) >= NtStatus.Error)
Win32.ThrowLastError(status);
this.Memory = block;
this.Size = size;
}
public override void Resize(int newSize)
{
throw new NotSupportedException();
}
protected override void Free()
{
NtStatus status;
if ((status = Win32.RtlFreeToPeb(this, this.Size)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
}
}
@@ -0,0 +1,63 @@
/*
* Process Hacker -
* mapped view of section
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
namespace ProcessHacker.Native.Memory
{
/// <summary>
/// Represents a mapped view of a section.
/// </summary>
public class SectionView : MemoryAlloc
{
internal SectionView(IntPtr baseAddress, IntPtr commitSize)
{
this.Memory = baseAddress;
this.Size = commitSize.ToInt32();
}
protected override void Free()
{
NtStatus status;
if ((status = Win32.NtUnmapViewOfSection(ProcessHandle.GetCurrent(), this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
public bool IsSameFile(SectionView mappedAsFile)
{
if ((uint)Win32.NtAreMappedFilesTheSame(this, mappedAsFile) == this.Memory.ToUInt32())
return true;
else
return false;
}
public override void Resize(int newSize)
{
throw new NotSupportedException();
}
}
}
@@ -32,7 +32,7 @@ namespace ProcessHacker.Native.Objects
{
public static DebugObjectHandle Create(DebugObjectAccess access, DebugObjectFlags flags)
{
int status;
NtStatus status;
IntPtr handle;
if ((status = Win32.NtCreateDebugObject(
@@ -40,7 +40,7 @@ namespace ProcessHacker.Native.Objects
access,
IntPtr.Zero,
flags
)) < 0)
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return new DebugObjectHandle(handle, true);
@@ -1,4 +1,26 @@
using System;
/*
* Process Hacker -
* directory handle
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -24,18 +46,18 @@ namespace ProcessHacker.Native.Objects
public DirectoryHandle Create(DirectoryAccess access, string name)
{
return this.Create(access, name, null);
return this.Create(access, name, 0, null);
}
public DirectoryHandle Create(DirectoryAccess access, string name, DirectoryHandle rootDirectory)
public DirectoryHandle Create(DirectoryAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateDirectoryObject(out handle, access, ref oa)) < 0)
if ((status = Win32.NtCreateDirectoryObject(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -50,15 +72,15 @@ namespace ProcessHacker.Native.Objects
: base(handle, owned)
{ }
public DirectoryHandle(string name, DirectoryHandle rootDirectory, DirectoryAccess access)
public DirectoryHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, DirectoryAccess access)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtOpenDirectoryObject(out handle, access, ref oa)) < 0)
if ((status = Win32.NtOpenDirectoryObject(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -70,7 +92,7 @@ namespace ProcessHacker.Native.Objects
}
public DirectoryHandle(string name, DirectoryAccess access)
: this(name, null, access)
: this(name, 0, null, access)
{ }
/// <summary>
@@ -79,7 +101,7 @@ namespace ProcessHacker.Native.Objects
/// <returns>An array of object entries.</returns>
public ObjectEntry[] Query()
{
int status;
NtStatus status;
int context = 0;
int retLength;
var objectList = new List<ObjectEntry>();
@@ -87,7 +109,7 @@ namespace ProcessHacker.Native.Objects
using (var data = new MemoryAlloc(0x400))
{
// NtQueryDirectoryObject isn't very nice.
while ((uint)(status = Win32.NtQueryDirectoryObject(
while ((status = Win32.NtQueryDirectoryObject(
this,
data,
data.Size,
@@ -95,7 +117,7 @@ namespace ProcessHacker.Native.Objects
false,
ref context,
out retLength
)) == Win32.STATUS_INFO_LENGTH_MISMATCH)
)) == NtStatus.InfoLengthMismatch)
{
if (data.Size > 16 * 1024 * 1024)
Win32.ThrowLastError(status);
@@ -1,4 +1,26 @@
using System;
/*
* Process Hacker -
* event handle
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -14,18 +36,18 @@ namespace ProcessHacker.Native.Objects
public static EventHandle Create(EventAccess access, string name, EventType type, bool initialState)
{
return Create(access, name, null, type, initialState);
return Create(access, name, 0, null, type, initialState);
}
public static EventHandle Create(EventAccess access, string name, DirectoryHandle rootDirectory, EventType type, bool initialState)
public static EventHandle Create(EventAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, EventType type, bool initialState)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateEvent(out handle, access, ref oa, type, initialState)) < 0)
if ((status = Win32.NtCreateEvent(out handle, access, ref oa, type, initialState)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -36,19 +58,24 @@ namespace ProcessHacker.Native.Objects
return new EventHandle(handle, true);
}
public static EventHandle FromHandle(IntPtr handle)
{
return new EventHandle(handle, false);
}
private EventHandle(IntPtr handle, bool owned)
: base(handle, owned)
{ }
public EventHandle(string name, DirectoryHandle rootDirectory, EventAccess access)
public EventHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, EventAccess access)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtOpenEvent(out handle, access, ref oa)) < 0)
if ((status = Win32.NtOpenEvent(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -59,44 +86,48 @@ namespace ProcessHacker.Native.Objects
this.Handle = handle;
}
public EventHandle(string name, EventAccess access)
: this(name, 0, null, access)
{ }
public void Clear()
{
int status;
NtStatus status;
if ((status = Win32.NtClearEvent(this)) < 0)
if ((status = Win32.NtClearEvent(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
public int Pulse()
public EventBasicInformation GetBasicInformation()
{
int status;
int previousState;
if ((status = Win32.NtPulseEvent(this, out previousState)) < 0)
Win32.ThrowLastError(status);
return previousState;
}
public EventBasicInformation Query()
{
int status;
NtStatus status;
EventBasicInformation ebi;
int retLength;
if ((status = Win32.NtQueryEvent(this, EventInformationClass.EventBasicInformation,
out ebi, Marshal.SizeOf(typeof(EventBasicInformation)), out retLength)) < 0)
out ebi, Marshal.SizeOf(typeof(EventBasicInformation)), out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return ebi;
}
public int Reset()
public int Pulse()
{
int status;
NtStatus status;
int previousState;
if ((status = Win32.NtResetEvent(this, out previousState)) < 0)
if ((status = Win32.NtPulseEvent(this, out previousState)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return previousState;
}
public int Reset()
{
NtStatus status;
int previousState;
if ((status = Win32.NtResetEvent(this, out previousState)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return previousState;
@@ -104,10 +135,10 @@ namespace ProcessHacker.Native.Objects
public int Set()
{
int status;
NtStatus status;
int previousState;
if ((status = Win32.NtSetEvent(this, out previousState)) < 0)
if ((status = Win32.NtSetEvent(this, out previousState)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return previousState;
@@ -119,9 +150,9 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public void SetBoostPriority()
{
int status;
NtStatus status;
if ((status = Win32.NtSetEventBoostPriority(this)) < 0)
if ((status = Win32.NtSetEventBoostPriority(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
}
@@ -1,4 +1,26 @@
using System;
/*
* Process Hacker -
* event pair handle
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ProcessHacker.Native.Api;
@@ -18,7 +40,7 @@ namespace ProcessHacker.Native.Objects
/// <returns>A handle to an event pair.</returns>
public static EventPairHandle Create(EventPairAccess access)
{
return Create(access, null, null);
return Create(access, null, 0, null);
}
/// <summary>
@@ -33,15 +55,15 @@ namespace ProcessHacker.Native.Objects
/// The directory in which to place the event pair. This can be null.
/// </param>
/// <returns>A handle to an event pair.</returns>
public static EventPairHandle Create(EventPairAccess access, string name, DirectoryHandle rootDirectory)
public static EventPairHandle Create(EventPairAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateEventPair(out handle, access, ref oa)) < 0)
if ((status = Win32.NtCreateEventPair(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -64,15 +86,15 @@ namespace ProcessHacker.Native.Objects
/// you must specify a fully qualified name.</param>
/// <param name="rootDirectory">The directory object in which the event pair can be found.</param>
/// <param name="access">The desired access to the event pair.</param>
public EventPairHandle(string name, DirectoryHandle rootDirectory, EventPairAccess access)
public EventPairHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, EventPairAccess access)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtOpenEventPair(out handle, access, ref oa)) < 0)
if ((status = Win32.NtOpenEventPair(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -84,7 +106,7 @@ namespace ProcessHacker.Native.Objects
}
public EventPairHandle(string name, EventPairAccess access)
: this(name, null, access)
: this(name, 0, null, access)
{ }
/// <summary>
@@ -92,9 +114,9 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public void SetHigh()
{
int status;
NtStatus status;
if ((status = Win32.NtSetHighEventPair(this)) < 0)
if ((status = Win32.NtSetHighEventPair(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -103,9 +125,9 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public void SetHighWaitLow()
{
int status;
NtStatus status;
if ((status = Win32.NtSetHighWaitLowEventPair(this)) < 0)
if ((status = Win32.NtSetHighWaitLowEventPair(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -114,9 +136,9 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public void SetLow()
{
int status;
NtStatus status;
if ((status = Win32.NtSetLowEventPair(this)) < 0)
if ((status = Win32.NtSetLowEventPair(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -125,9 +147,9 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public void SetLowWaitHigh()
{
int status;
NtStatus status;
if ((status = Win32.NtSetLowWaitHighEventPair(this)) < 0)
if ((status = Win32.NtSetLowWaitHighEventPair(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -136,9 +158,9 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public void WaitHigh()
{
int status;
NtStatus status;
if ((status = Win32.NtWaitHighEventPair(this)) < 0)
if ((status = Win32.NtWaitHighEventPair(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -147,9 +169,9 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public void WaitLow()
{
int status;
NtStatus status;
if ((status = Win32.NtWaitLowEventPair(this)) < 0)
if ((status = Win32.NtWaitLowEventPair(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
}
@@ -19,7 +19,8 @@
* You should have received a copy of the GNU General Public License
* along with Process Hacker. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.Objects
@@ -29,7 +30,11 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public interface ISynchronizable
{
WaitResult Wait();
WaitResult Wait(uint timeout);
IntPtr Handle { get; }
NtStatus SignalAndWait(ISynchronizable waitObject, bool alertable, long timeout);
NtStatus Wait();
NtStatus Wait(long timeout);
NtStatus Wait(bool alertable, long timeout);
}
}
@@ -180,110 +180,4 @@ namespace ProcessHacker.Native.Objects
Win32.ThrowLastError();
}
}
[Flags]
public enum JobObjectInformationClass : int
{
JobObjectBasicAccountingInformation = 1,
JobObjectBasicLimitInformation,
JobObjectBasicProcessIdList,
JobObjectBasicUIRestrictions,
JobObjectSecurityLimitInformation,
JobObjectEndOfJobTimeInformation,
JobObjectAssociateCompletionPortInformation,
JobObjectBasicAndIoAccountingInformation,
JobObjectExtendedLimitInformation,
JobObjectJobSetInformation
}
[Flags]
public enum JobObjectLimitFlags : uint
{
WorkingSet = 0x1,
ProcessTime = 0x2,
JobTime = 0x4,
ActiveProcess = 0x8,
Affinity = 0x10,
PriorityClass = 0x20,
PreserveJobTime = 0x40,
SchedulingClass = 0x80,
ProcessMemory = 0x100,
JobMemory = 0x200,
DieOnUnhandledException = 0x400,
BreakawayOk = 0x800,
SilentBreakawayOk = 0x1000,
KillOnJobClose = 0x2000,
}
[Flags]
public enum JobObjectBasicUiRestrictions : uint
{
Handles = 0x1,
ReadClipboard = 0x2,
WriteClipboard = 0x4,
SystemParameters = 0x8,
DisplaySettings = 0x10,
GlobalAtoms = 0x20,
Desktop = 0x40,
ExitWindows = 0x80
}
[StructLayout(LayoutKind.Sequential)]
public struct JobObjectBasicAccountingInformation
{
public long TotalUserTime;
public long TotalKernelTime;
public long ThisPeriodTotalUserTime;
public long ThisPeriodTotalKernelTime;
public int TotalPageFaultCount;
public int TotalProcesses;
public int ActiveProcesses;
public int TotalTerminatedProcesses;
}
[StructLayout(LayoutKind.Sequential)]
public struct JobObjectBasicAndIoAccountingInformation
{
public JobObjectBasicAccountingInformation BasicInfo;
public IoCounters IoInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct JobObjectBasicLimitInformation
{
public long PerProcessUserTimeLimit;
public long PerJobUserTimeLimit;
public JobObjectLimitFlags LimitFlags;
public int MinimumWorkingSetSize;
public int MaximumWorkingSetSize;
public int ActiveProcessLimit;
public int Affinity;
public int PriorityClass;
public int SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
public struct JobObjectBasicProcessIdList
{
public int NumberOfAssignedProcesses;
public int NumberOfProcessIdsInList;
/* an array follows */
}
[StructLayout(LayoutKind.Sequential)]
public struct JobObjectEndOfJobTimeInformation
{
public int EndOfJobTimeAction; // 0: Terminate, 1: Post
}
[StructLayout(LayoutKind.Sequential)]
public struct JobObjectExtendedLimitInformation
{
public JobObjectBasicLimitInformation BasicLimitInformation;
public IoCounters IoInfo;
public int ProcessMemoryLimit;
public int JobMemoryLimit;
public int PeakProcessMemoryUsed;
public int PeakJobMemoryUsed;
}
}
@@ -1,4 +1,26 @@
using System;
/*
* Process Hacker -
* keyed event handle
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ProcessHacker.Native.Api;
@@ -8,8 +30,106 @@ namespace ProcessHacker.Native.Objects
{
public class KeyedEventHandle : Win32Handle<KeyedEventAccess>
{
public static KeyedEventHandle Create(KeyedEventAccess access)
{
return Create(access, null);
}
public static KeyedEventHandle Create(KeyedEventAccess access, string name)
{
return Create(access, name, 0, null);
}
public static KeyedEventHandle Create(KeyedEventAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory)
{
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateKeyedEvent(out handle, access, ref oa, 0)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
{
oa.Dispose();
}
return new KeyedEventHandle(handle, true);
}
private KeyedEventHandle(IntPtr handle, bool owned)
: base(handle, owned)
{ }
public KeyedEventHandle(string name, DirectoryHandle rootDirectory, ObjectFlags objectFlags, KeyedEventAccess access)
{
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtOpenKeyedEvent(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
{
oa.Dispose();
}
this.Handle = handle;
}
public KeyedEventHandle(string name, KeyedEventAccess access)
: this(name, null, 0, access)
{ }
public void Release(IntPtr key, bool alertable, long timeout)
{
NtStatus status;
if ((status = Win32.NtReleaseKeyedEvent(this, key, alertable, ref timeout)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
public void Release(int key, bool alertable, long timeout)
{
this.Release(new IntPtr(key), alertable, timeout);
}
public void Release(int key, long timeout)
{
this.Release(key, false, timeout);
}
public void Release(int key)
{
this.Release(key, -1);
}
public void Wait(IntPtr key, bool alertable, long timeout)
{
NtStatus status;
if ((status = Win32.NtWaitForKeyedEvent(this, key, alertable, ref timeout)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
public void Wait(int key, bool alertable, long timeout)
{
this.Wait(new IntPtr(key), alertable, timeout);
}
public void Wait(int key, long timeout)
{
this.Wait(key, false, timeout);
}
public void Wait(int key)
{
this.Wait(key, -1);
}
}
}
@@ -37,11 +37,11 @@ namespace ProcessHacker.Native.Objects
/// <param name="access">The desired access to the policy.</param>
public LsaPolicyHandle(PolicyAccess access)
{
int status;
NtStatus status;
ObjectAttributes attributes = new ObjectAttributes();
IntPtr handle = IntPtr.Zero;
if ((status = Win32.LsaOpenPolicy(IntPtr.Zero, ref attributes, access, ref handle)) < 0)
if ((status = Win32.LsaOpenPolicy(IntPtr.Zero, ref attributes, access, ref handle)) >= NtStatus.Error)
Win32.ThrowLastError(status);
this.Handle = handle;
@@ -1,4 +1,26 @@
using System;
/*
* Process Hacker -
* mutant handle
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ProcessHacker.Native.Api;
@@ -16,18 +38,18 @@ namespace ProcessHacker.Native.Objects
public static MutantHandle Create(MutantAccess access, string name, bool initialOwner)
{
return Create(access, name, null, initialOwner);
return Create(access, name, 0, null, initialOwner);
}
public static MutantHandle Create(MutantAccess access, string name, DirectoryHandle rootDirectory, bool initialOwner)
public static MutantHandle Create(MutantAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, bool initialOwner)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateMutant(out handle, access, ref oa, initialOwner)) < 0)
if ((status = Win32.NtCreateMutant(out handle, access, ref oa, initialOwner)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -38,19 +60,24 @@ namespace ProcessHacker.Native.Objects
return new MutantHandle(handle, true);
}
public static MutantHandle FromHandle(IntPtr handle)
{
return new MutantHandle(handle, false);
}
private MutantHandle(IntPtr handle, bool owned)
: base(handle, owned)
{ }
public MutantHandle(string name, DirectoryHandle rootDirectory, MutantAccess access)
public MutantHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, MutantAccess access)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtOpenMutant(out handle, access, ref oa)) < 0)
if ((status = Win32.NtOpenMutant(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -62,17 +89,17 @@ namespace ProcessHacker.Native.Objects
}
public MutantHandle(string name, MutantAccess access)
: this(name, null, access)
: this(name, 0, null, access)
{ }
public MutantBasicInformation Query()
public MutantBasicInformation GetBasicInformation()
{
int status;
NtStatus status;
MutantBasicInformation mbi;
int retLength;
if ((status = Win32.NtQueryMutant(this, MutantInformationClass.MutantBasicInformation,
out mbi, Marshal.SizeOf(typeof(MutantBasicInformation)), out retLength)) < 0)
out mbi, Marshal.SizeOf(typeof(MutantBasicInformation)), out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return mbi;
@@ -80,10 +107,10 @@ namespace ProcessHacker.Native.Objects
public int Release()
{
int status;
NtStatus status;
int previousCount;
if ((status = Win32.NtReleaseMutant(this, out previousCount)) < 0)
if ((status = Win32.NtReleaseMutant(this, out previousCount)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return previousCount;
@@ -0,0 +1,101 @@
/*
* Process Hacker -
* port handle
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
namespace ProcessHacker.Native.Objects
{
public class PortHandle : Win32Handle<PortAccess>
{
public static PortHandle Create(
string name,
ObjectFlags objectFlags,
DirectoryHandle rootDirectory,
int maxConnectionInfoLength,
int maxMessageLength,
int maxPoolUsage
)
{
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreatePort(
out handle,
ref oa,
maxConnectionInfoLength,
maxMessageLength,
maxPoolUsage
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
{
oa.Dispose();
}
return new PortHandle(handle, true);
}
public static PortHandle CreateWaitable(
string name,
ObjectFlags objectFlags,
DirectoryHandle rootDirectory,
int maxConnectionInfoLength,
int maxMessageLength,
int maxPoolUsage
)
{
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateWaitablePort(
out handle,
ref oa,
maxConnectionInfoLength,
maxMessageLength,
maxPoolUsage
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
{
oa.Dispose();
}
return new PortHandle(handle, true);
}
private PortHandle(IntPtr handle, bool owned)
: base(handle, owned)
{ }
}
}
@@ -55,41 +55,71 @@ namespace ProcessHacker.Native.Objects
/// <returns>Return true to continue enumerating; return false to stop.</returns>
public delegate bool EnumModulesDelegate(ProcessModule module);
public static ProcessHandle Create(SectionHandle sectionHandle, ProcessAccess access, ProcessHandle parent, bool inheritHandles)
{
int status;
IntPtr process;
if ((status = Win32.NtCreateProcess(
out process,
access,
IntPtr.Zero,
parent,
inheritHandles,
sectionHandle,
IntPtr.Zero,
IntPtr.Zero)) < 0)
Win32.ThrowLastError(status);
return new ProcessHandle(process, true);
}
public static ProcessHandle Create(string fileName, ProcessAccess access, bool inheritHandles)
public static ProcessHandle Create(ProcessAccess access, string fileName, bool inheritHandles)
{
using (var fhandle = new FileHandle(
fileName,
(FileAccess)StandardRights.Synchronize | FileAccess.Execute | FileAccess.ReadData,
FileShareMode.Delete | FileShareMode.Read, FileCreationDisposition.OpenAlways))
{
using (var shandle = new SectionHandle(
SectionAccess.All, fhandle,
SectionAttributes.Image, MemoryProtection.Execute))
using (var shandle =
SectionHandle.Create(
SectionAccess.All,
SectionAttributes.Image,
MemoryProtection.Execute,
fhandle))
{
return Create(shandle, access, ProcessHandle.GetCurrent(), inheritHandles);
return Create(access, ProcessHandle.GetCurrent(), inheritHandles, shandle);
}
}
}
public static ProcessHandle Create(
ProcessAccess access,
ProcessHandle parentProcess,
bool inheritHandles,
SectionHandle sectionHandle)
{
return Create(access, null, 0, null, parentProcess, inheritHandles, sectionHandle, null);
}
public static ProcessHandle Create(
ProcessAccess access,
string name,
ObjectFlags objectFlags,
DirectoryHandle rootDirectory,
ProcessHandle parentProcess,
bool inheritHandles,
SectionHandle sectionHandle,
DebugObjectHandle debugPort
)
{
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateProcess(
out handle,
access,
ref oa,
parentProcess != null ? parentProcess : IntPtr.Zero,
inheritHandles,
sectionHandle != null ? sectionHandle : IntPtr.Zero,
debugPort != null ? debugPort : IntPtr.Zero,
IntPtr.Zero
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
{
oa.Dispose();
}
return new ProcessHandle(handle, true);
}
/// <summary>
/// Creates a process handle using an existing handle.
/// The handle will not be closed automatically.
@@ -114,14 +144,6 @@ namespace ProcessHacker.Native.Objects
: base(handle, owned)
{ }
/// <summary>
/// Creates a new process handle.
/// </summary>
/// <param name="PID">The ID of the process to open.</param>
public ProcessHandle(int pid)
: this(pid, ProcessAccess.All)
{ }
/// <summary>
/// Creates a new process handle.
/// </summary>
@@ -156,6 +178,66 @@ namespace ProcessHacker.Native.Objects
Win32.ThrowLastError();
}
/// <summary>
/// Creates a new process handle.
/// </summary>
/// <param name="PID">The ID of the process to open.</param>
public ProcessHandle(int pid)
: this(pid, ProcessAccess.All)
{ }
public ProcessHandle(
string name,
ObjectFlags objectFlags,
DirectoryHandle rootDirectory,
ClientId clientId,
ProcessAccess access
)
{
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
// NtOpenProcess fails when both a client ID and a name is specified.
if (clientId.ProcessId == 0 && clientId.ThreadId == 0)
{
if ((status = Win32.NtOpenProcess(
out handle,
access,
ref oa,
IntPtr.Zero
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
else
{
if ((status = Win32.NtOpenProcess(
out handle,
access,
ref oa,
ref clientId
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
}
finally
{
oa.Dispose();
}
this.Handle = handle;
}
public ProcessHandle(string name, ProcessAccess access)
: this(name, 0, null, new ClientId(), access)
{ }
public ProcessHandle(ClientId clientId, ProcessAccess access)
: this(null, 0, null, clientId, access)
{ }
/// <summary>
/// Allocates a memory region in the process' virtual memory.
/// </summary>
@@ -241,9 +323,9 @@ namespace ProcessHacker.Native.Objects
/// <param name="debugObjectHandle">A handle to a debug object.</param>
public void Debug(DebugObjectHandle debugObjectHandle)
{
int status;
NtStatus status;
if ((status = Win32.NtDebugActiveProcess(this, debugObjectHandle)) < 0)
if ((status = Win32.NtDebugActiveProcess(this, debugObjectHandle)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -415,12 +497,12 @@ namespace ProcessHacker.Native.Objects
/// <returns>A PROCESS_BASIC_INFORMATION structure.</returns>
public ProcessBasicInformation GetBasicInformation()
{
int status;
NtStatus status;
ProcessBasicInformation pbi;
int retLen;
if ((status = Win32.NtQueryInformationProcess(this, ProcessInformationClass.ProcessBasicInformation,
out pbi, Marshal.SizeOf(typeof(ProcessBasicInformation)), out retLen)) < 0)
out pbi, Marshal.SizeOf(typeof(ProcessBasicInformation)), out retLen)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return pbi;
@@ -471,12 +553,12 @@ namespace ProcessHacker.Native.Objects
/// <returns>A DEPStatus enum.</returns>
public DepStatus GetDepStatus()
{
int status;
NtStatus status;
MemExecuteOptions options;
int retLength;
if ((status = Win32.NtQueryInformationProcess(this, ProcessInformationClass.ProcessExecuteFlags,
out options, 4, out retLength)) < 0)
out options, 4, out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
DepStatus depStatus = 0;
@@ -646,12 +728,12 @@ namespace ProcessHacker.Native.Objects
private int GetInformationInt32(ProcessInformationClass infoClass)
{
int status;
NtStatus status;
int value;
int retLength;
if ((status = Win32.NtQueryInformationProcess(
this, infoClass, out value, sizeof(int), out retLength)) < 0)
this, infoClass, out value, sizeof(int), out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return value;
@@ -738,7 +820,7 @@ namespace ProcessHacker.Native.Objects
/// <returns>A file name, in device/native format.</returns>
public string GetNativeImageFileName()
{
int status;
NtStatus status;
int retLen;
Win32.NtQueryInformationProcess(this, ProcessInformationClass.ProcessImageFileName,
@@ -747,7 +829,7 @@ namespace ProcessHacker.Native.Objects
using (MemoryAlloc data = new MemoryAlloc(retLen))
{
if ((status = Win32.NtQueryInformationProcess(this, ProcessInformationClass.ProcessImageFileName,
data, retLen, out retLen)) < 0)
data, retLen, out retLen)) >= NtStatus.Error)
Win32.ThrowLastError(status);
UnicodeString str = data.ReadStruct<UnicodeString>();
@@ -763,7 +845,7 @@ namespace ProcessHacker.Native.Objects
/// <returns>A process handle.</returns>
public ProcessHandle GetNextProcess(ProcessAccess access)
{
int status;
NtStatus status;
IntPtr handle;
if ((status = Win32.NtGetNextProcess(
@@ -772,7 +854,7 @@ namespace ProcessHacker.Native.Objects
0,
0,
out handle
)) < 0)
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return new ProcessHandle(handle, true);
@@ -786,7 +868,7 @@ namespace ProcessHacker.Native.Objects
/// <returns>A thread handle.</returns>
public ThreadHandle GetNextThread(ThreadHandle threadHandle, ThreadAccess access)
{
int status;
NtStatus status;
IntPtr handle;
if ((status = Win32.NtGetNextThread(
@@ -796,7 +878,7 @@ namespace ProcessHacker.Native.Objects
0,
0,
out handle
)) < 0)
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return new ThreadHandle(handle, true);
@@ -1084,9 +1166,9 @@ namespace ProcessHacker.Native.Objects
/// <param name="debugObjectHandle">The debug object which was used to debug the process.</param>
public void RemoveDebug(DebugObjectHandle debugObjectHandle)
{
int status;
NtStatus status;
if ((status = Win32.NtRemoveProcessDebug(this, debugObjectHandle)) < 0)
if ((status = Win32.NtRemoveProcessDebug(this, debugObjectHandle)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -1101,13 +1183,27 @@ namespace ProcessHacker.Native.Objects
}
else
{
int status;
NtStatus status;
if ((status = Win32.NtResumeProcess(this)) < 0)
if ((status = Win32.NtResumeProcess(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
}
public void SetCritical(bool critical)
{
this.SetInformationInt32(ProcessInformationClass.ProcessBreakOnTermination, critical ? 1 : 0);
}
private void SetInformationInt32(ProcessInformationClass infoClass, int value)
{
NtStatus status;
if ((status = Win32.NtSetInformationProcess(
this, infoClass, ref value, sizeof(int))) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
public unsafe void SetModuleReferenceCount(IntPtr baseAddress, ushort count)
{
byte* buffer = stackalloc byte[IntPtr.Size];
@@ -1169,9 +1265,9 @@ namespace ProcessHacker.Native.Objects
}
else
{
int status;
NtStatus status;
if ((status = Win32.NtSuspendProcess(this)) < 0)
if ((status = Win32.NtSuspendProcess(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
}
@@ -0,0 +1,35 @@
/*
* Process Hacker -
* profile handle
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
namespace ProcessHacker.Native.Objects
{
public class ProfileHandle : Win32Handle<ProfileAccess>
{
// TODO: Implement basics
}
}
@@ -25,31 +25,195 @@ using System.Collections.Generic;
using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
using ProcessHacker.Native.Memory;
using System.Runtime.InteropServices;
namespace ProcessHacker.Native.Objects
{
public class SectionHandle : Win32Handle<SectionAccess>
{
public SectionHandle(SectionAccess access, FileHandle fileHandle, SectionAttributes sectionAttributes, MemoryProtection pageAttributes)
public static SectionHandle Create(
SectionAccess access,
SectionAttributes sectionAttributes,
MemoryProtection pageAttributes,
FileHandle fileHandle
)
{
int status;
IntPtr section;
LargeInteger largeInteger = new LargeInteger();
if ((status = Win32.NtCreateSection(
out section,
access,
IntPtr.Zero,
ref largeInteger,
(int)pageAttributes,
(int)sectionAttributes,
fileHandle)) < 0)
Win32.ThrowLastError(status);
return Create(access, null, 0, sectionAttributes, pageAttributes, fileHandle);
}
this.Handle = section;
public static SectionHandle Create(
SectionAccess access,
string name,
long maximumSize,
SectionAttributes sectionAttributes,
MemoryProtection pageAttributes,
FileHandle fileHandle
)
{
return Create(access, name, 0, null, maximumSize, sectionAttributes, pageAttributes, fileHandle);
}
public static SectionHandle Create(
SectionAccess access,
string name,
ObjectFlags objectFlags,
DirectoryHandle rootDirectory,
long maximumSize,
SectionAttributes sectionAttributes,
MemoryProtection pageAttributes,
FileHandle fileHandle
)
{
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateSection(
out handle,
access,
ref oa,
ref maximumSize,
(int)pageAttributes,
(int)sectionAttributes,
fileHandle)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
{
oa.Dispose();
}
return new SectionHandle(handle, true);
}
public static SectionHandle FromHandle(IntPtr handle)
{
return new SectionHandle(handle, false);
}
private SectionHandle(IntPtr handle, bool owned)
: base(handle, owned)
{ }
public SectionHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, SectionAccess access)
{
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtOpenSection(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
{
oa.Dispose();
}
this.Handle = handle;
}
public SectionHandle(string name, SectionAccess access)
: this(name, 0, null, access)
{ }
public long Extend(long newSize)
{
NtStatus status;
if ((status = Win32.NtExtendSection(this, ref newSize)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return newSize;
}
public SectionBasicInformation GetBasicInformation()
{
NtStatus status;
SectionBasicInformation sbi;
IntPtr retLength;
if ((status = Win32.NtQuerySection(this, SectionInformationClass.SectionBasicInformation,
out sbi, new IntPtr(Marshal.SizeOf(typeof(SectionBasicInformation))), out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return sbi;
}
public SectionImageInformation GetImageInformation()
{
NtStatus status;
SectionImageInformation sii;
IntPtr retLength;
if ((status = Win32.NtQuerySection(this, SectionInformationClass.SectionImageInformation,
out sii, new IntPtr(Marshal.SizeOf(typeof(SectionImageInformation))), out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return sii;
}
public SectionView MapView(
ProcessHandle processHandle,
IntPtr baseAddress,
IntPtr commitSize,
long sectionOffset,
IntPtr viewSize,
SectionInherit inheritDisposition,
MemoryFlags allocationType,
MemoryProtection protection
)
{
NtStatus status;
if ((status = Win32.NtMapViewOfSection(
this,
processHandle,
ref baseAddress,
IntPtr.Zero,
commitSize,
ref sectionOffset,
ref viewSize,
inheritDisposition,
allocationType,
protection
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return new SectionView(baseAddress, commitSize);
}
public SectionView MapView(
ProcessHandle processHandle,
IntPtr baseAddress,
IntPtr size,
MemoryProtection protection
)
{
return this.MapView(
processHandle,
baseAddress,
size,
0,
size,
SectionInherit.ViewShare,
0,
protection
);
}
public SectionView MapView(IntPtr baseAddress, IntPtr size, MemoryProtection protection)
{
return this.MapView(ProcessHandle.GetCurrent(), baseAddress, size, protection);
}
public SectionView MapView(int size, MemoryProtection protection)
{
return this.MapView(IntPtr.Zero, new IntPtr(size), protection);
}
}
}
@@ -1,4 +1,26 @@
using System;
/*
* Process Hacker -
* semaphore handle
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -14,19 +36,19 @@ namespace ProcessHacker.Native.Objects
public static SemaphoreHandle Create(SemaphoreAccess access, string name, int initialCount, int maximumCount)
{
return Create(access, name, null, initialCount, maximumCount);
return Create(access, name, 0, null, initialCount, maximumCount);
}
public static SemaphoreHandle Create(SemaphoreAccess access, string name, DirectoryHandle rootDirectory, int initialCount, int maximumCount)
public static SemaphoreHandle Create(SemaphoreAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, int initialCount, int maximumCount)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateSemaphore(out handle, access, ref oa,
initialCount, maximumCount)) < 0)
if ((status = Win32.NtCreateSemaphore(out handle, access, ref oa,
initialCount, maximumCount)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -37,19 +59,24 @@ namespace ProcessHacker.Native.Objects
return new SemaphoreHandle(handle, true);
}
public static SemaphoreHandle FromHandle(IntPtr handle)
{
return new SemaphoreHandle(handle, false);
}
private SemaphoreHandle(IntPtr handle, bool owned)
: base(handle, owned)
{ }
public SemaphoreHandle(string name, DirectoryHandle rootDirectory, SemaphoreAccess access)
public SemaphoreHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, SemaphoreAccess access)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtOpenSemaphore(out handle, access, ref oa)) < 0)
if ((status = Win32.NtOpenSemaphore(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -61,17 +88,17 @@ namespace ProcessHacker.Native.Objects
}
public SemaphoreHandle(string name, SemaphoreAccess access)
: this(name, null, access)
: this(name, 0, null, access)
{ }
public SemaphoreBasicInformation Query()
public SemaphoreBasicInformation GetBasicInformation()
{
int status;
NtStatus status;
SemaphoreBasicInformation sbi;
int retLength;
if ((status = Win32.NtQuerySemaphore(this, SemaphoreInformationClass.SemaphoreBasicInformation,
out sbi, Marshal.SizeOf(typeof(SemaphoreBasicInformation)), out retLength)) < 0)
out sbi, Marshal.SizeOf(typeof(SemaphoreBasicInformation)), out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return sbi;
@@ -79,10 +106,10 @@ namespace ProcessHacker.Native.Objects
public int Release(int count)
{
int status;
NtStatus status;
int previousCount;
if ((status = Win32.NtReleaseSemaphore(this, count, out previousCount)) < 0)
if ((status = Win32.NtReleaseSemaphore(this, count, out previousCount)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return previousCount;
@@ -1,4 +1,26 @@
using System;
/*
* Process Hacker -
* symbolic link handle
*
* Copyright (C) 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 <http://www.gnu.org/licenses/>.
*/
using System;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -8,20 +30,20 @@ namespace ProcessHacker.Native.Objects
{
public static SymbolicLinkHandle Create(SymbolicLinkAccess access, string name, string linkTarget)
{
return Create(access, name, null, linkTarget);
return Create(access, name, 0, null, linkTarget);
}
public static SymbolicLinkHandle Create(SymbolicLinkAccess access, string name, DirectoryHandle rootDirectory, string linkTarget)
public static SymbolicLinkHandle Create(SymbolicLinkAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, string linkTarget)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
UnicodeString linkTargetString = UnicodeString.Create(linkTarget);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
UnicodeString linkTargetString = new UnicodeString(linkTarget);
IntPtr handle;
try
{
if ((status = Win32.NtCreateSymbolicLinkObject(out handle, access,
ref oa, ref linkTargetString)) < 0)
ref oa, ref linkTargetString)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -37,15 +59,15 @@ namespace ProcessHacker.Native.Objects
: base(handle, owned)
{ }
public SymbolicLinkHandle(string name, DirectoryHandle rootDirectory, SymbolicLinkAccess access)
public SymbolicLinkHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, SymbolicLinkAccess access)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtOpenSymbolicLinkObject(out handle, access, ref oa)) < 0)
if ((status = Win32.NtOpenSymbolicLinkObject(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -57,12 +79,12 @@ namespace ProcessHacker.Native.Objects
}
public SymbolicLinkHandle(string name, SymbolicLinkAccess access)
: this(name, null, access)
: this(name, 0, null, access)
{ }
public string GetTarget()
{
int status;
NtStatus status;
int retLength;
UnicodeString str = new UnicodeString();
@@ -72,14 +94,14 @@ namespace ProcessHacker.Native.Objects
str.MaximumLength = (ushort)buffer.Size;
str.Buffer = buffer;
if ((status = Win32.NtQuerySymbolicLinkObject(this, ref str, out retLength)) < 0)
if ((status = Win32.NtQuerySymbolicLinkObject(this, ref str, out retLength)) >= NtStatus.Error)
{
buffer.Resize(retLength);
str.MaximumLength = (ushort)retLength;
str.Buffer = buffer;
}
if ((status = Win32.NtQuerySymbolicLinkObject(this, ref str, out retLength)) < 0)
if ((status = Win32.NtQuerySymbolicLinkObject(this, ref str, out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return str.Read();
@@ -33,6 +33,44 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public class ThreadHandle : Win32Handle<ThreadAccess>, IWithToken
{
public static ThreadHandle Create(
ThreadAccess access,
string name,
ObjectFlags objectFlags,
DirectoryHandle rootDirectory,
ProcessHandle processHandle,
out ClientId clientId,
ref Context threadContext,
ref InitialTeb initialTeb,
bool createSuspended
)
{
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateThread(
out handle,
access,
ref oa,
processHandle,
out clientId,
ref threadContext,
ref initialTeb,
createSuspended
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
{
oa.Dispose();
}
return new ThreadHandle(handle, true);
}
/// <summary>
/// Creates a thread handle using an existing handle.
/// The handle will not be closed automatically.
@@ -53,6 +91,22 @@ namespace ProcessHacker.Native.Objects
return new ThreadHandle(new IntPtr(-2), false);
}
public static void RegisterTerminationPort(PortHandle portHandle)
{
NtStatus status;
if ((status = Win32.NtRegisterThreadTerminatePort(portHandle)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
public static void TestAlert()
{
NtStatus status;
if ((status = Win32.NtTestAlert()) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
internal ThreadHandle(IntPtr handle, bool owned)
: base(handle, owned)
{ }
@@ -95,14 +149,61 @@ namespace ProcessHacker.Native.Objects
Win32.ThrowLastError();
}
public ThreadHandle(
string name,
ObjectFlags objectFlags,
DirectoryHandle rootDirectory,
ClientId clientId,
ThreadAccess access
)
{
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
if (clientId.ProcessId == 0 && clientId.ThreadId == 0)
{
if ((status = Win32.NtOpenThread(
out handle,
access,
ref oa,
IntPtr.Zero
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
else
{
if ((status = Win32.NtOpenThread(
out handle,
access,
ref oa,
ref clientId
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
}
finally
{
oa.Dispose();
}
this.Handle = handle;
}
public ThreadHandle(string name, ThreadAccess access)
: this(name, 0, null, new ClientId(), access)
{ }
/// <summary>
/// Puts the thread in an alerted state.
/// </summary>
public void Alert()
{
int status;
NtStatus status;
if ((status = Win32.NtAlertThread(this)) < 0)
if ((status = Win32.NtAlertThread(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -111,10 +212,10 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public int AlertResume()
{
int status;
NtStatus status;
int suspendCount;
if ((status = Win32.NtAlertResumeThread(this, out suspendCount)) < 0)
if ((status = Win32.NtAlertResumeThread(this, out suspendCount)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return suspendCount;
@@ -134,12 +235,12 @@ namespace ProcessHacker.Native.Objects
/// <returns>A THREAD_BASIC_INFORMATION structure.</returns>
public ThreadBasicInformation GetBasicInformation()
{
int status;
NtStatus status;
ThreadBasicInformation basicInfo = new ThreadBasicInformation();
int retLen;
if ((status = Win32.NtQueryInformationThread(this, ThreadInformationClass.ThreadBasicInformation,
ref basicInfo, Marshal.SizeOf(basicInfo), out retLen)) < 0)
ref basicInfo, Marshal.SizeOf(basicInfo), out retLen)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return basicInfo;
@@ -206,12 +307,12 @@ namespace ProcessHacker.Native.Objects
private int GetInformationInt32(ThreadInformationClass infoClass)
{
int status;
NtStatus status;
int value;
int retLength;
if ((status = Win32.NtQueryInformationThread(
this, infoClass, out value, sizeof(int), out retLength)) < 0)
this, infoClass, out value, sizeof(int), out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return value;
@@ -243,12 +344,12 @@ namespace ProcessHacker.Native.Objects
/// <returns>A system call number.</returns>
public unsafe int GetLastSystemCall(out int firstArgument)
{
int status;
NtStatus status;
int* data = stackalloc int[2];
int retLength;
if ((status = Win32.NtQueryInformationThread(
this, ThreadInformationClass.ThreadLastSystemCall, data, sizeof(int) * 2, out retLength)) < 0)
this, ThreadInformationClass.ThreadLastSystemCall, data, sizeof(int) * 2, out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
firstArgument = data[0];
@@ -294,6 +395,24 @@ namespace ProcessHacker.Native.Objects
return this.GetInformationInt32(ThreadInformationClass.ThreadQuerySetWin32StartAddress);
}
public void Impersonate(ThreadHandle clientThreadHandle, SecurityImpersonationLevel impersonationLevel)
{
NtStatus status;
SecurityQualityOfService securityQos =
new SecurityQualityOfService(impersonationLevel, false, false);
if ((status = Win32.NtImpersonateThread(this, clientThreadHandle, ref securityQos)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
public void ImpersonateAnonymous()
{
NtStatus status;
if ((status = Win32.NtImpersonateAnonymousToken(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
/// <summary>
/// Gets whether the system will break (crash) upon the thread terminating.
/// </summary>
@@ -348,7 +467,7 @@ namespace ProcessHacker.Native.Objects
public void QueueApc(IntPtr address, IntPtr param1, IntPtr param2, IntPtr param3)
{
int status;
NtStatus status;
if ((status = Win32.NtQueueApcThread(
this,
@@ -356,7 +475,7 @@ namespace ProcessHacker.Native.Objects
param1,
param2,
param3
)) < 0)
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -375,6 +494,20 @@ namespace ProcessHacker.Native.Objects
if (!Win32.SetThreadContext(this, ref context))
Win32.ThrowLastError();
}
}
public void SetCritical(bool critical)
{
this.SetInformationInt32(ThreadInformationClass.ThreadBreakOnTermination, critical ? 1 : 0);
}
private void SetInformationInt32(ThreadInformationClass infoClass, int value)
{
NtStatus status;
if ((status = Win32.NtSetInformationThread(
this, infoClass, ref value, sizeof(int))) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
/// <summary>
@@ -392,10 +525,10 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public int Suspend()
{
int status;
NtStatus status;
int suspendCount;
if ((status = Win32.NtSuspendThread(this, out suspendCount)) < 0)
if ((status = Win32.NtSuspendThread(this, out suspendCount)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return suspendCount;
@@ -406,10 +539,10 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public int Resume()
{
int status;
NtStatus status;
int suspendCount;
if ((status = Win32.NtResumeThread(this, out suspendCount)) < 0)
if ((status = Win32.NtResumeThread(this, out suspendCount)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return suspendCount;
@@ -9,8 +9,6 @@ namespace ProcessHacker.Native.Objects
{
public class TimerHandle : Win32Handle<TimerAccess>
{
public delegate void TimerApcRoutine(IntPtr context, int lowValue, int highValue);
public static TimerHandle Create(TimerAccess access, TimerType type)
{
return Create(access, null, type);
@@ -23,13 +21,13 @@ namespace ProcessHacker.Native.Objects
public static TimerHandle Create(TimerAccess access, string name, DirectoryHandle rootDirectory, TimerType type)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, 0, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtCreateTimer(out handle, access, ref oa, type)) < 0)
if ((status = Win32.NtCreateTimer(out handle, access, ref oa, type)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -48,13 +46,13 @@ namespace ProcessHacker.Native.Objects
public TimerHandle(string name, DirectoryHandle rootDirectory, TimerAccess access)
{
int status;
ObjectAttributes oa = ObjectAttributes.Create(name, 0, rootDirectory);
NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, 0, rootDirectory);
IntPtr handle;
try
{
if ((status = Win32.NtOpenTimer(out handle, access, ref oa)) < 0)
if ((status = Win32.NtOpenTimer(out handle, access, ref oa)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -71,23 +69,23 @@ namespace ProcessHacker.Native.Objects
public bool Cancel()
{
int status;
NtStatus status;
bool currentState;
if ((status = Win32.NtCancelTimer(this, out currentState)) < 0)
if ((status = Win32.NtCancelTimer(this, out currentState)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return currentState;
}
public TimerBasicInformation Query()
public TimerBasicInformation GetBasicInformation()
{
int status;
NtStatus status;
TimerBasicInformation tbi;
int retLength;
if ((status = Win32.NtQueryTimer(this, TimerInformationClass.TimerBasicInformation,
out tbi, Marshal.SizeOf(typeof(TimerBasicInformation)), out retLength)) < 0)
out tbi, Marshal.SizeOf(typeof(TimerBasicInformation)), out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return tbi;
@@ -95,13 +93,13 @@ namespace ProcessHacker.Native.Objects
public bool Set(long dueTime, TimerApcRoutine routine, IntPtr context, bool resume, int period)
{
int status;
NtStatus status;
bool previousState;
_routine = routine;
if ((status = Win32.NtSetTimer(this, ref dueTime, routine, context,
resume, period, out previousState)) < 0)
resume, period, out previousState)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return previousState;
@@ -353,7 +353,7 @@ namespace ProcessHacker.Native.Objects
TokenUser user = data.ReadStruct<TokenUser>();
return new WindowsSid(user.User.SID);
return new WindowsSid(user.User.Sid);
}
}
@@ -31,6 +31,56 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public class Win32Handle : Win32Handle<int>
{
public static NtStatus WaitAll(ISynchronizable[] objects, bool alertable, long timeout)
{
return WaitForMultipleObjects(objects, WaitType.WaitAll, alertable, timeout);
}
public static NtStatus WaitAll(ISynchronizable[] objects, long timeout)
{
return WaitAll(objects, false, timeout);
}
public static NtStatus WaitAll(ISynchronizable[] objects)
{
return WaitAll(objects, -1);
}
public static NtStatus WaitAny(ISynchronizable[] objects, bool alertable, long timeout)
{
return WaitForMultipleObjects(objects, WaitType.WaitAny, alertable, timeout);
}
public static NtStatus WaitAny(ISynchronizable[] objects, long timeout)
{
return WaitAny(objects, false, timeout);
}
public static NtStatus WaitAny(ISynchronizable[] objects)
{
return WaitAny(objects, -1);
}
private static NtStatus WaitForMultipleObjects(ISynchronizable[] objects, WaitType waitType, bool alertable, long timeout)
{
NtStatus status;
IntPtr[] handles = new IntPtr[objects.Length];
for (int i = 0; i < objects.Length; i++)
handles[i] = objects[i].Handle;
if ((status = Win32.NtWaitForMultipleObjects(
handles.Length,
handles,
waitType,
alertable,
ref timeout
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return status;
}
/// <summary>
/// Creates a new, invalid handle. You must set the handle using the Handle property.
/// </summary>
@@ -206,7 +256,7 @@ namespace ProcessHacker.Native.Objects
/// <returns>A string.</returns>
public string GetHandleName()
{
int status;
NtStatus status;
int retLength;
status = Win32.NtQueryObject(this, ObjectInformationClass.ObjectNameInformation,
@@ -217,7 +267,7 @@ namespace ProcessHacker.Native.Objects
using (MemoryAlloc oniMem = new MemoryAlloc(retLength))
{
if ((status = Win32.NtQueryObject(this, ObjectInformationClass.ObjectNameInformation,
oniMem, oniMem.Size, out retLength)) < 0)
oniMem, oniMem.Size, out retLength)) >= NtStatus.Error)
Win32.ThrowLastError(status);
ObjectNameInformation oni = oniMem.ReadStruct<ObjectNameInformation>();
@@ -238,9 +288,9 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public void MakePermanent()
{
int status;
NtStatus status;
if ((status = Win32.NtMakePermanentObject(this)) < 0)
if ((status = Win32.NtMakePermanentObject(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -250,9 +300,9 @@ namespace ProcessHacker.Native.Objects
/// </summary>
public void MakeTemporary()
{
int status;
NtStatus status;
if ((status = Win32.NtMakeTemporaryObject(this)) < 0)
if ((status = Win32.NtMakeTemporaryObject(this)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
@@ -270,26 +320,36 @@ namespace ProcessHacker.Native.Objects
/// <summary>
/// Signals the object and waits for another.
/// </summary>
public int SignalAndWait(Win32Handle waitObject, bool alertable, long timeout)
public NtStatus SignalAndWait(ISynchronizable waitObject, bool alertable, long timeout)
{
return Win32.NtSignalAndWaitForSingleObject(this, waitObject, alertable, ref timeout);
return Win32.NtSignalAndWaitForSingleObject(this, waitObject.Handle, alertable, ref timeout);
}
/// <summary>
/// Waits for the object.
/// </summary>
public WaitResult Wait()
public NtStatus Wait()
{
return Win32.WaitForSingleObject(this, 0xffffffff);
return this.Wait(-1);
}
/// <summary>
/// Waits for the object with a timeout.
/// </summary>
/// <param name="Timeout">The timeout of the wait.</param>
public WaitResult Wait(uint timeout)
public NtStatus Wait(long timeout)
{
return Win32.WaitForSingleObject(this, timeout);
return this.Wait(false, timeout);
}
public NtStatus Wait(bool alertable, long timeout)
{
NtStatus status;
if ((status = Win32.NtWaitForSingleObject(
this,
alertable,
ref timeout
)) >= NtStatus.Error)
Win32.ThrowLastError(status);
return status;
}
/// <summary>
@@ -42,7 +42,11 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Api\NativeDefinitions.cs" />
<Compile Include="Api\NativeEnums.cs" />
<Compile Include="Api\NativeFunctions.cs" />
<Compile Include="Api\NativeStructs.cs" />
<Compile Include="Api\NtStatus.cs" />
<Compile Include="Cryptography.cs" />
<Compile Include="ExtensionAttribute.cs" />
<Compile Include="FileUtils.cs" />
@@ -50,6 +54,8 @@
<Compile Include="KProcessHacker.cs" />
<Compile Include="IntPtrExtensions.cs" />
<Compile Include="Memory\LocalMemoryAlloc.cs" />
<Compile Include="Memory\PebMemoryAlloc.cs" />
<Compile Include="Memory\SectionView.cs" />
<Compile Include="Objects\DebugObjectHandle.cs" />
<Compile Include="Objects\DesktopHandle.cs" />
<Compile Include="Objects\DirectoryHandle.cs" />
@@ -57,6 +63,8 @@
<Compile Include="Objects\EventPairHandle.cs" />
<Compile Include="Objects\KeyedEventHandle.cs" />
<Compile Include="Objects\MutantHandle.cs" />
<Compile Include="Objects\PortHandle.cs" />
<Compile Include="Objects\ProfileHandle.cs" />
<Compile Include="Objects\SemaphoreHandle.cs" />
<Compile Include="Objects\SymbolicLinkHandle.cs" />
<Compile Include="Objects\TimerHandle.cs" />
+11 -20
View File
@@ -48,19 +48,13 @@ namespace ProcessHacker.Native.Api
#region Consts
public const int AnysizeArray = 1;
public const int DontResolveDllReferences = 0x1;
public const int ErrorNoMoreItems = 259;
public const int MaximumSupportedExtension = 512;
public const int SecurityDescriptorMinLength = 20;
public const int SecurityDescriptorRevision = 1;
public const int SeeMaskInvokeIdList = 0xc;
public const uint ServiceNoChange = 0xffffffff;
public const uint ShgFiIcon = 0x100;
public const uint ShgFiLargeIcon = 0x0;
public const uint ShgFiSmallIcon = 0x1;
public const int SizeOf80387Registers = 80;
public const uint STATUS_INFO_LENGTH_MISMATCH = 0xc0000004;
#endregion
@@ -110,27 +104,24 @@ namespace ProcessHacker.Native.Api
/// </summary>
public static void ThrowLastError()
{
ThrowLastError(Marshal.GetLastWin32Error(), false);
ThrowLastError(Marshal.GetLastWin32Error());
}
public static void ThrowLastError(int status)
public static void ThrowLastError(NtStatus status)
{
ThrowLastError(status, true);
ThrowLastError(RtlNtStatusToDosError(status));
}
public static void ThrowLastError(int status, bool isNtStatus)
public static void ThrowLastError(int error)
{
if (isNtStatus)
status = RtlNtStatusToDosError(status);
// No error, but the caller requested us throw an exception so do it anyway.
if (status == 0)
if (error == 0)
{
throw new WindowsException();
}
else
{
var ex = new WindowsException(status);
var ex = new WindowsException(error);
throw ex;
}
@@ -145,7 +136,7 @@ namespace ProcessHacker.Native.Api
IntPtr sourceHandle,
int desiredAccess,
HandleFlags handleAttributes,
int options
DuplicateOptions options
)
{
IntPtr dummy;
@@ -168,7 +159,7 @@ namespace ProcessHacker.Native.Api
out IntPtr targetHandle,
int desiredAccess,
HandleFlags handleAttributes,
int options
DuplicateOptions options
)
{
if (KProcessHacker.Instance != null)
@@ -181,13 +172,13 @@ namespace ProcessHacker.Native.Api
targetProcessHandle.ToInt32(),
out target,
desiredAccess,
(int)handleAttributes,
handleAttributes,
options);
targetHandle = new IntPtr(target);
}
else
{
int status;
NtStatus status;
if ((status = NtDuplicateObject(
sourceProcessHandle,
@@ -196,7 +187,7 @@ namespace ProcessHacker.Native.Api
out targetHandle,
desiredAccess,
handleAttributes,
options)) < 0)
options)) >= NtStatus.Error)
ThrowLastError(status);
}
}
+31 -32
View File
@@ -124,17 +124,17 @@ namespace ProcessHacker.Native
using (MemoryAlloc data = new MemoryAlloc(0x1000))
{
int status;
NtStatus status;
// This is needed because NtQuerySystemInformation with SystemHandleInformation doesn't
// actually give a real return length when called with an insufficient buffer. This code
// tries repeatedly to call the function, doubling the buffer size each time it fails.
while ((uint)(status = Win32.NtQuerySystemInformation(
while ((status = Win32.NtQuerySystemInformation(
SystemInformationClass.SystemHandleInformation,
data,
data.Size,
out retLength)
) == Win32.STATUS_INFO_LENGTH_MISMATCH)
) == NtStatus.InfoLengthMismatch)
{
data.Resize(data.Size * 2);
@@ -291,7 +291,7 @@ namespace ProcessHacker.Native
using (MemoryAlloc data = new MemoryAlloc(0x4000))
{
int status;
NtStatus status;
int attempts = 0;
while (true)
@@ -299,7 +299,7 @@ namespace ProcessHacker.Native
attempts++;
if ((status = Win32.NtQuerySystemInformation(SystemInformationClass.SystemProcessInformation, data.Memory,
data.Size, out retLength)) < 0)
data.Size, out retLength)) >= NtStatus.Error)
{
if (attempts > 3)
Win32.ThrowLastError(status);
@@ -332,7 +332,7 @@ namespace ProcessHacker.Native
var thread = data.ReadStruct<SystemThreadInformation>(i +
Marshal.SizeOf(typeof(SystemProcessInformation)), j);
currentProcess.Threads.Add(thread.ClientId.UniqueThread, thread);
currentProcess.Threads.Add(thread.ClientId.ThreadId, thread);
}
}
@@ -354,7 +354,7 @@ namespace ProcessHacker.Native
using (MemoryAlloc data = new MemoryAlloc(0x4000))
{
int status;
NtStatus status;
int attempts = 0;
while (true)
@@ -362,7 +362,7 @@ namespace ProcessHacker.Native
attempts++;
if ((status = Win32.NtQuerySystemInformation(SystemInformationClass.SystemProcessInformation, data.Memory,
data.Size, out retLength)) < 0)
data.Size, out retLength)) >= NtStatus.Error)
{
if (attempts > 3)
Win32.ThrowLastError(status);
@@ -391,7 +391,7 @@ namespace ProcessHacker.Native
var thread = data.ReadStruct<SystemThreadInformation>(i +
Marshal.SizeOf(typeof(SystemProcessInformation)), j);
threads.Add(thread.ClientId.UniqueThread, thread);
threads.Add(thread.ClientId.ThreadId, thread);
}
return threads;
@@ -445,14 +445,14 @@ namespace ProcessHacker.Native
public static void LoadDriver(string serviceName)
{
var str = UnicodeString.Create(
var str = new UnicodeString(
"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\" + serviceName);
try
{
int status;
NtStatus status;
if ((status = Win32.NtLoadDriver(ref str)) < 0)
if ((status = Win32.NtLoadDriver(ref str)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -463,14 +463,14 @@ namespace ProcessHacker.Native
public static void UnloadDriver(string serviceName)
{
var str = UnicodeString.Create(
var str = new UnicodeString(
"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\" + serviceName);
try
{
int status;
NtStatus status;
if ((status = Win32.NtUnloadDriver(ref str)) < 0)
if ((status = Win32.NtUnloadDriver(ref str)) >= NtStatus.Error)
Win32.ThrowLastError(status);
}
finally
@@ -532,10 +532,10 @@ namespace ProcessHacker.Native
// Duplicate the handle if we're not using KPH
if (KProcessHacker.Instance == null)
{
int status;
NtStatus status;
if ((status = Win32.NtDuplicateObject(
process, handle, ProcessHandle.GetCurrent(), out objectHandleI, 0, 0, 0)) < 0)
process, handle, ProcessHandle.GetCurrent(), out objectHandleI, 0, 0, 0)) >= NtStatus.Error)
Win32.ThrowLastError();
objectHandle = new Win32Handle(objectHandleI);
@@ -573,13 +573,13 @@ namespace ProcessHacker.Native
if (KProcessHacker.Instance != null)
{
if (KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectTypeInformation,
otiMem, otiMem.Size, out retLength, out baseAddress) < 0)
otiMem, otiMem.Size, out retLength, out baseAddress) >= NtStatus.Error)
throw new Exception("ZwQueryObject failed.");
}
else
{
if (Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectTypeInformation,
otiMem, otiMem.Size, out retLength) < 0)
otiMem, otiMem.Size, out retLength) >= NtStatus.Error)
throw new Exception("NtQueryObject failed.");
}
@@ -627,13 +627,13 @@ namespace ProcessHacker.Native
if (KProcessHacker.Instance != null)
{
if (KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectNameInformation,
oniMem, oniMem.Size, out retLength, out baseAddress) < 0)
oniMem, oniMem.Size, out retLength, out baseAddress) >= NtStatus.Error)
throw new Exception("ZwQueryObject failed.");
}
else
{
if (Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectNameInformation,
oniMem, oniMem.Size, out retLength) < 0)
oniMem, oniMem.Size, out retLength) >= NtStatus.Error)
throw new Exception("NtQueryObject failed.");
}
@@ -696,8 +696,8 @@ namespace ProcessHacker.Native
}
else
{
using (Win32Handle processHandle =
new Win32Handle(process, handle, (int)OSVersion.MinProcessQueryInfoAccess))
using (var processHandle =
new Win32Handle<ProcessAccess>(process, handle, OSVersion.MinProcessQueryInfoAccess))
{
if ((processId = Win32.GetProcessId(processHandle)) == 0)
Win32.ThrowLastError();
@@ -728,14 +728,13 @@ namespace ProcessHacker.Native
}
else
{
using (Win32Handle threadHandle =
new Win32Handle(process, handle, (int)OSVersion.MinThreadQueryInfoAccess))
using (var threadHandle =
new Win32Handle<ThreadAccess>(process, handle, OSVersion.MinThreadQueryInfoAccess))
{
if ((threadId = Win32.GetThreadId(threadHandle)) == 0)
Win32.ThrowLastError();
var basicInfo = ThreadHandle.FromHandle(threadHandle).GetBasicInformation();
if ((processId = Win32.GetProcessIdOfThread(threadHandle)) == 0)
Win32.ThrowLastError();
threadId = basicInfo.ClientId.ThreadId;
processId = basicInfo.ClientId.ProcessId;
}
}
@@ -753,8 +752,8 @@ namespace ProcessHacker.Native
case "Token":
{
using (Win32Handle tokenHandle =
new Win32Handle(process, handle, (int)TokenAccess.Query))
using (var tokenHandle =
new Win32Handle<TokenAccess>(process, handle, TokenAccess.Query))
{
info.BestName = TokenHandle.FromHandle(tokenHandle).GetUser().GetName(true);
}
@@ -825,7 +824,7 @@ namespace ProcessHacker.Native
int result = Win32.SetTcpEntry(ref row);
if (result != 0)
Win32.ThrowLastError(result, false);
Win32.ThrowLastError(result);
}
}
+34 -27
View File
@@ -322,6 +322,7 @@ namespace ProcessHacker.Components
{
if (type == "Token" || type == "Process" || type == "File" ||
type == "Event" || type == "Mutant" || type == "Section" ||
type == "Semaphore" ||
type == "DLL" || type == "Mapped File")
return true;
else
@@ -390,28 +391,22 @@ namespace ProcessHacker.Components
}
else if (type == "Event")
{
var eventHandle = new Win32Handle<EventAccess>(phandle, handle, EventAccess.All);
EventBasicInformation ebi;
int retLen;
Win32.NtQueryEvent(eventHandle, EventInformationClass.EventBasicInformation,
out ebi, Marshal.SizeOf(typeof(EventBasicInformation)), out retLen);
var dupHandle = new Win32Handle<EventAccess>(phandle, handle, EventAccess.All);
var eventHandle = EventHandle.FromHandle(dupHandle);
EventBasicInformation ebi = eventHandle.GetBasicInformation();
InformationBox info = new InformationBox(
"Type: " + ebi.EventType.ToString().Replace("Event", "") +
"\r\nState: " + (ebi.EventState != 0 ? "True" : "False"));
info.ShowDialog();
eventHandle.Dispose();
dupHandle.Dispose();
}
else if (type == "Mutant")
{
var mutantHandle = new Win32Handle<MutantAccess>(phandle, handle, MutantAccess.All);
MutantBasicInformation mbi;
int retLen;
Win32.NtQueryMutant(mutantHandle, MutantInformationClass.MutantBasicInformation,
out mbi, Marshal.SizeOf(typeof(MutantBasicInformation)), out retLen);
var dupHandle = new Win32Handle<MutantAccess>(phandle, handle, MutantAccess.All);
var mutantHandle = MutantHandle.FromHandle(dupHandle);
MutantBasicInformation mbi = mutantHandle.GetBasicInformation();
InformationBox info = new InformationBox(
"Count: " + mbi.CurrentCount +
@@ -419,33 +414,47 @@ namespace ProcessHacker.Components
"\r\nAbandoned: " + (mbi.AbandonedState != 0 ? "True" : "False"));
info.ShowDialog();
mutantHandle.Dispose();
dupHandle.Dispose();
}
else if (type == "Section")
{
var sectionHandle = new Win32Handle<SectionAccess>(phandle, handle, SectionAccess.Query);
var dupHandle = new Win32Handle<SectionAccess>(phandle, handle, SectionAccess.Query);
var sectionHandle = SectionHandle.FromHandle(dupHandle);
SectionBasicInformation sbi;
SectionImageInformation sii;
int retLen;
int retVal;
SectionImageInformation sii = new SectionImageInformation();
bool haveImageInfo = true;
Win32.NtQuerySection(sectionHandle, SectionInformationClass.SectionBasicInformation,
out sbi, Marshal.SizeOf(typeof(SectionBasicInformation)), out retLen);
retVal = Win32.NtQuerySection(sectionHandle, SectionInformationClass.SectionImageInformation,
out sii, Marshal.SizeOf(typeof(SectionImageInformation)), out retLen);
sbi = sectionHandle.GetBasicInformation();
try { sii = sectionHandle.GetImageInformation(); }
catch { haveImageInfo = false; }
InformationBox info = new InformationBox(
"Attributes: " + Misc.FlagsToString(typeof(SectionAttributes), (long)sbi.SectionAttributes) +
"\r\nSize: " + Misc.GetNiceSizeName(sbi.SectionSize) + " (" + sbi.SectionSize.ToString() + " B)" +
(retVal == 0 ? ("\r\n\r\nImage Entry Point: 0x" + sii.EntryPoint.ToString("x8") +
(haveImageInfo ? ("\r\n\r\nImage Entry Point: 0x" + sii.TransferAddress.ToString("x8") +
"\r\nImage Machine Type: " + ((PE.MachineType)sii.ImageMachineType).ToString() +
"\r\nImage Characteristics: " + ((PE.ImageCharacteristics)sii.ImageCharacteristics).ToString() +
"\r\nImage Subsystem: " + ((PE.ImageSubsystem)sii.ImageSubsystem).ToString() +
"\r\nStack Reserve: 0x" + sii.StackReserved.ToString("x")) : ""));
info.ShowDialog();
sectionHandle.Dispose();
dupHandle.Dispose();
}
else if (type == "Semaphore")
{
var dupHandle = new Win32Handle<SemaphoreAccess>(phandle, handle, SemaphoreAccess.QueryState);
var semaphoreHandle = SemaphoreHandle.FromHandle(dupHandle);
SemaphoreBasicInformation sbi = semaphoreHandle.GetBasicInformation();
InformationBox info = new InformationBox(
"Current Count: " + sbi.CurrentCount.ToString() +
"\r\nMaximum Count: " + sbi.MaximumCount.ToString()
);
info.ShowDialog();
dupHandle.Dispose();
}
}
}
@@ -465,9 +474,7 @@ namespace ProcessHacker.Components
using (ProcessHandle process =
new ProcessHandle(_pid, Program.MinProcessGetHandleInformationRights))
{
Win32.DuplicateObject(process.Handle, handle, 0, 0,
0x1 // DUPLICATE_CLOSE_SOURCE
);
Win32.DuplicateObject(process.Handle, handle, 0, 0, DuplicateOptions.CloseSource);
}
}
catch (Exception ex)
@@ -23,6 +23,7 @@
using System;
using System.Windows.Forms;
using ProcessHacker.Native;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
@@ -39,7 +39,7 @@ namespace ProcessHacker.Components
{
ListViewItem item = listGroups.Items.Add(new ListViewItem());
item.Text = Windows.GetAccountName(groups.Groups.Groups[i].SID, Properties.Settings.Default.ShowAccountDomains);
item.Text = Windows.GetAccountName(groups.Groups.Groups[i].Sid, Properties.Settings.Default.ShowAccountDomains);
item.BackColor = GetAttributeColor(groups.Groups.Groups[i].Attributes);
item.SubItems.Add(new ListViewItem.ListViewSubItem(item,
GetAttributeString(groups.Groups.Groups[i].Attributes)));
@@ -128,7 +128,7 @@ namespace ProcessHacker
using (ProcessHandle process =
new ProcessHandle((int)listHandles.Items[index].Tag, ProcessAccess.DupHandle))
{
Win32.DuplicateObject(process.Handle, handle, 0, 0, 0x1);
Win32.DuplicateObject(process.Handle, handle, 0, 0, DuplicateOptions.CloseSource);
remove.Add(listHandles.Items[index]);
}
}
@@ -137,7 +137,7 @@ namespace ProcessHacker
try
{
Win32.DuplicateObject(phandle, new IntPtr(i), 0, 0, 0x1);
Win32.DuplicateObject(phandle, new IntPtr(i), 0, 0, DuplicateOptions.CloseSource);
}
catch
{ }
@@ -880,7 +880,7 @@ namespace ProcessHacker
if ((groups.Groups.Groups[i].Attributes & SidAttributes.IntegrityEnabled) != 0)
{
item.Integrity = Windows.GetAccountName(
groups.Groups.Groups[i].SID, false).Replace(" Mandatory Level", "");
groups.Groups.Groups[i].Sid, false).Replace(" Mandatory Level", "");
if (item.Integrity == "Untrusted")
item.IntegrityLevel = 0;