From 2199520ed577f5ca2004b54c852a964ffcf21a08 Mon Sep 17 00:00:00 2001 From: wj32 Date: Wed, 20 May 2009 07:05:02 +0000 Subject: [PATCH] * 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 --- trunk/KProcessHacker/i386/kprocesshacker.sys | Bin 20992 -> 20992 bytes trunk/KProcessHacker/include/ob.h | 8 + trunk/ProcessHacker.Native/Api/Enums.cs | 507 +----- trunk/ProcessHacker.Native/Api/Functions.cs | 13 +- .../Api/NativeDefinitions.cs | 44 + trunk/ProcessHacker.Native/Api/NativeEnums.cs | 569 +++++++ .../Api/NativeFunctions.cs | 986 ++++++++++-- .../ProcessHacker.Native/Api/NativeStructs.cs | 1365 +++++++++++++++++ trunk/ProcessHacker.Native/Api/NtStatus.cs | 131 ++ trunk/ProcessHacker.Native/Api/Structs.cs | 998 ------------ trunk/ProcessHacker.Native/KProcessHacker.cs | 18 +- .../Memory/PebMemoryAlloc.cs | 60 + .../Memory/SectionView.cs | 63 + .../Objects/DebugObjectHandle.cs | 4 +- .../Objects/DirectoryHandle.cs | 50 +- .../Objects/EventHandle.cs | 97 +- .../Objects/EventPairHandle.cs | 68 +- .../Objects/ISynchronizable.cs | 11 +- .../Objects/JobObjectHandle.cs | 106 -- .../Objects/KeyedEventHandle.cs | 122 +- .../Objects/LsaPolicyHandle.cs | 4 +- .../Objects/MutantHandle.cs | 59 +- .../Objects/PortHandle.cs | 101 ++ .../Objects/ProcessHandle.cs | 200 ++- .../Objects/ProfileHandle.cs | 35 + .../Objects/SectionHandle.cs | 192 ++- .../Objects/SemaphoreHandle.cs | 61 +- .../Objects/SymbolicLinkHandle.cs | 52 +- .../Objects/ThreadHandle.cs | 165 +- .../Objects/TimerHandle.cs | 28 +- .../Objects/TokenHandle.cs | 2 +- .../Objects/Win32Handle.cs | 92 +- .../ProcessHacker.Native.csproj | 8 + trunk/ProcessHacker.Native/Win32.cs | 31 +- trunk/ProcessHacker.Native/Windows.cs | 63 +- trunk/ProcessHacker/Components/HandleList.cs | 61 +- .../ProcessHacker/Components/JobProperties.cs | 1 + .../Components/TokenGroupsList.cs | 2 +- .../ProcessHacker/Forms/HandleFilterWindow.cs | 2 +- trunk/ProcessHacker/Forms/TerminatorWindow.cs | 2 +- .../Providers/ProcessSystemProvider.cs | 2 +- 41 files changed, 4394 insertions(+), 1989 deletions(-) create mode 100644 trunk/ProcessHacker.Native/Api/NativeDefinitions.cs create mode 100644 trunk/ProcessHacker.Native/Api/NativeEnums.cs create mode 100644 trunk/ProcessHacker.Native/Api/NativeStructs.cs create mode 100644 trunk/ProcessHacker.Native/Api/NtStatus.cs create mode 100644 trunk/ProcessHacker.Native/Memory/PebMemoryAlloc.cs create mode 100644 trunk/ProcessHacker.Native/Memory/SectionView.cs create mode 100644 trunk/ProcessHacker.Native/Objects/PortHandle.cs create mode 100644 trunk/ProcessHacker.Native/Objects/ProfileHandle.cs diff --git a/trunk/KProcessHacker/i386/kprocesshacker.sys b/trunk/KProcessHacker/i386/kprocesshacker.sys index 228ad52c425de3b475a39f7d151c050ba88f7289..26161fbc86f1238d0017a54ae6ee158f1c1794d6 100644 GIT binary patch delta 53 zcmZoz!q~8cal#8`(;31OU;8p0n7!GG@s}=$JK0=6Rlwrq{0+H}@*Q?Q*;-?ga{cz^ IHToe+0APd{yZ`_I delta 53 zcmZoz!q~8cal#Acb!kEqU;8rM&)RIo_)8bWooue3DzK{7H$zlmy<7k8Qnr_Gw@%)? IMn6Oe09N)EnE(I) diff --git a/trunk/KProcessHacker/include/ob.h b/trunk/KProcessHacker/include/ob.h index bfe7691a1..7e891fbeb 100644 --- a/trunk/KProcessHacker/include/ob.h +++ b/trunk/KProcessHacker/include/ob.h @@ -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, diff --git a/trunk/ProcessHacker.Native/Api/Enums.cs b/trunk/ProcessHacker.Native/Api/Enums.cs index b88dae89c..d8fa80922 100644 --- a/trunk/ProcessHacker.Native/Api/Enums.cs +++ b/trunk/ProcessHacker.Native/Api/Enums.cs @@ -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 + { + /// + /// Don't use any of the flags (only works alone) + /// + None = 0x0000, + /// + /// Removes the browse button + /// + NoBrowse = 0x0001, + /// + /// No default item selected + /// + NoDefault = 0x0002, + /// + /// Calculates the working directory from the file name + /// + CalcDirectory = 0x0004, + /// + /// Removes the edit box label + /// + NoLabel = 0x0008, + /// + /// Removes the seperate memory space checkbox (Windows NT only) + /// + 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 - { - /// - /// Don't use any of the flags (only works alone) - /// - None = 0x0000, - /// - /// Removes the browse button - /// - NoBrowse = 0x0001, - /// - /// No default item selected - /// - NoDefault = 0x0002, - /// - /// Calculates the working directory from the file name - /// - CalcDirectory = 0x0004, - /// - /// Removes the edit box label - /// - NoLabel = 0x0008, - /// - /// Removes the seperate memory space checkbox (Windows NT only) - /// - NoSeperateMemory = 0x0020 - } } diff --git a/trunk/ProcessHacker.Native/Api/Functions.cs b/trunk/ProcessHacker.Native/Api/Functions.cs index badbec43d..34938335e 100644 --- a/trunk/ProcessHacker.Native/Api/Functions.cs +++ b/trunk/ProcessHacker.Native/Api/Functions.cs @@ -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 ); diff --git a/trunk/ProcessHacker.Native/Api/NativeDefinitions.cs b/trunk/ProcessHacker.Native/Api/NativeDefinitions.cs new file mode 100644 index 000000000..6ff716a71 --- /dev/null +++ b/trunk/ProcessHacker.Native/Api/NativeDefinitions.cs @@ -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 . + */ + +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; + } +} diff --git a/trunk/ProcessHacker.Native/Api/NativeEnums.cs b/trunk/ProcessHacker.Native/Api/NativeEnums.cs new file mode 100644 index 000000000..060507f70 --- /dev/null +++ b/trunk/ProcessHacker.Native/Api/NativeEnums.cs @@ -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 . + */ + +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 + } +} diff --git a/trunk/ProcessHacker.Native/Api/NativeFunctions.cs b/trunk/ProcessHacker.Native/Api/NativeFunctions.cs index d54682355..58559cd92 100644 --- a/trunk/ProcessHacker.Native/Api/NativeFunctions.cs +++ b/trunk/ProcessHacker.Native/Api/NativeFunctions.cs @@ -31,35 +31,103 @@ namespace ProcessHacker.Native.Api { public partial class Win32 { + #region System Calls + [DllImport("ntdll.dll")] - public static extern int NtAlertThread( + public static extern NtStatus NtAcceptConnectPort( + [Out] out IntPtr PortHandle, + [In] [Optional] IntPtr PortContext, + [In] ref PortMessage ConnectionRequest, + [In] bool AcceptConnection, + [Optional] ref PortView ServerView, + [Out] [Optional] out RemotePortView ClientView + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtAlertThread( [In] IntPtr ThreadHandle ); [DllImport("ntdll.dll")] - public static extern int NtAlertResumeThread( + public static extern NtStatus NtAlertResumeThread( [In] IntPtr ThreadHandle, [Out] [Optional] out int PreviousSuspendCount ); [DllImport("ntdll.dll")] - public static extern int NtAllocateLocallyUniqueId( + public static extern NtStatus NtAllocateLocallyUniqueId( [Out] out Luid Luid ); [DllImport("ntdll.dll")] - public static extern int NtCancelTimer( + public static extern NtStatus NtAllocateVirtualMemory( + [In] IntPtr ProcessHandle, + ref IntPtr BaseAddress, + [In] IntPtr ZeroBits, + ref IntPtr RegionSize, + [In] MemoryFlags AllocationType, + [In] MemoryProtection Protect + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtAreMappedFilesTheSame( + [In] IntPtr File1MappedAsAnImage, + [In] IntPtr File2MappedAsFile + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtAssignProcessToJobObject( + [In] IntPtr JobHandle, + [In] IntPtr ProcessHandle + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtCancelTimer( [In] IntPtr TimerHandle, [Out] [Optional] out bool CurrentState ); [DllImport("ntdll.dll")] - public static extern int NtClearEvent( + public static extern NtStatus NtClearEvent( [In] IntPtr EventHandle ); [DllImport("ntdll.dll")] - public static extern int NtCreateDebugObject( + public static extern NtStatus NtClose( + [In] IntPtr Handle + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtCompleteConnectPort( + [In] IntPtr PortHandle + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtConnectPort( + [Out] out IntPtr PortHandle, + [In] ref UnicodeString PortName, + [In] ref SecurityQualityOfService SecurityQos, + [Optional] ref PortView ClientView, + [Optional] ref RemotePortView ServerView, + [Out] [Optional] out int MaxMessageLength, + [Optional] IntPtr ConnectionInformation, + [Optional] out int ConnectionInformationLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtConnectPort( + [Out] out IntPtr PortHandle, + [In] ref UnicodeString PortName, + [In] ref SecurityQualityOfService SecurityQos, + [Optional] ref PortView ClientView, + [Optional] ref RemotePortView ServerView, + [Out] [Optional] out int MaxMessageLength, + [Optional] IntPtr ConnectionInformation, + [Optional] int ConnectionInformationLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtCreateDebugObject( [Out] out IntPtr DebugObjectHandle, [In] DebugObjectAccess DesiredAccess, [In] [Optional] ref ObjectAttributes ObjectAttributes, @@ -67,7 +135,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateDebugObject( + public static extern NtStatus NtCreateDebugObject( [Out] out IntPtr DebugObjectHandle, [In] DebugObjectAccess DesiredAccess, [In] [Optional] IntPtr ObjectAttributes, @@ -75,14 +143,14 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateDirectoryObject( + public static extern NtStatus NtCreateDirectoryObject( [Out] out IntPtr DirectoryHandle, [In] DirectoryAccess DesiredAccess, [In] ref ObjectAttributes ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtCreateEvent( + public static extern NtStatus NtCreateEvent( [Out] out IntPtr EventHandle, [In] EventAccess DesiredAccess, [In] [Optional] ref ObjectAttributes ObjectAttributes, @@ -91,7 +159,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateEvent( + public static extern NtStatus NtCreateEvent( [Out] out IntPtr EventHandle, [In] EventAccess DesiredAccess, [In] [Optional] IntPtr ObjectAttributes, @@ -100,21 +168,42 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateEventPair( + public static extern NtStatus NtCreateEventPair( [Out] out IntPtr EventPairHandle, [In] EventPairAccess DesiredAccess, [In] [Optional] ref ObjectAttributes ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtCreateEventPair( + public static extern NtStatus NtCreateEventPair( [Out] out IntPtr EventPairHandle, [In] EventPairAccess DesiredAccess, [In] [Optional] IntPtr ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtCreateKeyedEvent( + public static extern NtStatus NtCreateJobObject( + [Out] out IntPtr JobHandle, + [In] JobObjectAccess DesiredAccess, + [In] [Optional] ref ObjectAttributes ObjectAttributes + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtCreateJobObject( + [Out] out IntPtr JobHandle, + [In] JobObjectAccess DesiredAccess, + [In] [Optional] IntPtr ObjectAttributes + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtCreateJobSet( + [In] int NumJob, + JobSetArray[] UserJobSet, + [In] int Flags + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtCreateKeyedEvent( [Out] out IntPtr KeyedEventHandle, [In] KeyedEventAccess DesiredAccess, [In] [Optional] ref ObjectAttributes ObjectAttributes, @@ -122,7 +211,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateKeyedEvent( + public static extern NtStatus NtCreateKeyedEvent( [Out] out IntPtr KeyedEventHandle, [In] KeyedEventAccess DesiredAccess, [In] [Optional] IntPtr ObjectAttributes, @@ -130,7 +219,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateMutant( + public static extern NtStatus NtCreateMutant( [Out] out IntPtr MutantHandle, [In] MutantAccess DesiredAccess, [In] [Optional] ref ObjectAttributes ObjectAttributes, @@ -138,7 +227,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateMutant( + public static extern NtStatus NtCreateMutant( [Out] out IntPtr MutantHandle, [In] MutantAccess DesiredAccess, [In] [Optional] IntPtr ObjectAttributes, @@ -146,7 +235,16 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateProcess( + public static extern NtStatus NtCreatePort( + [Out] out IntPtr PortHandle, + [In] ref ObjectAttributes ObjectAttributes, + [In] int MaxConnectionInfoLength, + [In] int MaxMessageLength, + [In] [Optional] int MaxPoolUsage + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtCreateProcess( [Out] out IntPtr ProcessHandle, [In] ProcessAccess DesiredAccess, [In] [Optional] ref ObjectAttributes ObjectAttributes, @@ -158,7 +256,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateProcess( + public static extern NtStatus NtCreateProcess( [Out] out IntPtr ProcessHandle, [In] ProcessAccess DesiredAccess, [In] [Optional] IntPtr ObjectAttributes, @@ -170,29 +268,42 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateSection( + public static extern NtStatus NtCreateProfile( + [Out] out IntPtr ProfileHandle, + [In] IntPtr ProcessHandle, + [In] IntPtr ProfileBase, + [In] IntPtr ProfileSize, + [In] int BucketSize, + [In] IntPtr Buffer, + [In] int BufferSize, + [In] KProfileSource ProfileSource, + [In] IntPtr Affinity + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtCreateSection( [Out] out IntPtr SectionHandle, [In] SectionAccess DesiredAccess, [In] [Optional] ref ObjectAttributes ObjectAttributes, - [In] [Optional] ref LargeInteger MaximumSize, + [In] [Optional] ref long MaximumSize, [In] int PageAttributes, [In] int SectionAttributes, [In] [Optional] IntPtr FileHandle ); [DllImport("ntdll.dll")] - public static extern int NtCreateSection( + public static extern NtStatus NtCreateSection( [Out] out IntPtr SectionHandle, [In] SectionAccess DesiredAccess, [In] [Optional] IntPtr ObjectAttributes, - [In] [Optional] ref LargeInteger MaximumSize, + [In] [Optional] ref long MaximumSize, [In] int PageAttributes, [In] int SectionAttributes, [In] [Optional] IntPtr FileHandle ); [DllImport("ntdll.dll")] - public static extern int NtCreateSemaphore( + public static extern NtStatus NtCreateSemaphore( [Out] out IntPtr SemaphoreHandle, [In] SemaphoreAccess DesiredAccess, [In] [Optional] ref ObjectAttributes ObjectAttributes, @@ -201,7 +312,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateSemaphore( + public static extern NtStatus NtCreateSemaphore( [Out] out IntPtr SemaphoreHandle, [In] SemaphoreAccess DesiredAccess, [In] [Optional] IntPtr ObjectAttributes, @@ -210,7 +321,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateSymbolicLinkObject( + public static extern NtStatus NtCreateSymbolicLinkObject( [Out] out IntPtr LinkHandle, [In] SymbolicLinkAccess DesiredAccess, [In] ref ObjectAttributes ObjectAttributes, @@ -218,7 +329,19 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateTimer( + public static extern NtStatus NtCreateThread( + [Out] out IntPtr ThreadHandle, + [In] ThreadAccess DesiredAccess, + [In] [Optional] ref ObjectAttributes ObjectAttributes, + [In] IntPtr ProcessHandle, + [Out] out ClientId ClientId, + [In] ref Context ThreadContext, + [In] ref InitialTeb InitialTeb, + [In] bool CreateSuspended + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtCreateTimer( [Out] out IntPtr TimerHandle, [In] TimerAccess DesiredAccess, [In] [Optional] ref ObjectAttributes ObjectAttributes, @@ -226,7 +349,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtCreateTimer( + public static extern NtStatus NtCreateTimer( [Out] out IntPtr TimerHandle, [In] TimerAccess DesiredAccess, [In] [Optional] IntPtr ObjectAttributes, @@ -234,30 +357,70 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtDebugActiveProcess( + public static extern NtStatus NtCreateWaitablePort( + [Out] out IntPtr PortHandle, + [In] ref ObjectAttributes ObjectAttributes, + [In] int MaxConnectionInfoLength, + [In] int MaxMessageLength, + [In] [Optional] int MaxPoolUsage + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtDebugActiveProcess( [In] IntPtr ProcessHandle, [In] IntPtr DebugObjectHandle ); [DllImport("ntdll.dll")] - public static extern int NtDelayExecution( + public static extern NtStatus NtDelayExecution( [In] bool Alertable, [In] ref long DelayInterval ); [DllImport("ntdll.dll")] - public static extern int NtDuplicateObject( + public static extern NtStatus NtDuplicateObject( [In] IntPtr SourceProcessHandle, [In] IntPtr SourceHandle, [In] IntPtr TargetProcessHandle, [Out] out IntPtr TargetHandle, [In] int DesiredAccess, [In] HandleFlags Attributes, - [In] int Options + [In] DuplicateOptions Options ); [DllImport("ntdll.dll")] - public static extern int NtGetNextProcess( + public static extern NtStatus NtExtendSection( + [In] IntPtr SectionHandle, + ref long NewSectionSize + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtFlushVirtualMemory( + [In] IntPtr ProcessHandle, + ref IntPtr BaseAddress, + ref IntPtr RegionSize, + [Out] out IoStatusBlock IoStatus + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtFreeVirtualMemory( + [In] IntPtr ProcessHandle, + ref IntPtr BaseAddress, + ref IntPtr RegionSize, + [In] MemoryFlags FreeType + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtGetContextThread( + [In] IntPtr ThreadHandle, + ref Context ThreadContext + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtGetCurrentProcessorNumber(); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtGetNextProcess( [In] [Optional] IntPtr ProcessHandle, [In] ProcessAccess DesiredAccess, [In] HandleFlags HandleAttributes, @@ -266,7 +429,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtGetNextThread( + public static extern NtStatus NtGetNextThread( [In] [Optional] IntPtr ProcessHandle, [In] [Optional] IntPtr ThreadHandle, [In] ThreadAccess DesiredAccess, @@ -276,84 +439,191 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtLoadDriver( + public static extern NtStatus NtImpersonateAnonymousToken( + [In] IntPtr ThreadHandle + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtImpersonateClientOfPort( + [In] IntPtr PortHandle, + [In] ref PortMessage Message + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtImpersonateThread( + [In] IntPtr ServerThreadHandle, + [In] IntPtr ClientThreadHandle, + [In] ref SecurityQualityOfService SecurityQos + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtIsProcessInJob( + [In] IntPtr ProcessHandle, + [In] [Optional] IntPtr JobHandle + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtListenPort( + [In] IntPtr PortHandle, + [Out] out PortMessage ConnectionRequest + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtLoadDriver( [In] ref UnicodeString DriverPath ); [DllImport("ntdll.dll")] - public static extern int NtMakePermanentObject( + public static extern NtStatus NtLockVirtualMemory( + [In] IntPtr ProcessHandle, + ref IntPtr BaseAddress, + ref IntPtr RegionSize, + [In] MemoryFlags MapType + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtMakePermanentObject( [In] IntPtr Handle ); [DllImport("ntdll.dll")] - public static extern int NtMakeTemporaryObject( + public static extern NtStatus NtMakeTemporaryObject( [In] IntPtr Handle ); [DllImport("ntdll.dll")] - public static extern int NtOpenDirectoryObject( + public static extern NtStatus NtMapViewOfSection( + [In] IntPtr SectionHandle, + [In] IntPtr ProcessHandle, + ref IntPtr BaseAddress, + [In] IntPtr ZeroBits, + [In] IntPtr CommitSize, + [Optional] ref long SectionOffset, + ref IntPtr ViewSize, + [In] SectionInherit InheritDisposition, + [In] MemoryFlags AllocationType, + [In] MemoryProtection Win32Protect + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtOpenDirectoryObject( [Out] out IntPtr DirectoryHandle, [In] DirectoryAccess DesiredAccess, [In] ref ObjectAttributes ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtOpenEvent( + public static extern NtStatus NtOpenEvent( [Out] out IntPtr EventHandle, [In] EventAccess DesiredAccess, [In] ref ObjectAttributes ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtOpenEventPair( + public static extern NtStatus NtOpenEventPair( [Out] out IntPtr EventPairHandle, [In] EventPairAccess DesiredAccess, [In] ref ObjectAttributes ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtOpenKeyedEvent( + public static extern NtStatus NtOpenJobObject( + [Out] out IntPtr JobHandle, + [In] JobObjectAccess DesiredAccess, + [In] ref ObjectAttributes ObjectAttributes + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtOpenKeyedEvent( [Out] out IntPtr KeyedEventHandle, [In] KeyedEventAccess DesiredAccess, [In] ref ObjectAttributes ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtOpenMutant( + public static extern NtStatus NtOpenMutant( [Out] out IntPtr MutantHandle, [In] MutantAccess DesiredAccess, [In] ref ObjectAttributes ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtOpenSemaphore( + public static extern NtStatus NtOpenProcess( + [Out] out IntPtr ProcessHandle, + [In] ProcessAccess DesiredAccess, + [In] ref ObjectAttributes ObjectAttributes, + [In] [Optional] ref ClientId ClientId + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtOpenProcess( + [Out] out IntPtr ProcessHandle, + [In] ProcessAccess DesiredAccess, + [In] ref ObjectAttributes ObjectAttributes, + [In] [Optional] IntPtr ClientId + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtOpenSection( + [Out] out IntPtr SectionHandle, + [In] SectionAccess DesiredAccess, + [In] ref ObjectAttributes ObjectAttributes + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtOpenSemaphore( [Out] out IntPtr SemaphoreHandle, [In] SemaphoreAccess DesiredAccess, [In] ref ObjectAttributes ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtOpenSymbolicLinkObject( + public static extern NtStatus NtOpenSymbolicLinkObject( [Out] out IntPtr LinkHandle, [In] SymbolicLinkAccess DesiredAccess, [In] ref ObjectAttributes ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtOpenTimer( + public static extern NtStatus NtOpenThread( + [Out] out IntPtr ThreadHandle, + [In] ThreadAccess DesiredAccess, + [In] ref ObjectAttributes ObjectAttributes, + [In] [Optional] ref ClientId ClientId + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtOpenThread( + [Out] out IntPtr ThreadHandle, + [In] ThreadAccess DesiredAccess, + [In] ref ObjectAttributes ObjectAttributes, + [In] [Optional] IntPtr ClientId + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtOpenTimer( [Out] out IntPtr TimerHandle, [In] TimerAccess DesiredAccess, [In] ref ObjectAttributes ObjectAttributes ); [DllImport("ntdll.dll")] - public static extern int NtPulseEvent( + public static extern NtStatus NtProtectVirtualMemory( + [In] IntPtr ProcessHandle, + ref IntPtr BaseAddress, + ref IntPtr RegionSize, + [In] MemoryProtection NewProtect, + [Out] out MemoryProtection OldProtect + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtPulseEvent( [In] IntPtr EventHandle, [Out] [Optional] out int PreviousState ); [DllImport("ntdll.dll")] - public static extern int NtQueryDirectoryObject( + public static extern NtStatus NtQueryDirectoryObject( [In] IntPtr DirectoryHandle, [In] IntPtr Buffer, [In] int Length, @@ -364,7 +634,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryEvent( + public static extern NtStatus NtQueryEvent( [In] IntPtr EventHandle, [In] EventInformationClass EventInformationClass, [Out] out EventBasicInformation EventInformation, @@ -373,7 +643,16 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryInformationProcess( + public static extern NtStatus NtQueryInformationJobObject( + [In] [Optional] IntPtr JobHandle, + [In] JobObjectInformationClass JobObjectInformationClass, + [In] IntPtr JobObjectInformation, + [In] int JobObjectInformationLength, + [Out] [Optional] out int ReturnLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtQueryInformationProcess( [In] IntPtr ProcessHandle, [In] ProcessInformationClass ProcessInformationClass, IntPtr ProcessInformation, @@ -382,7 +661,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryInformationProcess( + public static extern NtStatus NtQueryInformationProcess( [In] IntPtr ProcessHandle, [In] ProcessInformationClass ProcessInformationClass, [Out] out int ProcessInformation, @@ -391,7 +670,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryInformationProcess( + public static extern NtStatus NtQueryInformationProcess( [In] IntPtr ProcessHandle, [In] ProcessInformationClass ProcessInformationClass, [Out] out PooledUsageAndLimits ProcessInformation, @@ -400,7 +679,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryInformationProcess( + public static extern NtStatus NtQueryInformationProcess( [In] IntPtr ProcessHandle, [In] ProcessInformationClass ProcessInformationClass, [Out] out QuotaLimits ProcessInformation, @@ -409,7 +688,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryInformationProcess( + public static extern NtStatus NtQueryInformationProcess( [In] IntPtr ProcessHandle, [In] ProcessInformationClass ProcessInformationClass, [Out] out MemExecuteOptions ProcessInformation, @@ -418,7 +697,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryInformationProcess( + public static extern NtStatus NtQueryInformationProcess( [In] IntPtr ProcessHandle, [In] ProcessInformationClass ProcessInformationClass, [Out] out ProcessBasicInformation ProcessInformation, @@ -427,7 +706,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryInformationProcess( + public static extern NtStatus NtQueryInformationProcess( [In] IntPtr ProcessHandle, [In] ProcessInformationClass ProcessInformationClass, [Out] out UnicodeString ProcessInformation, @@ -436,7 +715,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryInformationThread( + public static extern NtStatus NtQueryInformationThread( [In] IntPtr ThreadHandle, [In] ThreadInformationClass ThreadInformationClass, ref ThreadBasicInformation ThreadInformation, @@ -445,7 +724,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryInformationThread( + public static extern NtStatus NtQueryInformationThread( [In] IntPtr ThreadHandle, [In] ThreadInformationClass ThreadInformationClass, [Out] out int ThreadInformation, @@ -454,7 +733,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryInformationThread( + public static extern NtStatus NtQueryInformationThread( [In] IntPtr ThreadHandle, [In] ThreadInformationClass ThreadInformationClass, IntPtr ThreadInformation, @@ -463,7 +742,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public unsafe static extern int NtQueryInformationThread( + public unsafe static extern NtStatus NtQueryInformationThread( [In] IntPtr ThreadHandle, [In] ThreadInformationClass ThreadInformationClass, void* ThreadInformation, @@ -472,7 +751,13 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryMutant( + public static extern NtStatus NtQueryIntervalProfile( + [In] KProfileSource Source, + [Out] out int Interval + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtQueryMutant( [In] IntPtr MutantHandle, [In] MutantInformationClass MutantInformationClass, [Out] out MutantBasicInformation MutantInformation, @@ -481,7 +766,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryObject( + public static extern NtStatus NtQueryObject( [In] IntPtr Handle, [In] ObjectInformationClass ObjectInformationClass, [Out] IntPtr ObjectInformation, @@ -490,25 +775,28 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQuerySection( + public static extern NtStatus NtQueryPortInformationProcess(); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtQuerySection( [In] IntPtr SectionHandle, [In] SectionInformationClass SectionInformationClass, [Out] out SectionBasicInformation SectionInformation, - [In] int SectionInformationLength, - [Out] [Optional] out int ReturnLength + [In] IntPtr SectionInformationLength, + [Out] [Optional] out IntPtr ReturnLength ); [DllImport("ntdll.dll")] - public static extern int NtQuerySection( + public static extern NtStatus NtQuerySection( [In] IntPtr SectionHandle, [In] SectionInformationClass SectionInformationClass, [Out] out SectionImageInformation SectionInformation, - [In] int SectionInformationLength, - [Out] [Optional] out int ReturnLength + [In] IntPtr SectionInformationLength, + [Out] [Optional] out IntPtr ReturnLength ); [DllImport("ntdll.dll")] - public static extern int NtQuerySemaphore( + public static extern NtStatus NtQuerySemaphore( [In] IntPtr SemaphoreHandle, [In] SemaphoreInformationClass SemaphoreInformationClass, [Out] out SemaphoreBasicInformation SemaphoreInformation, @@ -517,14 +805,14 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQuerySymbolicLinkObject( + public static extern NtStatus NtQuerySymbolicLinkObject( [In] IntPtr LinkHandle, ref UnicodeString LinkName, [Out] [Optional] out int ReturnLength ); [DllImport("ntdll.dll")] - public static extern int NtQuerySystemInformation( + public static extern NtStatus NtQuerySystemInformation( [In] SystemInformationClass SystemInformationClass, [Out] out SystemBasicInformation SystemInformation, [In] int SystemInformationLength, @@ -532,7 +820,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQuerySystemInformation( + public static extern NtStatus NtQuerySystemInformation( [In] SystemInformationClass SystemInformationClass, IntPtr SystemInformation, [In] int SystemInformationLength, @@ -540,7 +828,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQuerySystemInformation( + public static extern NtStatus NtQuerySystemInformation( [In] SystemInformationClass SystemInformationClass, [MarshalAs(UnmanagedType.LPArray)] SystemProcessorPerformanceInformation[] SystemInformation, [In] int SystemInformationLength, @@ -548,7 +836,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQuerySystemInformation( + public static extern NtStatus NtQuerySystemInformation( [In] SystemInformationClass SystemInformationClass, [Out] out SystemPerformanceInformation SystemInformation, [In] int SystemInformationLength, @@ -556,7 +844,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQuerySystemInformation( + public static extern NtStatus NtQuerySystemInformation( [In] SystemInformationClass SystemInformationClass, [Out] out SystemCacheInformation SystemInformation, [In] int SystemInformationLength, @@ -564,7 +852,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueryTimer( + public static extern NtStatus NtQueryTimer( [In] IntPtr TimerHandle, [In] TimerInformationClass TimerInformationClass, [Out] out TimerBasicInformation TimerInformation, @@ -573,7 +861,17 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtQueueApcThread( + public static extern NtStatus NtQueryVirtualMemory( + [In] IntPtr ProcessHandle, + [In] IntPtr BaseAddress, + [In] MemoryInformationClass MemoryInformationClass, + [In] IntPtr Buffer, + [In] IntPtr MemoryInformationLength, + [Out] [Optional] out IntPtr ReturnLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtQueueApcThread( [In] IntPtr ThreadHandle, [In] IntPtr ApcRoutine, [In] [Optional] IntPtr ApcArgument1, @@ -582,7 +880,31 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtReleaseKeyedEvent( + public static extern NtStatus NtReadRequestData( + [In] IntPtr PortHandle, + [In] ref PortMessage Message, + [In] int DataEntryIndex, + [In] IntPtr Buffer, + [In] IntPtr BufferSize, + [Out] [Optional] out IntPtr ReturnLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtReadVirtualMemory( + [In] IntPtr ProcessHandle, + [In] [Optional] IntPtr BaseAddress, + [In] IntPtr Buffer, + [In] IntPtr BufferSize, + [Out] [Optional] out IntPtr ReturnLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtRegisterThreadTerminatePort( + [In] IntPtr PortHandle + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtReleaseKeyedEvent( [In] IntPtr KeyedEventHandle, [In] IntPtr KeyValue, [In] bool Alertable, @@ -590,64 +912,136 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtReleaseMutant( + public static extern NtStatus NtReleaseMutant( [In] IntPtr MutantHandle, [Out] [Optional] out int PreviousCount ); [DllImport("ntdll.dll")] - public static extern int NtReleaseSemaphore( + public static extern NtStatus NtReleaseSemaphore( [In] IntPtr SemaphoreHandle, [In] int ReleaseCount, [Out] [Optional] out int PreviousCount ); [DllImport("ntdll.dll")] - public static extern int NtRemoveProcessDebug( + public static extern NtStatus NtRemoveProcessDebug( [In] IntPtr ProcessHandle, [In] IntPtr DebugObjectHandle ); [DllImport("ntdll.dll")] - public static extern int NtResetEvent( + public static extern NtStatus NtReplyPort( + [In] IntPtr PortHandle, + [In] ref PortMessage ReplyMessage + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtReplyWaitReceivePort( + [In] IntPtr PortHandle, + [Out] [Optional] out IntPtr PortContext, + [In] [Optional] ref PortMessage ReplyMessage, + [Out] out PortMessage ReceiveMessage + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtReplyWaitReceivePortEx( + [In] IntPtr PortHandle, + [Out] [Optional] out IntPtr PortContext, + [In] [Optional] ref PortMessage ReplyMessage, + [Out] out PortMessage ReceiveMessage, + [In] [Optional] ref long Timeout + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtReplyWaitReplyPort( + [In] IntPtr PortHandle, + ref PortMessage ReplyMessage + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtRequestPort( + [In] IntPtr PortHandle, + [In] ref PortMessage RequestMessage + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtRequestWaitReplyPort( + [In] IntPtr PortHandle, + [In] ref PortMessage RequestMessage, + [Out] out PortMessage ReplyMessage + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtResetEvent( [In] IntPtr EventHandle, [Out] [Optional] out int PreviousState ); [DllImport("ntdll.dll")] - public static extern int NtResumeProcess( + public static extern NtStatus NtResumeProcess( [In] IntPtr ProcessHandle ); [DllImport("ntdll.dll")] - public static extern int NtResumeThread( + public static extern NtStatus NtResumeThread( [In] IntPtr ThreadHandle, [Out] [Optional] out int PreviousSuspendCount ); [DllImport("ntdll.dll")] - public static extern int NtSetEvent( + public static extern NtStatus NtSetContextThread( + [In] IntPtr ThreadHandle, + [In] ref Context ThreadContext + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtSetEvent( [In] IntPtr EventHandle, [Out] [Optional] out int PreviousState ); [DllImport("ntdll.dll")] - public static extern int NtSetEventBoostPriority( + public static extern NtStatus NtSetEventBoostPriority( [In] IntPtr EventHandle ); [DllImport("ntdll.dll")] - public static extern int NtSetHighEventPair( + public static extern NtStatus NtSetHighEventPair( [In] IntPtr EventPairHandle ); [DllImport("ntdll.dll")] - public static extern int NtSetHighWaitLowEventPair( + public static extern NtStatus NtSetHighWaitLowEventPair( [In] IntPtr EventPairHandle ); [DllImport("ntdll.dll")] - public static extern int NtSetInformationThread( + public static extern NtStatus NtSetInformationJobObject( + [In] IntPtr JobHandle, + [In] JobObjectInformationClass JobObjectInformationClass, + [In] IntPtr JobObjectInformation, + [In] int JobObjectInformationLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtSetInformationProcess( + [In] IntPtr ProcessHandle, + [In] ProcessInformationClass ProcessInformationClass, + [In] IntPtr ProcessInformation, + [In] int ProcessInformationLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtSetInformationProcess( + [In] IntPtr ProcessHandle, + [In] ProcessInformationClass ProcessInformationClass, + [In] ref int ProcessInformation, + [In] int ProcessInformationLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtSetInformationThread( [In] IntPtr ThreadHandle, [In] ThreadInformationClass ThreadInformationClass, [In] IntPtr ThreadInformation, @@ -655,27 +1049,41 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtSetLowEventPair( + public static extern NtStatus NtSetInformationThread( + [In] IntPtr ThreadHandle, + [In] ThreadInformationClass ThreadInformationClass, + [In] ref int ThreadInformation, + [In] int ThreadInformationLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtSetIntervalProfile( + [In] int Interval, + [In] KProfileSource Source + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtSetLowEventPair( [In] IntPtr EventPairHandle ); [DllImport("ntdll.dll")] - public static extern int NtSetLowWaitHighEventPair( + public static extern NtStatus NtSetLowWaitHighEventPair( [In] IntPtr EventPairHandle ); [DllImport("ntdll.dll")] - public static extern int NtSetSystemInformation( + public static extern NtStatus NtSetSystemInformation( [In] SystemInformationClass SystemInformationClass, [In] ref SystemLoadAndCallImage SystemInformation, [In] int SystemInformationLength ); [DllImport("ntdll.dll")] - public static extern int NtSetTimer( + public static extern NtStatus NtSetTimer( [In] IntPtr TimerHandle, [In] ref long DueTime, - [In] [Optional] ProcessHacker.Native.Objects.TimerHandle.TimerApcRoutine TimerApcRoutine, + [In] [Optional] TimerApcRoutine TimerApcRoutine, [In] [Optional] IntPtr TimerContext, [In] bool ResumeTimer, [In] [Optional] int Period, @@ -683,7 +1091,7 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtSignalAndWaitForSingleObject( + public static extern NtStatus NtSignalAndWaitForSingleObject( [In] IntPtr SignalHandle, [In] IntPtr WaitHandle, [In] bool Alertable, @@ -691,37 +1099,415 @@ namespace ProcessHacker.Native.Api ); [DllImport("ntdll.dll")] - public static extern int NtSuspendProcess( + public static extern NtStatus NtStartProfile( + [In] IntPtr ProfileHandle + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtStopProfile( + [In] IntPtr ProfileHandle + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtSuspendProcess( [In] IntPtr ProcessHandle ); [DllImport("ntdll.dll")] - public static extern int NtSuspendThread( + public static extern NtStatus NtSuspendThread( [In] IntPtr ThreadHandle, [Out] [Optional] out int PreviousSuspendCount ); [DllImport("ntdll.dll")] - public static extern int NtUnloadDriver( + public static extern NtStatus NtTerminateJobObject( + [In] IntPtr JobHandle, + [In] int ExitStatus + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtTerminateProcess( + [In] [Optional] IntPtr ProcessHandle, + [In] int ExitStatus + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtTerminateThread( + [In] [Optional] IntPtr ThreadHandle, + [In] int ExitStatus + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtTestAlert(); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtUnloadDriver( [In] ref UnicodeString DriverPath ); [DllImport("ntdll.dll")] - public static extern int NtWaitForKeyedEvent( - [In] int KeyedEventHandle, + public static extern NtStatus NtUnlockVirtualMemory( + [In] IntPtr ProcessHandle, + ref IntPtr BaseAddress, + ref IntPtr RegionSize, + [In] MemoryFlags MapType + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtUnmapViewOfSection( + [In] IntPtr ProcessHandle, + [In] IntPtr BaseAddress + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtWaitForKeyedEvent( + [In] IntPtr KeyedEventHandle, [In] IntPtr KeyValue, [In] bool Alertable, [In] [Optional] ref long Timeout ); [DllImport("ntdll.dll")] - public static extern int NtWaitHighEventPair( + public static extern NtStatus NtWaitForMultipleObjects( + [In] int Count, + [In] IntPtr[] Handles, + [In] WaitType WaitType, + [In] bool Alertable, + [In] [Optional] ref long Timeout + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtWaitForMultipleObjects32( + [In] int Count, + [In] int[] Handles, + [In] WaitType WaitType, + [In] bool Alertable, + [In] [Optional] ref long Timeout + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtWaitForSingleObject( + [In] IntPtr Handle, + [In] bool Alertable, + [In] [Optional] ref long Timeout + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtWaitHighEventPair( [In] IntPtr EventPairHandle ); [DllImport("ntdll.dll")] - public static extern int NtWaitLowEventPair( + public static extern NtStatus NtWaitLowEventPair( [In] IntPtr EventPairHandle ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtWriteRequestData( + [In] IntPtr PortHandle, + [In] ref PortMessage Message, + [In] int DataEntryIndex, + [In] IntPtr Buffer, + [In] IntPtr BufferSize, + [Out] [Optional] out IntPtr ReturnLength + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus NtWriteVirtualMemory( + [In] IntPtr ProcessHandle, + [In] [Optional] IntPtr BaseAddress, + [In] IntPtr Buffer, + [In] IntPtr BufferSize, + [Out] [Optional] out IntPtr ReturnLength + ); + + #endregion + + #region Run-Time Library + + #region Processes and Threads + + [DllImport("ntdll.dll")] + public static extern void RtlAcquirePebLock(); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlAllocateFromPeb( + [In] int Size, + [Out] out IntPtr Block + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlCreateEnvironment( + [In] bool CloneCurrentEnvironment, + [Out] out IntPtr Environment + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlCreateProcessParameters( + [Out] out IntPtr ProcessParameters, + [In] ref UnicodeString ImagePathName, + [In] ref UnicodeString DllPath, + [In] ref UnicodeString CurrentDirectory, + [In] ref UnicodeString CommandLine, + [In] IntPtr Environment, + [In] ref UnicodeString WindowTitle, + [In] ref UnicodeString DesktopInfo, + [In] ref UnicodeString ShellInfo, + [In] ref UnicodeString RuntimeData + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlCreateUserProcess( + [In] ref UnicodeString NtImagePathName, + [In] int Attributes, + [In] IntPtr ProcessParameters, + [In] IntPtr ProcessSecurityDescriptor, + [In] IntPtr ThreadSecurityDescriptor, + [In] IntPtr ParentProcess, + [In] bool InheritHandles, + [In] IntPtr DebugPort, + [In] IntPtr ExceptionPort, + [In] ref RtlUserProcessInformation ProcessInformation + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlCreateUserThread( + [In] IntPtr Process, + [In] IntPtr ThreadSecurityDescriptor, + [In] bool CreateSuspended, + [In] int StackZeroBits, + [In] [Optional] IntPtr MaximumStackSize, + [In] [Optional] IntPtr InitialStackSize, + [In] IntPtr StartAddress, + [In] IntPtr Parameter, + [Out] out IntPtr Thread, + [Out] out ClientId ClientId + ); + + [DllImport("ntdll.dll")] + public static extern IntPtr RtlDeNormalizeProcessParameters( + [In] IntPtr ProcessParameters + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlDestroyEnvironment( + [In] IntPtr Environment + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlDestroyProcessParameters( + [In] IntPtr ProcessParameters + ); + + [DllImport("ntdll.dll")] + public static extern void RtlExitUserThread( + [In] int ExitStatus + ); + + [DllImport("ntdll.dll")] + public static extern void RtlFreeUserThreadStack( + [In] IntPtr Process, + [In] IntPtr Thread + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlFreeToPeb( + [In] IntPtr Block, + [In] int Size + ); + + [DllImport("ntdll.dll")] + public static extern void RtlInitializeContext( + [In] IntPtr Process, + ref Context Context, + [In] IntPtr Parameter, + [In] IntPtr InitialPc, + [In] IntPtr InitialSp + ); + + [DllImport("ntdll.dll")] + public static extern IntPtr RtlNormalizeProcessParameters( + [In] IntPtr ProcessParameters + ); + + [DllImport("ntdll.dll")] + public static extern int RtlNtStatusToDosError( + [In] NtStatus Status + ); + + [DllImport("ntdll.dll")] + public static extern void RtlReleasePebLock(); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlRemoteCall( + [In] IntPtr Process, + [In] IntPtr Thread, + [In] IntPtr CallSite, + [In] int ArgumentCount, + [In] IntPtr[] Arguments, + [In] bool PassContext, + [In] bool AlreadySuspended + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlSetCurrentEnvironment( + [In] IntPtr Environment, + [Out] out IntPtr PreviousEnvironment + ); + + #endregion + + #region Security ID Routines + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlAllocateAndInitializeSid( + [In] ref SidIdentifierAuthority IdentifierAuthority, + [In] int SubAuthorityCount, + [In] int SubAuthority0, + [In] int SubAuthority1, + [In] int SubAuthority2, + [In] int SubAuthority3, + [In] int SubAuthority4, + [In] int SubAuthority5, + [In] int SubAuthority6, + [In] int SubAuthority7, + [Out] out IntPtr Sid + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlConvertSidToUnicodeString( + ref UnicodeString UnicodeString, + [In] IntPtr Sid, + [In] bool AllocateDestinationString + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlCopySid( + [In] int DestinationSidLength, + [In] IntPtr DestinationSid, + [In] IntPtr SourceSid + ); + + [DllImport("ntdll.dll")] + [return: MarshalAs(UnmanagedType.I1)] + public static extern bool RtlEqualSid( + [In] IntPtr Sid1, + [In] IntPtr Sid2 + ); + + [DllImport("ntdll.dll")] + [return: MarshalAs(UnmanagedType.I1)] + public static extern bool RtlEqualPrefixSid( + [In] IntPtr Sid1, + [In] IntPtr Sid2 + ); + + [DllImport("ntdll.dll")] + public static extern IntPtr RtlFreeSid( + [In] IntPtr Sid + ); + + [DllImport("ntdll.dll")] + public unsafe static extern SidIdentifierAuthority* RtlIdentifierAuthoritySid( + [In] IntPtr Sid + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlInitializeSid( + [In] IntPtr Sid, + [In] ref SidIdentifierAuthority IdentifierAuthority, + [In] int SubAuthorityCount + ); + + [DllImport("ntdll.dll")] + public static extern int RtlLengthRequiredSid( + [In] int SubAuthorityCount + ); + + [DllImport("ntdll.dll")] + public static extern int RtlLengthSid( + [In] IntPtr Sid + ); + + [DllImport("ntdll.dll")] + public unsafe static extern int* RtlSubAuthoritySid( + [In] IntPtr Sid, + [In] int SubAuthority + ); + + [DllImport("ntdll.dll")] + public unsafe static extern byte* RtlSubAuthorityCountSid( + [In] IntPtr Sid + ); + + [DllImport("ntdll.dll")] + [return: MarshalAs(UnmanagedType.I1)] + public static extern bool RtlValidSid( + [In] IntPtr Sid + ); + + #endregion + + #region Strings + + [DllImport("ntdll.dll")] + public static extern int RtlCompareUnicodeString( + [In] ref UnicodeString String1, + [In] ref UnicodeString String2, + [In] bool CaseInSensitive + ); + + [DllImport("ntdll.dll", CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.I1)] + public static extern bool RtlCreateUnicodeString( + [Out] out UnicodeString DestinationString, + [In] string SourceString + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlDuplicateUnicodeString( + [In] RtlDuplicateUnicodeStringFlags Flags, + [In] ref UnicodeString StringIn, + [Out] out UnicodeString StringOut + ); + + [DllImport("ntdll.dll")] + [return: MarshalAs(UnmanagedType.I1)] + public static extern bool RtlEqualUnicodeString( + [In] ref UnicodeString String1, + [In] ref UnicodeString String2, + [In] bool CaseInSensitive + ); + + [DllImport("ntdll.dll")] + public static extern void RtlFreeUnicodeString( + [In] ref UnicodeString UnicodeString + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlHashUnicodeString( + [In] ref UnicodeString String, + [In] bool CaseInSensitive, + [In] HashStringAlgorithm HashAlgorithm, + [Out] out int HashValue + ); + + [DllImport("ntdll.dll")] + [return: MarshalAs(UnmanagedType.I1)] + public static extern bool RtlPrefixUnicodeString( + [In] ref UnicodeString String1, + [In] ref UnicodeString String2, + [In] bool CaseInSensitive + ); + + [DllImport("ntdll.dll")] + public static extern NtStatus RtlValidateUnicodeString( + [In] int Flags, + [In] ref UnicodeString String + ); + + #endregion + + #endregion } } diff --git a/trunk/ProcessHacker.Native/Api/NativeStructs.cs b/trunk/ProcessHacker.Native/Api/NativeStructs.cs new file mode 100644 index 000000000..05e80422c --- /dev/null +++ b/trunk/ProcessHacker.Native/Api/NativeStructs.cs @@ -0,0 +1,1365 @@ +/* + * Process Hacker - + * native API structs + * + * 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 . + */ + +using System; +using System.Runtime.InteropServices; +using ProcessHacker.Native.Objects; + +namespace ProcessHacker.Native.Api +{ + [StructLayout(LayoutKind.Sequential)] + public struct ClientId + { + public ClientId(int processId, int threadId) + { + this.UniqueProcess = new IntPtr(processId); + this.UniqueThread = new IntPtr(threadId); + } + + public IntPtr UniqueProcess; + public IntPtr UniqueThread; + + public int ProcessId { get { return this.UniqueProcess.ToInt32(); } } + public int ThreadId { get { return this.UniqueThread.ToInt32(); } } + } + + // NOTE: This x86 CONTEXT ONLY + [StructLayout(LayoutKind.Sequential)] + public struct Context + { + public ContextFlags ContextFlags; + + public int Dr0; + public int Dr1; + public int Dr2; + public int Dr3; + public int Dr6; + public int Dr7; + + [MarshalAs(UnmanagedType.Struct)] + public FloatingSaveArea FloatSave; + + public int SegGs; + public int SegFs; + public int SegEs; + public int SegDs; + + public int Edi; + public int Esi; + public int Ebx; + public int Edx; + public int Ecx; + public int Eax; + + public int Ebp; + public int Eip; + public int SegCs; + public int EFlags; + public int Esp; + public int SegSs; + + public unsafe fixed byte ExtendedRegisters[Win32.MaximumSupportedExtension]; + } + + [StructLayout(LayoutKind.Sequential)] + public struct EventBasicInformation + { + public EventType EventType; + public int EventState; + } + + [StructLayout(LayoutKind.Sequential)] + public struct FloatingSaveArea + { + public int ControlWord; + public int StatusWord; + public int TagWord; + public int ErrorOffset; + public int ErrorSelector; + public int DataOffset; + public int DataSelector; + + public unsafe fixed byte RegisterArea[Win32.SizeOf80387Registers]; + + public int Cr0NpxState; + } + + [StructLayout(LayoutKind.Sequential)] + public struct GenericMapping + { + public int GenericRead; + public int GenericWrite; + public int GenericExecute; + public int GenericAll; + } + + [StructLayout(LayoutKind.Sequential)] + public struct InitialTeb + { + public struct OldInitialTebStruct + { + public IntPtr OldStackBase; + public IntPtr OldStackLimit; + } + + public OldInitialTebStruct OldInitialTeb; + public IntPtr StackBase; + public IntPtr StackLimit; + public IntPtr StackAllocationBase; + } + + [StructLayout(LayoutKind.Sequential)] + public struct IoCounters + { + public ulong ReadOperationCount; + public ulong WriteOperationCount; + public ulong OtherOperationCount; + public ulong ReadTransferCount; + public ulong WriteTransferCount; + public ulong OtherTransferCount; + } + + [StructLayout(LayoutKind.Explicit)] + public struct IoStatusBlock + { + [FieldOffset(0)] + public NtStatus status; + [FieldOffset(0)] + public IntPtr Pointer; + + // HACK, offset is 8 on x64 + [FieldOffset(4)] + public IntPtr Information; + } + + [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; + } + + [StructLayout(LayoutKind.Sequential)] + public struct JobSetArray + { + public IntPtr JobHandle; + public uint MemberLevel; + public int Flags; // Unused + } + + [StructLayout(LayoutKind.Explicit, Size = 8)] + public struct LargeInteger + { + [FieldOffset(0)] + public Int64 QuadPart; + [FieldOffset(0)] + public UInt32 LowPart; + [FieldOffset(4)] + public UInt32 HighPart; + } + + [StructLayout(LayoutKind.Sequential)] + public struct LdrModule + { + public ListEntry InLoadOrderModuleList; + public ListEntry InMemoryOrderModuleList; + public ListEntry InInitializationOrderModuleList; + public IntPtr BaseAddress; + public IntPtr EntryPoint; + public int SizeOfImage; + public UnicodeString FullDllName; + public UnicodeString BaseDllName; + public int Flags; + public short LoadCount; + public short TlsIndex; + public ListEntry HashTableEntry; + public int TimeDateStamp; + } + + [StructLayout(LayoutKind.Sequential)] + public struct ListEntry + { + public IntPtr Flink; + public IntPtr Blink; + } + + [StructLayout(LayoutKind.Sequential)] + public struct Luid + { + public int LowPart; + public int HighPart; + + public Luid Allocate() + { + NtStatus status; + Luid luid; + + if ((status = Win32.NtAllocateLocallyUniqueId(out luid)) >= NtStatus.Error) + Win32.ThrowLastError(status); + + return luid; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct MutantBasicInformation + { + public int CurrentCount; + public byte OwnedByCaller; + public byte AbandonedState; + } + + [StructLayout(LayoutKind.Sequential)] + public struct ObjectAttributes : IDisposable + { + public ObjectAttributes( + string objectName, + ObjectFlags attributes, + DirectoryHandle rootDirectory + ) + { + this.Length = Marshal.SizeOf(typeof(ObjectAttributes)); + this.RootDirectory = IntPtr.Zero; + this.ObjectName = IntPtr.Zero; + this.SecurityDescriptor = IntPtr.Zero; + this.SecurityQualityOfService = IntPtr.Zero; + + if (objectName != null) + { + UnicodeString unicodeString = new UnicodeString(objectName); + IntPtr unicodeStringMemory = Marshal.AllocHGlobal(Marshal.SizeOf(unicodeString)); + + Marshal.StructureToPtr(unicodeString, unicodeStringMemory, false); + this.ObjectName = unicodeStringMemory; + } + + this.Attributes = attributes; + + if (rootDirectory != null) + this.RootDirectory = rootDirectory; + } + + public int Length; + public IntPtr RootDirectory; + public IntPtr ObjectName; + public ObjectFlags Attributes; + public IntPtr SecurityDescriptor; + public IntPtr SecurityQualityOfService; + + public void Dispose() + { + if (this.ObjectName == IntPtr.Zero) + return; + + UnicodeString unicodeString = + (UnicodeString)Marshal.PtrToStructure(this.ObjectName, typeof(UnicodeString)); + + unicodeString.Dispose(); + Marshal.FreeHGlobal(this.ObjectName); + + this.ObjectName = IntPtr.Zero; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct ObjectBasicInformation + { + public uint Attributes; + public int GrantedAccess; + public uint HandleCount; + public uint PointerCount; + public uint PagedPoolUsage; + public uint NonPagedPoolUsage; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] + public uint[] Reserved; + + public uint NameInformationLength; + public uint TypeInformationLength; + public uint SecurityDescriptorLength; + public ulong CreateTime; + } + + [StructLayout(LayoutKind.Sequential)] + public struct ObjectDirectoryInformation + { + public UnicodeString Name; + public UnicodeString TypeName; + } + + [StructLayout(LayoutKind.Sequential)] + public struct ObjectNameInformation + { + public UnicodeString Name; + } + + [StructLayout(LayoutKind.Sequential)] + public struct ObjectTypeInformation + { + public UnicodeString Name; + public int TotalNumberOfObjects; + public int TotalNumberOfHandles; + public int TotalPagedPoolUsage; + public int TotalNonPagedPoolUsage; + public int TotalNamePoolUsage; + public int TotalHandleTableUsage; + public int HighWaterNumberOfObjects; + public int HighWaterNumberOfHandles; + public int HighWaterPagedPoolUsage; + public int HighWaterNonPagedPoolUsage; + public int HighWaterNamePoolUsage; + public int HighWaterHandleTableUsage; + public int InvalidAttributes; + public GenericMapping GenericMapping; + public int ValidAccess; + public byte SecurityRequired; + public byte MaintainHandleCount; + public ushort MaintainTypeList; + public PoolType PoolType; + public int PagedPoolUsage; + public int NonPagedPoolUsage; + } + + [StructLayout(LayoutKind.Sequential)] + public struct PebLdrData + { + public int Length; + public char Initialized; + public int SsHandle; + public ListEntry InLoadOrderModuleList; + public ListEntry InMemoryOrderModuleList; + public ListEntry InInitializationOrderModuleList; + } + + [StructLayout(LayoutKind.Sequential)] + public struct PooledUsageAndLimits + { + public int PeakPagedPoolUsage; + public int PagedPoolUsage; + public int PagedPoolLimit; + public int PeakNonPagedPoolUsage; + public int NonPagedPoolUsage; + public int NonPagedPoolLimit; + public int PeakPagefileUsage; + public int PagefileUsage; + public int PagefileLimit; + } + + [StructLayout(LayoutKind.Explicit)] + public struct PortMessage + { + [FieldOffset(0)] + public short DataLength; + [FieldOffset(2)] + public short TotalLength; + [FieldOffset(0)] + public int Length; + + [FieldOffset(4)] + public short Type; + [FieldOffset(6)] + public short DataInfoOffset; + [FieldOffset(4)] + public int ZeroInit; + + [FieldOffset(8)] + public ClientId ClientId; + [FieldOffset(8)] + public double DoNotUseThisField; + + [FieldOffset(16)] + public int MessageId; + + [FieldOffset(20)] + public IntPtr ClientViewSize; + [FieldOffset(20)] + public int CallbackId; + } + + [StructLayout(LayoutKind.Sequential)] + public struct PortView + { + public int Length; + public IntPtr SectionHandle; + public int SectionOffset; + public IntPtr ViewSize; + public IntPtr ViewBase; + public IntPtr ViewRemoteBase; + } + + [StructLayout(LayoutKind.Sequential)] + public struct ProcessBasicInformation + { + public int ExitStatus; + public IntPtr PebBaseAddress; + public int AffinityMask; + public int BasePriority; + public int UniqueProcessId; + public int InheritedFromUniqueProcessId; + } + + [StructLayout(LayoutKind.Sequential)] + public struct QuotaLimits + { + public int PagedPoolLimit; + public int NonPagedPoolLimit; + public int MinimumWorkingSetSize; + public int MaximumWorkingSetSizse; + public int PagefileLimit; + public long TimeLimit; + } + + [StructLayout(LayoutKind.Sequential)] + public struct RemotePortView + { + public int Length; + public IntPtr ViewSize; + public IntPtr ViewBase; + } + + [StructLayout(LayoutKind.Sequential)] + public struct RtlUserProcessInformation + { + public int Length; + public IntPtr Process; + public IntPtr Thread; + public ClientId ClientId; + public SectionImageInformation ImageInformation; + } + + [StructLayout(LayoutKind.Sequential)] + public struct RtlUserProcessParameters + { + public struct CurDir + { + public UnicodeString DosPath; + public IntPtr Handle; + } + + public struct RtlDriveLetterCurDir + { + public ushort Flags; + public ushort Length; + public uint TimeStamp; + public IntPtr DosPath; + } + + public int MaximumLength; + public int Length; + + public RtlUserProcessFlags Flags; + public int DebugFlags; + + public IntPtr ConsoleHandle; + public int ConsoleFlags; + public IntPtr StandardInput; + public IntPtr StandardOutput; + public IntPtr StandardError; + + public CurDir CurrentDirectory; + public UnicodeString DllPath; + public UnicodeString ImagePathName; + public UnicodeString CommandLine; + public IntPtr Environment; + + public int StartingX; + public int StartingY; + public int CountX; + public int CountY; + public int CountCharsX; + public int CountCharsY; + public int FillAttribute; + + public int WindowFlags; + public int ShowWindowFlags; + public UnicodeString WindowTitle; + public UnicodeString DesktopInfo; + public UnicodeString ShellInfo; + public UnicodeString RuntimeData; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] + public RtlDriveLetterCurDir[] CurrentDirectories; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SectionBasicInformation + { + public int Unknown; + public SectionAttributes SectionAttributes; + public long SectionSize; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SectionImageInformation + { + public IntPtr TransferAddress; + public int StackZeroBits; + public IntPtr StackReserved; + public IntPtr StackCommit; + public int ImageSubsystem; + public short SubSystemVersionLow; + public short SubSystemVersionHigh; + public int GpValue; + public short ImageCharacteristics; + public short DllCharacteristics; + public int ImageMachineType; + [MarshalAs(UnmanagedType.I1)] + public bool ImageContainsCode; + [MarshalAs(UnmanagedType.I1)] + public bool Spare1; + public int LoaderFlags; + public int ImageFileSize; + public int Reserved; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SecurityQualityOfService + { + public SecurityQualityOfService( + SecurityImpersonationLevel impersonationLevel, + bool dynamicTracking, + bool effectiveOnly + ) + { + this.Length = Marshal.SizeOf(typeof(SecurityQualityOfService)); + this.ImpersonationLevel = impersonationLevel; + this.ContextTrackingMode = dynamicTracking; + this.EffectiveOnly = effectiveOnly; + } + + public int Length; + public SecurityImpersonationLevel ImpersonationLevel; + [MarshalAs(UnmanagedType.I1)] + public bool ContextTrackingMode; // True for dynamic tracking, false for static tracking + [MarshalAs(UnmanagedType.I1)] + public bool EffectiveOnly; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SemaphoreBasicInformation + { + public int CurrentCount; + public int MaximumCount; + } + + [StructLayout(LayoutKind.Sequential)] + public struct Sid + { + public byte Revision; + public byte SubAuthorityCount; + public SidIdentifierAuthority IdentifierAuthority; + + // Array of ULONG follows + } + + [StructLayout(LayoutKind.Sequential)] + public struct SidAndAttributes + { + public IntPtr Sid; // ptr to a SID object + public SidAttributes Attributes; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SidIdentifierAuthority + { + public unsafe fixed byte Value[6]; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SystemBasicInformation + { + public int Reserved; + public int TimerResolution; + public int PageSize; + public int NumberOfPhysicalPages; + public int LowestPhysicalPageNumber; + public int HighestPhysicalPageNumber; + public int AllocationGranularity; + public int MinimumUserModeAddress; + public int MaximumUserModeAddress; + public int ActiveProcessorsAffinityMask; + public byte NumberOfProcessors; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SystemCacheInformation + { + /// + /// The size of the system working set, in bytes. + /// + public int SystemCacheWsSize; + public int SystemCacheWsPeakSize; + public int SystemCacheWsFaults; + + /// + /// Measured in pages. + /// + public int SystemCacheWsMinimum; + + /// + /// Measured in pages. + /// + public int SystemCacheWsMaximum; + public int TransitionSharedPages; + public int TransitionSharedPagesPeak; + public int Reserved1; + public int Reserved2; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SystemExtendedThreadInformation + { + public SystemThreadInformation ThreadInfo; + public int StackBase; // 16 + public int StackLimit; + public int Win32StartAddress; + public int TebAddress; // Vista+ + public int Unused1; + public int Unused2; + public int Unused3; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SystemLoadAndCallImage + { + public UnicodeString ModuleName; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SystemObjectTypeInformation + { + public int NextEntryOffset; + public UnicodeString Name; + public int ObjectCount; + public int HandleCount; + public int TypeNumber; + public int InvalidAttributes; + public GenericMapping GenericMapping; + public int ValidAccessMask; + public PoolType PoolType; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SystemPerformanceInformation + { + /// + /// The total idle time of all processors in units of 100-nanoseconds. + /// + public long IdleTime; + + /// + /// Total bytes read by calls to NtReadFile. + /// + public long IoReadTransferCount; + + /// + /// Total bytes written by calls to NtWriteFile. + /// + public long IoWriteTransferCount; + + /// + /// Total bytes transferred by other I/O operations. + /// + public long IoOtherTransferCount; + + /// + /// Number of calls to NtReadFile. + /// + public int IoReadOperationCount; + + /// + /// Number of calls to NtWriteFile. + /// + public int IoWriteOperationCount; + + /// + /// Number of calls to other I/O functions. + /// + public int IoOtherOperationCount; + + /// + /// The number of pages of physical memory available. + /// + public int AvailablePages; + + /// + /// The number of pages of committed virtual memory. + /// + public int CommittedPages; + + /// + /// The number of pages of virtual memory that could be committed + /// without extending the system's pagefiles. + /// + public int CommitLimit; + + /// + /// The peak number of pages of committed virtual memory. + /// + public int PeakCommitment; + + /// + /// The total number of soft and hard page faults. + /// + public int PageFaults; + + /// + /// The number of copy-on-write page faults. + /// + public int CopyOnWriteFaults; + + /// + /// The number of soft page faults. + /// + public int TransitionFaults; + + /// + /// Something that the Native API reference book doesn't have. + /// + public int CacheTransitionFaults; + + /// + /// The number of demand zero faults. + /// + public int DemandZeroFaults; + + /// + /// The number of pages read from disk to resolve page faults. + /// + public int PagesRead; + + /// + /// The number of read operations initiated to resolve page faults. + /// + public int PagesReadIos; + + public int CacheRead; + public int CacheReadIos; + + /// + /// The number of pages written to the system's pagefiles. + /// + public int PagefilePagesWritten; + + /// + /// The number of write operations performed on the system's pagefiles. + /// + public int PagefilePagesWriteIos; + + /// + /// The number of pages written to mapped files. + /// + public int MappedFilePagesWritten; + + /// + /// The number of write operations performed on mapped files. + /// + public int MappedFilePageWriteIos; + + /// + /// The number of pages used by the paged pool. + /// + public int PagedPoolUsage; + + /// + /// The number of pages used by the non-paged pool. + /// + public int NonPagedPoolUsage; + + /// + /// The number of allocations made from the paged pool. + /// + public int PagedPoolAllocs; + + /// + /// The number of allocations returned to the paged pool. + /// + public int PagedPoolFrees; + + /// + /// The number of allocations made from the non-paged pool. + /// + public int NonPagedPoolAllocs; + + /// + /// The number of allocations returned to the non-paged pool. + /// + public int NonPagedPoolFrees; + + /// + /// The number of available System Page Table Entries. + /// + public int FreeSystemPtes; + + /// + /// The number of pages of pageable OS code and data in physical + /// memory. + /// + public int SystemCodePages; + + /// + /// The number of pages of pageable driver code and data. + /// + public int TotalSystemDriverPages; + + /// + /// The number of pages of OS driver code and data. + /// + public int TotalSystemCodePages; + + /// + /// The number of times an allocation could be statisfied by one of the + /// small non-paged lookaside lists. + /// + public int SmallNonPagedPoolLookasideListAllocateHits; + + /// + /// The number of times an allocation could be statisfied by one of the + /// small paged lookaside lists. + /// + public int SmallPagedPoolLookasideAllocateHits; + + public int Reserved3; + + /// + /// The number of pages of the system cache in physical memory. + /// + public int SystemCachePages; + + /// + /// The number of pages of the paged pool in physical memory. + /// + public int PagedPoolPages; + + /// + /// The number of pages of pageable driver code and data in physical memory. + /// + public int SystemDriverPages; + + /// + /// The number of asynchronous fast read operations. + /// + public int FastReadNoWait; + + /// + /// The number of synchronous fast read operations. + /// + public int FastReadWait; + + /// + /// The number of fast read operations not possible because of resource + /// conflicts. + /// + public int FastReadResourceMiss; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int FastReadNotPossible; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int FastMdlReadNoWait; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int FastMdlReadWait; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int FastMdlReadResourceMiss; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int FastMdlReadNotPossible; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int MapDataNoWait; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int MapDataWait; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int MapDataNoWaitMiss; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int MapDataWaitMiss; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int PinMappedDataCount; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int PinReadNoWait; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int PinReadWait; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int PinReadNoWaitMiss; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int PinReadWaitMiss; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int CopyReadNoWait; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int CopyReadWait; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int CopyReadNoWaitMiss; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int CopyReadWaitMiss; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int MdlReadNoWait; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int MdlReadWait; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int MdlReadNoWaitMiss; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int MdlReadWaitMiss; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int ReadAheadIos; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int LazyWriteIos; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int LazyWritePages; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int DataFlushes; + + /// + /// Google Books won't let me read the page containing the description + /// for this field! + /// + public int DataPages; + + /// + /// The total number of context switches. + /// + public int ContextSwitches; + + /// + /// The number of first level translation buffer fills. + /// + public int FirstLevelTbFills; + + /// + /// The number of second level translation buffer fills. + /// + public int SecondLevelTbFills; + + /// + /// The number of system calls executed. + /// + public int SystemCalls; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SystemProcessInformation + { + public int NextEntryOffset; + public int NumberOfThreads; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] + public long[] Spare; + + public long CreateTime; // 8 + public long UserTime; + public long KernelTime; + public UnicodeString ImageName; + public int BasePriority; + public int ProcessId; + public int InheritedFromProcessId; + public int HandleCount; + public int SessionId; + public int PageDirectoryBase; + public VmCountersEx VirtualMemoryCounters; + public IoCounters IoCounters; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SystemProcessorPerformanceInformation + { + public long IdleTime; + public long KernelTime; + public long UserTime; + public long DpcTime; + public long InterruptTime; + public int InterruptCount; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SystemSessionProcessInformation + { + public int SessionId; + public int BufferLength; + public IntPtr Buffer; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SystemThreadInformation + { + public long KernelTime; + public long UserTime; + public long CreateTime; + public int WaitTime; + public int StartAddress; + public ClientId ClientId; + public int Priority; + public int BasePriority; + public int ContextSwitchCount; // 12 + public int State; // 13 + public KWaitReason WaitReason; // 14 + } + + [StructLayout(LayoutKind.Sequential)] + public struct ThreadBasicInformation + { + public uint ExitStatus; + public IntPtr TebBaseAddress; + public ClientId ClientId; + public uint AffinityMask; + public uint Priority; + public uint BasePriority; + } + + [StructLayout(LayoutKind.Sequential)] + public struct TimerBasicInformation + { + public LargeInteger RemainingTime; + [MarshalAs(UnmanagedType.I1)] + public bool TimerState; + } + + [StructLayout(LayoutKind.Sequential)] + public struct TokenGroups + { + public uint GroupCount; + + [MarshalAs(UnmanagedType.ByValArray)] + public SidAndAttributes[] Groups; + } + + [StructLayout(LayoutKind.Sequential)] + public struct TokenPrivileges + { + public uint PrivilegeCount; + + [MarshalAs(UnmanagedType.ByValArray)] + public LuidAndAttributes[] Privileges; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct TokenSource + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] + public string SourceName; + + public Luid SourceIdentifier; + } + + [StructLayout(LayoutKind.Sequential)] + public struct TokenUser + { + public SidAndAttributes User; + } + + [StructLayout(LayoutKind.Sequential)] + public struct UnicodeString : IComparable, IEquatable, IDisposable + { + public UnicodeString(string str) + { + UnicodeString newString; + + if (!Win32.RtlCreateUnicodeString(out newString, str)) + throw new OutOfMemoryException(); + + this.Length = newString.Length; + this.MaximumLength = newString.MaximumLength; + this.Buffer = newString.Buffer; + } + + public ushort Length; + public ushort MaximumLength; + public IntPtr Buffer; + + public int CompareTo(UnicodeString unicodeString, bool caseInsensitive) + { + return Win32.RtlCompareUnicodeString(ref this, ref unicodeString, caseInsensitive); + } + + public int CompareTo(UnicodeString unicodeString) + { + return this.CompareTo(unicodeString, false); + } + + public void Dispose() + { + if (this.Buffer == IntPtr.Zero) + return; + + Win32.RtlFreeUnicodeString(ref this); + this.Buffer = IntPtr.Zero; + } + + /// + /// Copies the string to a newly allocated string. + /// + public UnicodeString Duplicate() + { + NtStatus status; + UnicodeString newString; + + if ((status = Win32.RtlDuplicateUnicodeString( + RtlDuplicateUnicodeStringFlags.AllocateNullString | + RtlDuplicateUnicodeStringFlags.NullTerminate, + ref this, out newString)) >= NtStatus.Error) + Win32.ThrowLastError(status); + + return newString; + } + + public bool Equals(UnicodeString unicodeString, bool caseInsensitive) + { + return Win32.RtlEqualUnicodeString(ref this, ref unicodeString, caseInsensitive); + } + + public bool Equals(UnicodeString unicodeString) + { + return this.Equals(unicodeString, false); + } + + public int Hash(HashStringAlgorithm algorithm, bool caseInsensitive) + { + NtStatus status; + int hash; + + if ((status = Win32.RtlHashUnicodeString(ref this, + caseInsensitive, algorithm, out hash)) >= NtStatus.Error) + Win32.ThrowLastError(status); + + return hash; + } + + public int Hash(HashStringAlgorithm algorithm) + { + return this.Hash(algorithm, false); + } + + public int Hash() + { + return this.Hash(HashStringAlgorithm.Default); + } + + public override int GetHashCode() + { + return this.Hash(); + } + + public string Read() + { + return Utils.ReadUnicodeString(this); + } + + public string Read(ProcessHandle processHandle) + { + return Utils.ReadUnicodeString(processHandle, this); + } + + public bool StartsWith(UnicodeString unicodeString, bool caseInsensitive) + { + return Win32.RtlPrefixUnicodeString(ref this, ref unicodeString, caseInsensitive); + } + + public bool StartsWith(UnicodeString unicodeString) + { + return this.StartsWith(unicodeString, false); + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct VmCounters + { + public int PeakVirtualSize; + public int VirtualSize; + public int PageFaultCount; + public int PeakWorkingSetSize; + public int WorkingSetSize; + public int QuotaPeakPagedPoolUsage; + public int QuotaPagedPoolUsage; + public int QuotaPeakNonPagedPoolUsage; + public int QuotaNonPagedPoolUsage; + public int PagefileUsage; + public int PeakPagefileUsage; + } + + [StructLayout(LayoutKind.Sequential)] + public struct VmCountersEx + { + public int PeakVirtualSize; + public int VirtualSize; + public int PageFaultCount; + public int PeakWorkingSetSize; + public int WorkingSetSize; + public int QuotaPeakPagedPoolUsage; + public int QuotaPagedPoolUsage; + public int QuotaPeakNonPagedPoolUsage; + public int QuotaNonPagedPoolUsage; + public int PagefileUsage; + public int PeakPagefileUsage; + public int PrivateBytes; + } +} diff --git a/trunk/ProcessHacker.Native/Api/NtStatus.cs b/trunk/ProcessHacker.Native/Api/NtStatus.cs new file mode 100644 index 000000000..eab6ca4bd --- /dev/null +++ b/trunk/ProcessHacker.Native/Api/NtStatus.cs @@ -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, + } +} diff --git a/trunk/ProcessHacker.Native/Api/Structs.cs b/trunk/ProcessHacker.Native/Api/Structs.cs index 7c5baa808..8ba5c316e 100644 --- a/trunk/ProcessHacker.Native/Api/Structs.cs +++ b/trunk/ProcessHacker.Native/Api/Structs.cs @@ -46,51 +46,6 @@ namespace ProcessHacker.Native.Api public string CatalogFile; } - [StructLayout(LayoutKind.Sequential)] - public struct ClientId - { - public int UniqueProcess; - public int UniqueThread; - } - - // NOTE: This x86 CONTEXT ONLY!!! - [StructLayout(LayoutKind.Sequential)] - public struct Context - { - public ContextFlags ContextFlags; - - public int Dr0; - public int Dr1; - public int Dr2; - public int Dr3; - public int Dr6; - public int Dr7; - - [MarshalAs(UnmanagedType.Struct)] - public FloatingSaveArea FloatSave; - - public int SegGs; - public int SegFs; - public int SegEs; - public int SegDs; - - public int Edi; - public int Esi; - public int Ebx; - public int Edx; - public int Ecx; - public int Eax; - - public int Ebp; - public int Eip; - public int SegCs; - public int EFlags; - public int Esp; - public int SegSs; - - public unsafe fixed byte ExtendedRegisters[Win32.MaximumSupportedExtension]; - } - [StructLayout(LayoutKind.Sequential)] public struct EnumServiceStatus { @@ -117,24 +72,6 @@ namespace ProcessHacker.Native.Api public ServiceStatusProcess ServiceStatusProcess; } - [StructLayout(LayoutKind.Sequential)] - public struct EventBasicInformation - { - public EventType EventType; - public int EventState; - } - - [StructLayout(LayoutKind.Explicit, Size = 8)] - public struct LargeInteger - { - [FieldOffset(0)] - public Int64 QuadPart; - [FieldOffset(0)] - public UInt32 LowPart; - [FieldOffset(4)] - public UInt32 HighPart; - } - [StructLayout(LayoutKind.Sequential)] public struct FileTime { @@ -150,22 +87,6 @@ namespace ProcessHacker.Native.Api } } - [StructLayout(LayoutKind.Sequential)] - public struct FloatingSaveArea - { - public int ControlWord; - public int StatusWord; - public int TagWord; - public int ErrorOffset; - public int ErrorSelector; - public int DataOffset; - public int DataSelector; - - public unsafe fixed byte RegisterArea[Win32.SizeOf80387Registers]; - - public int Cr0NpxState; - } - [StructLayout(LayoutKind.Sequential)] public struct FpoData { @@ -178,15 +99,6 @@ namespace ProcessHacker.Native.Api public long Part2; } - [StructLayout(LayoutKind.Sequential)] - public struct GenericMapping - { - public int GenericRead; - public int GenericWrite; - public int GenericExecute; - public int GenericAll; - } - [StructLayout(LayoutKind.Sequential)] public struct HeapEntry32 { @@ -220,17 +132,6 @@ namespace ProcessHacker.Native.Api public long Address; } - [StructLayout(LayoutKind.Sequential)] - public struct IoCounters - { - public ulong ReadOperationCount; - public ulong WriteOperationCount; - public ulong OtherOperationCount; - public ulong ReadTransferCount; - public ulong WriteTransferCount; - public ulong OtherTransferCount; - } - [StructLayout(LayoutKind.Sequential)] public struct KdHelp64 { @@ -247,49 +148,6 @@ namespace ProcessHacker.Native.Api public long[] Reserved; } - [StructLayout(LayoutKind.Sequential)] - public struct LdrModule - { - public ListEntry InLoadOrderModuleList; - public ListEntry InMemoryOrderModuleList; - public ListEntry InInitializationOrderModuleList; - public IntPtr BaseAddress; - public IntPtr EntryPoint; - public int SizeOfImage; - public UnicodeString FullDllName; - public UnicodeString BaseDllName; - public int Flags; - public short LoadCount; - public short TlsIndex; - public ListEntry HashTableEntry; - public int TimeDateStamp; - } - - [StructLayout(LayoutKind.Sequential)] - public struct ListEntry - { - public IntPtr Flink; - public IntPtr Blink; - } - - [StructLayout(LayoutKind.Sequential)] - public struct Luid - { - public int LowPart; - public int HighPart; - - public Luid Allocate() - { - int status; - Luid luid; - - if ((status = Win32.NtAllocateLocallyUniqueId(out luid)) < 0) - Win32.ThrowLastError(status); - - return luid; - } - } - [StructLayout(LayoutKind.Sequential)] public struct LuidAndAttributes { @@ -455,136 +313,6 @@ namespace ProcessHacker.Native.Api public uint Flags; } - [StructLayout(LayoutKind.Sequential)] - public struct MutantBasicInformation - { - public int CurrentCount; - public byte OwnedByCaller; - public byte AbandonedState; - } - - [StructLayout(LayoutKind.Sequential)] - public struct ObjectAttributes : IDisposable - { - public int Length; - public IntPtr RootDirectory; - public IntPtr ObjectName; - public ObjectFlags Attributes; - public IntPtr SecurityDescriptor; - public IntPtr SecurityQualityOfService; - - public void Dispose() - { - if (this.ObjectName == IntPtr.Zero) - return; - - UnicodeString unicodeString = - (UnicodeString)Marshal.PtrToStructure(this.ObjectName, typeof(UnicodeString)); - - unicodeString.Dispose(); - Marshal.FreeHGlobal(this.ObjectName); - - this.ObjectName = IntPtr.Zero; - } - - public static ObjectAttributes Create( - string objectName, - ObjectFlags attributes, - DirectoryHandle rootDirectory - ) - { - ObjectAttributes oa = new ObjectAttributes(); - - oa.Length = Marshal.SizeOf(oa); - - if (objectName != null) - { - UnicodeString unicodeString = UnicodeString.Create(objectName); - IntPtr unicodeStringMemory = Marshal.AllocHGlobal(Marshal.SizeOf(unicodeString)); - - Marshal.StructureToPtr(unicodeString, unicodeStringMemory, false); - oa.ObjectName = unicodeStringMemory; - } - - oa.Attributes = attributes; - - if (rootDirectory != null) - oa.RootDirectory = rootDirectory; - - return oa; - } - } - - [StructLayout(LayoutKind.Sequential)] - public struct ObjectBasicInformation - { - public uint Attributes; - public int GrantedAccess; - public uint HandleCount; - public uint PointerCount; - public uint PagedPoolUsage; - public uint NonPagedPoolUsage; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] - public uint[] Reserved; - - public uint NameInformationLength; - public uint TypeInformationLength; - public uint SecurityDescriptorLength; - public ulong CreateTime; - } - - [StructLayout(LayoutKind.Sequential)] - public struct ObjectDirectoryInformation - { - public UnicodeString Name; - public UnicodeString TypeName; - } - - [StructLayout(LayoutKind.Sequential)] - public struct ObjectNameInformation - { - public UnicodeString Name; - } - - [StructLayout(LayoutKind.Sequential)] - public struct ObjectTypeInformation - { - public UnicodeString Name; - public int TotalNumberOfObjects; - public int TotalNumberOfHandles; - public int TotalPagedPoolUsage; - public int TotalNonPagedPoolUsage; - public int TotalNamePoolUsage; - public int TotalHandleTableUsage; - public int HighWaterNumberOfObjects; - public int HighWaterNumberOfHandles; - public int HighWaterPagedPoolUsage; - public int HighWaterNonPagedPoolUsage; - public int HighWaterNamePoolUsage; - public int HighWaterHandleTableUsage; - public int InvalidAttributes; - public GenericMapping GenericMapping; - public int ValidAccess; - public byte SecurityRequired; - public byte MaintainHandleCount; - public ushort MaintainTypeList; - public PoolType PoolType; - public int PagedPoolUsage; - public int NonPagedPoolUsage; - } - - [StructLayout(LayoutKind.Sequential)] - public struct PebLdrData - { - public int Length; - public char Initialized; - public int SsHandle; - public ListEntry InLoadOrderModuleList; - public ListEntry InMemoryOrderModuleList; - public ListEntry InInitializationOrderModuleList; - } - [StructLayout(LayoutKind.Sequential)] public struct PerformanceInformation { @@ -604,31 +332,6 @@ namespace ProcessHacker.Native.Api public int ThreadCount; } - [StructLayout(LayoutKind.Sequential)] - public struct PooledUsageAndLimits - { - public int PeakPagedPoolUsage; - public int PagedPoolUsage; - public int PagedPoolLimit; - public int PeakNonPagedPoolUsage; - public int NonPagedPoolUsage; - public int NonPagedPoolLimit; - public int PeakPagefileUsage; - public int PagefileUsage; - public int PagefileLimit; - } - - [StructLayout(LayoutKind.Sequential)] - public struct ProcessBasicInformation - { - public int ExitStatus; - public IntPtr PebBaseAddress; - public int AffinityMask; - public int BasePriority; - public int UniqueProcessId; - public int InheritedFromUniqueProcessId; - } - [StructLayout(LayoutKind.Sequential)] public struct ProcessEntry32 { @@ -678,17 +381,6 @@ namespace ProcessHacker.Native.Api public string DisplayName; } - [StructLayout(LayoutKind.Sequential)] - public struct QuotaLimits - { - public int PagedPoolLimit; - public int NonPagedPoolLimit; - public int MinimumWorkingSetSize; - public int MaximumWorkingSetSizse; - public int PagefileLimit; - public long TimeLimit; - } - [StructLayout(LayoutKind.Sequential)] public struct ScAction { @@ -696,39 +388,6 @@ namespace ProcessHacker.Native.Api public int Delay; } - [StructLayout(LayoutKind.Sequential)] - public struct SectionBasicInformation - { - public int Unknown; - public SectionAttributes SectionAttributes; - public long SectionSize; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SectionImageInformation - { - public int EntryPoint; - public int StackZeroBits; - public int StackReserved; - public int StackCommit; - public int ImageSubsystem; - public short SubSystemVersionLow; - public short SubSystemVersionHigh; - public int Unknown1; - public int ImageCharacteristics; - public int ImageMachineType; - public int Unknown2; - public int Unknown3; - public int Unknown4; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SemaphoreBasicInformation - { - public int CurrentCount; - public int MaximumCount; - } - [StructLayout(LayoutKind.Sequential)] public struct ServiceDescription { @@ -795,13 +454,6 @@ namespace ProcessHacker.Native.Api public string szTypeName; } - [StructLayout(LayoutKind.Sequential)] - public struct SidAndAttributes - { - public IntPtr SID; // ptr to a SID object - public SidAttributes Attributes; - } - [StructLayout(LayoutKind.Sequential)] public struct StackFrame64 { @@ -875,545 +527,6 @@ namespace ProcessHacker.Native.Api public char Name; } - [StructLayout(LayoutKind.Sequential)] - public struct SystemBasicInformation - { - public int Reserved; - public int TimerResolution; - public int PageSize; - public int NumberOfPhysicalPages; - public int LowestPhysicalPageNumber; - public int HighestPhysicalPageNumber; - public int AllocationGranularity; - public int MinimumUserModeAddress; - public int MaximumUserModeAddress; - public int ActiveProcessorsAffinityMask; - public byte NumberOfProcessors; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SystemCacheInformation - { - /// - /// The size of the system working set, in bytes. - /// - public int SystemCacheWsSize; - public int SystemCacheWsPeakSize; - public int SystemCacheWsFaults; - - /// - /// Measured in pages. - /// - public int SystemCacheWsMinimum; - - /// - /// Measured in pages. - /// - public int SystemCacheWsMaximum; - public int TransitionSharedPages; - public int TransitionSharedPagesPeak; - public int Reserved1; - public int Reserved2; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SystemExtendedThreadInformation - { - public SystemThreadInformation ThreadInfo; - public int StackBase; // 16 - public int StackLimit; - public int Win32StartAddress; - public int TebAddress; // Vista+ - public int Unused1; - public int Unused2; - public int Unused3; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SystemLoadAndCallImage - { - public UnicodeString ModuleName; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SystemObjectTypeInformation - { - public int NextEntryOffset; - public UnicodeString Name; - public int ObjectCount; - public int HandleCount; - public int TypeNumber; - public int InvalidAttributes; - public GenericMapping GenericMapping; - public int ValidAccessMask; - public PoolType PoolType; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SystemPerformanceInformation - { - /// - /// The total idle time of all processors in units of 100-nanoseconds. - /// - public long IdleTime; - - /// - /// Total bytes read by calls to NtReadFile. - /// - public long IoReadTransferCount; - - /// - /// Total bytes written by calls to NtWriteFile. - /// - public long IoWriteTransferCount; - - /// - /// Total bytes transferred by other I/O operations. - /// - public long IoOtherTransferCount; - - /// - /// Number of calls to NtReadFile. - /// - public int IoReadOperationCount; - - /// - /// Number of calls to NtWriteFile. - /// - public int IoWriteOperationCount; - - /// - /// Number of calls to other I/O functions. - /// - public int IoOtherOperationCount; - - /// - /// The number of pages of physical memory available. - /// - public int AvailablePages; - - /// - /// The number of pages of committed virtual memory. - /// - public int CommittedPages; - - /// - /// The number of pages of virtual memory that could be committed - /// without extending the system's pagefiles. - /// - public int CommitLimit; - - /// - /// The peak number of pages of committed virtual memory. - /// - public int PeakCommitment; - - /// - /// The total number of soft and hard page faults. - /// - public int PageFaults; - - /// - /// The number of copy-on-write page faults. - /// - public int CopyOnWriteFaults; - - /// - /// The number of soft page faults. - /// - public int TransitionFaults; - - /// - /// Something that the Native API reference book doesn't have. - /// - public int CacheTransitionFaults; - - /// - /// The number of demand zero faults. - /// - public int DemandZeroFaults; - - /// - /// The number of pages read from disk to resolve page faults. - /// - public int PagesRead; - - /// - /// The number of read operations initiated to resolve page faults. - /// - public int PagesReadIos; - - public int CacheRead; - public int CacheReadIos; - - /// - /// The number of pages written to the system's pagefiles. - /// - public int PagefilePagesWritten; - - /// - /// The number of write operations performed on the system's pagefiles. - /// - public int PagefilePagesWriteIos; - - /// - /// The number of pages written to mapped files. - /// - public int MappedFilePagesWritten; - - /// - /// The number of write operations performed on mapped files. - /// - public int MappedFilePageWriteIos; - - /// - /// The number of pages used by the paged pool. - /// - public int PagedPoolUsage; - - /// - /// The number of pages used by the non-paged pool. - /// - public int NonPagedPoolUsage; - - /// - /// The number of allocations made from the paged pool. - /// - public int PagedPoolAllocs; - - /// - /// The number of allocations returned to the paged pool. - /// - public int PagedPoolFrees; - - /// - /// The number of allocations made from the non-paged pool. - /// - public int NonPagedPoolAllocs; - - /// - /// The number of allocations returned to the non-paged pool. - /// - public int NonPagedPoolFrees; - - /// - /// The number of available System Page Table Entries. - /// - public int FreeSystemPtes; - - /// - /// The number of pages of pageable OS code and data in physical - /// memory. - /// - public int SystemCodePages; - - /// - /// The number of pages of pageable driver code and data. - /// - public int TotalSystemDriverPages; - - /// - /// The number of pages of OS driver code and data. - /// - public int TotalSystemCodePages; - - /// - /// The number of times an allocation could be statisfied by one of the - /// small non-paged lookaside lists. - /// - public int SmallNonPagedPoolLookasideListAllocateHits; - - /// - /// The number of times an allocation could be statisfied by one of the - /// small paged lookaside lists. - /// - public int SmallPagedPoolLookasideAllocateHits; - - public int Reserved3; - - /// - /// The number of pages of the system cache in physical memory. - /// - public int SystemCachePages; - - /// - /// The number of pages of the paged pool in physical memory. - /// - public int PagedPoolPages; - - /// - /// The number of pages of pageable driver code and data in physical memory. - /// - public int SystemDriverPages; - - /// - /// The number of asynchronous fast read operations. - /// - public int FastReadNoWait; - - /// - /// The number of synchronous fast read operations. - /// - public int FastReadWait; - - /// - /// The number of fast read operations not possible because of resource - /// conflicts. - /// - public int FastReadResourceMiss; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int FastReadNotPossible; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int FastMdlReadNoWait; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int FastMdlReadWait; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int FastMdlReadResourceMiss; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int FastMdlReadNotPossible; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int MapDataNoWait; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int MapDataWait; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int MapDataNoWaitMiss; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int MapDataWaitMiss; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int PinMappedDataCount; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int PinReadNoWait; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int PinReadWait; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int PinReadNoWaitMiss; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int PinReadWaitMiss; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int CopyReadNoWait; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int CopyReadWait; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int CopyReadNoWaitMiss; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int CopyReadWaitMiss; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int MdlReadNoWait; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int MdlReadWait; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int MdlReadNoWaitMiss; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int MdlReadWaitMiss; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int ReadAheadIos; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int LazyWriteIos; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int LazyWritePages; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int DataFlushes; - - /// - /// Google Books won't let me read the page containing the description - /// for this field! - /// - public int DataPages; - - /// - /// The total number of context switches. - /// - public int ContextSwitches; - - /// - /// The number of first level translation buffer fills. - /// - public int FirstLevelTbFills; - - /// - /// The number of second level translation buffer fills. - /// - public int SecondLevelTbFills; - - /// - /// The number of system calls executed. - /// - public int SystemCalls; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SystemProcessInformation - { - public int NextEntryOffset; - public int NumberOfThreads; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] - public long[] Spare; - - public long CreateTime; // 8 - public long UserTime; - public long KernelTime; - public UnicodeString ImageName; - public int BasePriority; - public int ProcessId; - public int InheritedFromProcessId; - public int HandleCount; - public int SessionId; - public int PageDirectoryBase; - public VmCountersEx VirtualMemoryCounters; - public IoCounters IoCounters; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SystemProcessorPerformanceInformation - { - public long IdleTime; - public long KernelTime; - public long UserTime; - public long DpcTime; - public long InterruptTime; - public int InterruptCount; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SystemSessionProcessInformation - { - public int SessionId; - public int BufferLength; - public IntPtr Buffer; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SystemThreadInformation - { - public long KernelTime; - public long UserTime; - public long CreateTime; - public int WaitTime; - public int StartAddress; - public ClientId ClientId; - public int Priority; - public int BasePriority; - public int ContextSwitchCount; // 12 - public int State; // 13 - public KWaitReason WaitReason; // 14 - } - - [StructLayout(LayoutKind.Sequential)] - public struct ThreadBasicInformation - { - public uint ExitStatus; - public IntPtr TebBaseAddress; - public ClientId ClientId; - public uint AffinityMask; - public uint Priority; - public uint BasePriority; - } - [StructLayout(LayoutKind.Sequential)] public struct ThreadEntry32 { @@ -1429,117 +542,6 @@ namespace ProcessHacker.Native.Api public string szExeFile; } - [StructLayout(LayoutKind.Sequential)] - public struct TimerBasicInformation - { - public LargeInteger RemainingTime; - [MarshalAs(UnmanagedType.I1)] - public bool TimerState; - } - - [StructLayout(LayoutKind.Sequential)] - public struct TokenGroups - { - public uint GroupCount; - - [MarshalAs(UnmanagedType.ByValArray)] - public SidAndAttributes[] Groups; - } - - [StructLayout(LayoutKind.Sequential)] - public struct TokenPrivileges - { - public uint PrivilegeCount; - - [MarshalAs(UnmanagedType.ByValArray)] - public LuidAndAttributes[] Privileges; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - public struct TokenSource - { - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] - public string SourceName; - - public Luid SourceIdentifier; - } - - [StructLayout(LayoutKind.Sequential)] - public struct TokenUser - { - public SidAndAttributes User; - } - - [StructLayout(LayoutKind.Sequential)] - public struct UnicodeString : IDisposable - { - public ushort Length; - public ushort MaximumLength; - public IntPtr Buffer; - - public static UnicodeString Create(string str) - { - UnicodeString unicodeString = new UnicodeString(); - - unicodeString.Buffer = Marshal.StringToHGlobalUni(str); - unicodeString.Length = (ushort)(str.Length * 2); - unicodeString.MaximumLength = unicodeString.Length; - - return unicodeString; - } - - public void Dispose() - { - if (this.Buffer == IntPtr.Zero) - return; - - Marshal.FreeHGlobal(this.Buffer); - } - - public string Read() - { - return Utils.ReadUnicodeString(this); - } - - public string Read(ProcessHandle processHandle) - { - return Utils.ReadUnicodeString(processHandle, this); - } - } - - [StructLayout(LayoutKind.Sequential)] - public struct VmCounters - { - public int PeakVirtualSize; - public int VirtualSize; - public int PageFaultCount; - public int PeakWorkingSetSize; - public int WorkingSetSize; - public int QuotaPeakPagedPoolUsage; - public int QuotaPagedPoolUsage; - public int QuotaPeakNonPagedPoolUsage; - public int QuotaNonPagedPoolUsage; - public int PagefileUsage; - public int PeakPagefileUsage; - } - - [StructLayout(LayoutKind.Sequential)] - public struct VmCountersEx - { - public int PeakVirtualSize; - public int VirtualSize; - public int PageFaultCount; - public int PeakWorkingSetSize; - public int WorkingSetSize; - public int QuotaPeakPagedPoolUsage; - public int QuotaPagedPoolUsage; - public int QuotaPeakNonPagedPoolUsage; - public int QuotaNonPagedPoolUsage; - public int PagefileUsage; - public int PeakPagefileUsage; - public int PrivateBytes; - } - [StructLayout(LayoutKind.Sequential)] public struct WindowClass { diff --git a/trunk/ProcessHacker.Native/KProcessHacker.cs b/trunk/ProcessHacker.Native/KProcessHacker.cs index 1369fb986..84c73d100 100644 --- a/trunk/ProcessHacker.Native/KProcessHacker.cs +++ b/trunk/ProcessHacker.Native/KProcessHacker.cs @@ -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); } diff --git a/trunk/ProcessHacker.Native/Memory/PebMemoryAlloc.cs b/trunk/ProcessHacker.Native/Memory/PebMemoryAlloc.cs new file mode 100644 index 000000000..ed99578d6 --- /dev/null +++ b/trunk/ProcessHacker.Native/Memory/PebMemoryAlloc.cs @@ -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 . + */ + +using System; +using System.Collections.Generic; +using System.Text; +using ProcessHacker.Native.Api; + +namespace ProcessHacker.Native.Memory +{ + /// + /// Represents a memory allocation from the PEB. + /// + 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); + } + } +} diff --git a/trunk/ProcessHacker.Native/Memory/SectionView.cs b/trunk/ProcessHacker.Native/Memory/SectionView.cs new file mode 100644 index 000000000..23aa1817d --- /dev/null +++ b/trunk/ProcessHacker.Native/Memory/SectionView.cs @@ -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 . + */ + +using System; +using System.Collections.Generic; +using System.Text; +using ProcessHacker.Native.Api; +using ProcessHacker.Native.Objects; + +namespace ProcessHacker.Native.Memory +{ + /// + /// Represents a mapped view of a section. + /// + 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(); + } + } +} diff --git a/trunk/ProcessHacker.Native/Objects/DebugObjectHandle.cs b/trunk/ProcessHacker.Native/Objects/DebugObjectHandle.cs index d6ba7a603..9cc223db4 100644 --- a/trunk/ProcessHacker.Native/Objects/DebugObjectHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/DebugObjectHandle.cs @@ -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); diff --git a/trunk/ProcessHacker.Native/Objects/DirectoryHandle.cs b/trunk/ProcessHacker.Native/Objects/DirectoryHandle.cs index cc89bd76b..8691ccd30 100644 --- a/trunk/ProcessHacker.Native/Objects/DirectoryHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/DirectoryHandle.cs @@ -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 . + */ + +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) { } /// @@ -79,7 +101,7 @@ namespace ProcessHacker.Native.Objects /// An array of object entries. public ObjectEntry[] Query() { - int status; + NtStatus status; int context = 0; int retLength; var objectList = new List(); @@ -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); diff --git a/trunk/ProcessHacker.Native/Objects/EventHandle.cs b/trunk/ProcessHacker.Native/Objects/EventHandle.cs index 90583c76e..52e7897c6 100644 --- a/trunk/ProcessHacker.Native/Objects/EventHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/EventHandle.cs @@ -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 . + */ + +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 /// public void SetBoostPriority() { - int status; + NtStatus status; - if ((status = Win32.NtSetEventBoostPriority(this)) < 0) + if ((status = Win32.NtSetEventBoostPriority(this)) >= NtStatus.Error) Win32.ThrowLastError(status); } } diff --git a/trunk/ProcessHacker.Native/Objects/EventPairHandle.cs b/trunk/ProcessHacker.Native/Objects/EventPairHandle.cs index f8d778556..fd70ebf3a 100644 --- a/trunk/ProcessHacker.Native/Objects/EventPairHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/EventPairHandle.cs @@ -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 . + */ + +using System; using System.Collections.Generic; using System.Text; using ProcessHacker.Native.Api; @@ -18,7 +40,7 @@ namespace ProcessHacker.Native.Objects /// A handle to an event pair. public static EventPairHandle Create(EventPairAccess access) { - return Create(access, null, null); + return Create(access, null, 0, null); } /// @@ -33,15 +55,15 @@ namespace ProcessHacker.Native.Objects /// The directory in which to place the event pair. This can be null. /// /// A handle to an event pair. - 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. /// The directory object in which the event pair can be found. /// The desired access to the event pair. - 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) { } /// @@ -92,9 +114,9 @@ namespace ProcessHacker.Native.Objects /// 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 /// 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 /// 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 /// 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 /// 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 /// public void WaitLow() { - int status; + NtStatus status; - if ((status = Win32.NtWaitLowEventPair(this)) < 0) + if ((status = Win32.NtWaitLowEventPair(this)) >= NtStatus.Error) Win32.ThrowLastError(status); } } diff --git a/trunk/ProcessHacker.Native/Objects/ISynchronizable.cs b/trunk/ProcessHacker.Native/Objects/ISynchronizable.cs index 958bf4a2b..fdd029ced 100644 --- a/trunk/ProcessHacker.Native/Objects/ISynchronizable.cs +++ b/trunk/ProcessHacker.Native/Objects/ISynchronizable.cs @@ -19,7 +19,8 @@ * You should have received a copy of the GNU General Public License * along with Process Hacker. If not, see . */ - + +using System; using ProcessHacker.Native.Api; namespace ProcessHacker.Native.Objects @@ -29,7 +30,11 @@ namespace ProcessHacker.Native.Objects /// 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); } } diff --git a/trunk/ProcessHacker.Native/Objects/JobObjectHandle.cs b/trunk/ProcessHacker.Native/Objects/JobObjectHandle.cs index ea628d9f4..0caf49fb5 100644 --- a/trunk/ProcessHacker.Native/Objects/JobObjectHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/JobObjectHandle.cs @@ -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; - } } diff --git a/trunk/ProcessHacker.Native/Objects/KeyedEventHandle.cs b/trunk/ProcessHacker.Native/Objects/KeyedEventHandle.cs index 655a0bf24..cd47a2040 100644 --- a/trunk/ProcessHacker.Native/Objects/KeyedEventHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/KeyedEventHandle.cs @@ -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 . + */ + +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 { + 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); + } } } diff --git a/trunk/ProcessHacker.Native/Objects/LsaPolicyHandle.cs b/trunk/ProcessHacker.Native/Objects/LsaPolicyHandle.cs index 598ebef4d..db74f11d6 100644 --- a/trunk/ProcessHacker.Native/Objects/LsaPolicyHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/LsaPolicyHandle.cs @@ -37,11 +37,11 @@ namespace ProcessHacker.Native.Objects /// The desired access to the policy. 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; diff --git a/trunk/ProcessHacker.Native/Objects/MutantHandle.cs b/trunk/ProcessHacker.Native/Objects/MutantHandle.cs index da0c8b89a..53cf82ff7 100644 --- a/trunk/ProcessHacker.Native/Objects/MutantHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/MutantHandle.cs @@ -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 . + */ + +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; diff --git a/trunk/ProcessHacker.Native/Objects/PortHandle.cs b/trunk/ProcessHacker.Native/Objects/PortHandle.cs new file mode 100644 index 000000000..c61621cec --- /dev/null +++ b/trunk/ProcessHacker.Native/Objects/PortHandle.cs @@ -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 . + */ + +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 + { + 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) + { } + } +} diff --git a/trunk/ProcessHacker.Native/Objects/ProcessHandle.cs b/trunk/ProcessHacker.Native/Objects/ProcessHandle.cs index 8ffe1fed8..b01926d8b 100644 --- a/trunk/ProcessHacker.Native/Objects/ProcessHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/ProcessHandle.cs @@ -55,41 +55,71 @@ namespace ProcessHacker.Native.Objects /// Return true to continue enumerating; return false to stop. 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); + } + /// /// 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) { } - /// - /// Creates a new process handle. - /// - /// The ID of the process to open. - public ProcessHandle(int pid) - : this(pid, ProcessAccess.All) - { } - /// /// Creates a new process handle. /// @@ -156,6 +178,66 @@ namespace ProcessHacker.Native.Objects Win32.ThrowLastError(); } + /// + /// Creates a new process handle. + /// + /// The ID of the process to open. + 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) + { } + /// /// Allocates a memory region in the process' virtual memory. /// @@ -241,9 +323,9 @@ namespace ProcessHacker.Native.Objects /// A handle to a debug object. 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 /// A PROCESS_BASIC_INFORMATION structure. 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 /// A DEPStatus enum. 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 /// A file name, in device/native format. 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(); @@ -763,7 +845,7 @@ namespace ProcessHacker.Native.Objects /// A process handle. 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 /// A thread handle. 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 /// The debug object which was used to debug the process. 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); } } diff --git a/trunk/ProcessHacker.Native/Objects/ProfileHandle.cs b/trunk/ProcessHacker.Native/Objects/ProfileHandle.cs new file mode 100644 index 000000000..0d3088065 --- /dev/null +++ b/trunk/ProcessHacker.Native/Objects/ProfileHandle.cs @@ -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 . + */ + +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 + { + // TODO: Implement basics + } +} diff --git a/trunk/ProcessHacker.Native/Objects/SectionHandle.cs b/trunk/ProcessHacker.Native/Objects/SectionHandle.cs index c0aa82e5e..153e67e62 100644 --- a/trunk/ProcessHacker.Native/Objects/SectionHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/SectionHandle.cs @@ -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 { - 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); + } } } diff --git a/trunk/ProcessHacker.Native/Objects/SemaphoreHandle.cs b/trunk/ProcessHacker.Native/Objects/SemaphoreHandle.cs index eee6e859d..9e2d5cb07 100644 --- a/trunk/ProcessHacker.Native/Objects/SemaphoreHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/SemaphoreHandle.cs @@ -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 . + */ + +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; diff --git a/trunk/ProcessHacker.Native/Objects/SymbolicLinkHandle.cs b/trunk/ProcessHacker.Native/Objects/SymbolicLinkHandle.cs index 79b355e5f..ba6cb5c42 100644 --- a/trunk/ProcessHacker.Native/Objects/SymbolicLinkHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/SymbolicLinkHandle.cs @@ -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 . + */ + +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(); diff --git a/trunk/ProcessHacker.Native/Objects/ThreadHandle.cs b/trunk/ProcessHacker.Native/Objects/ThreadHandle.cs index 5ec614016..114910401 100644 --- a/trunk/ProcessHacker.Native/Objects/ThreadHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/ThreadHandle.cs @@ -33,6 +33,44 @@ namespace ProcessHacker.Native.Objects /// public class ThreadHandle : Win32Handle, 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); + } + /// /// 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) + { } + /// /// Puts the thread in an alerted state. /// 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 /// 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 /// A THREAD_BASIC_INFORMATION structure. 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 /// A system call number. 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); + } + /// /// Gets whether the system will break (crash) upon the thread terminating. /// @@ -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); } /// @@ -392,10 +525,10 @@ namespace ProcessHacker.Native.Objects /// 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 /// 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; diff --git a/trunk/ProcessHacker.Native/Objects/TimerHandle.cs b/trunk/ProcessHacker.Native/Objects/TimerHandle.cs index 441be7e10..6019be92d 100644 --- a/trunk/ProcessHacker.Native/Objects/TimerHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/TimerHandle.cs @@ -9,8 +9,6 @@ namespace ProcessHacker.Native.Objects { public class TimerHandle : Win32Handle { - 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; diff --git a/trunk/ProcessHacker.Native/Objects/TokenHandle.cs b/trunk/ProcessHacker.Native/Objects/TokenHandle.cs index 8eec6f2be..bf3536f7c 100644 --- a/trunk/ProcessHacker.Native/Objects/TokenHandle.cs +++ b/trunk/ProcessHacker.Native/Objects/TokenHandle.cs @@ -353,7 +353,7 @@ namespace ProcessHacker.Native.Objects TokenUser user = data.ReadStruct(); - return new WindowsSid(user.User.SID); + return new WindowsSid(user.User.Sid); } } diff --git a/trunk/ProcessHacker.Native/Objects/Win32Handle.cs b/trunk/ProcessHacker.Native/Objects/Win32Handle.cs index f0157656a..39ae2469a 100644 --- a/trunk/ProcessHacker.Native/Objects/Win32Handle.cs +++ b/trunk/ProcessHacker.Native/Objects/Win32Handle.cs @@ -31,6 +31,56 @@ namespace ProcessHacker.Native.Objects /// public class Win32Handle : Win32Handle { + 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; + } + /// /// Creates a new, invalid handle. You must set the handle using the Handle property. /// @@ -206,7 +256,7 @@ namespace ProcessHacker.Native.Objects /// A string. 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(); @@ -238,9 +288,9 @@ namespace ProcessHacker.Native.Objects /// 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 /// 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 /// /// Signals the object and waits for another. /// - 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); } /// /// Waits for the object. /// - public WaitResult Wait() + public NtStatus Wait() { - return Win32.WaitForSingleObject(this, 0xffffffff); + return this.Wait(-1); } - /// - /// Waits for the object with a timeout. - /// - /// The timeout of the wait. - 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; } /// diff --git a/trunk/ProcessHacker.Native/ProcessHacker.Native.csproj b/trunk/ProcessHacker.Native/ProcessHacker.Native.csproj index f3892963e..b0458a5ed 100644 --- a/trunk/ProcessHacker.Native/ProcessHacker.Native.csproj +++ b/trunk/ProcessHacker.Native/ProcessHacker.Native.csproj @@ -42,7 +42,11 @@ + + + + @@ -50,6 +54,8 @@ + + @@ -57,6 +63,8 @@ + + diff --git a/trunk/ProcessHacker.Native/Win32.cs b/trunk/ProcessHacker.Native/Win32.cs index 7a17489b3..2b0c5e6ea 100644 --- a/trunk/ProcessHacker.Native/Win32.cs +++ b/trunk/ProcessHacker.Native/Win32.cs @@ -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 /// 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); } } diff --git a/trunk/ProcessHacker.Native/Windows.cs b/trunk/ProcessHacker.Native/Windows.cs index 724740105..6e3ca28e8 100644 --- a/trunk/ProcessHacker.Native/Windows.cs +++ b/trunk/ProcessHacker.Native/Windows.cs @@ -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(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(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(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(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(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); } } diff --git a/trunk/ProcessHacker/Components/HandleList.cs b/trunk/ProcessHacker/Components/HandleList.cs index 8f74f5d97..986c300cf 100644 --- a/trunk/ProcessHacker/Components/HandleList.cs +++ b/trunk/ProcessHacker/Components/HandleList.cs @@ -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(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(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(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(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(phandle, handle, SectionAccess.Query); + var dupHandle = new Win32Handle(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(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) diff --git a/trunk/ProcessHacker/Components/JobProperties.cs b/trunk/ProcessHacker/Components/JobProperties.cs index 6355430f5..b70210ab4 100644 --- a/trunk/ProcessHacker/Components/JobProperties.cs +++ b/trunk/ProcessHacker/Components/JobProperties.cs @@ -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; diff --git a/trunk/ProcessHacker/Components/TokenGroupsList.cs b/trunk/ProcessHacker/Components/TokenGroupsList.cs index 60067c6fc..8825c086e 100644 --- a/trunk/ProcessHacker/Components/TokenGroupsList.cs +++ b/trunk/ProcessHacker/Components/TokenGroupsList.cs @@ -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))); diff --git a/trunk/ProcessHacker/Forms/HandleFilterWindow.cs b/trunk/ProcessHacker/Forms/HandleFilterWindow.cs index d39b9eb2c..6182ece76 100644 --- a/trunk/ProcessHacker/Forms/HandleFilterWindow.cs +++ b/trunk/ProcessHacker/Forms/HandleFilterWindow.cs @@ -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]); } } diff --git a/trunk/ProcessHacker/Forms/TerminatorWindow.cs b/trunk/ProcessHacker/Forms/TerminatorWindow.cs index b8c8de816..93c874f0a 100644 --- a/trunk/ProcessHacker/Forms/TerminatorWindow.cs +++ b/trunk/ProcessHacker/Forms/TerminatorWindow.cs @@ -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 { } diff --git a/trunk/ProcessHacker/Providers/ProcessSystemProvider.cs b/trunk/ProcessHacker/Providers/ProcessSystemProvider.cs index 52191eca1..b5aff8381 100644 --- a/trunk/ProcessHacker/Providers/ProcessSystemProvider.cs +++ b/trunk/ProcessHacker/Providers/ProcessSystemProvider.cs @@ -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;