2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/ob/obhandle.c
5 * PURPOSE: Manages all functions related to the Object Manager handle
6 * implementation, including creating and destroying handles
7 * and/or handle tables, duplicating objects, and setting the
8 * permanent or temporary flags.
9 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
11 * Thomas Weidenmueller (w3seek@reactos.org)
14 /* INCLUDES ******************************************************************/
20 PHANDLE_TABLE ObpKernelHandleTable
= NULL
;
21 ULONG ObpAccessProtectCloseBit
= MAXIMUM_ALLOWED
;
23 #define TAG_OB_HANDLE 'dHbO'
25 /* PRIVATE FUNCTIONS *********************************************************/
29 ObReferenceProcessHandleTable(IN PEPROCESS Process
)
31 PHANDLE_TABLE HandleTable
= NULL
;
33 /* Lock the process */
34 if (ExAcquireRundownProtection(&Process
->RundownProtect
))
36 /* Get the handle table */
37 HandleTable
= Process
->ObjectTable
;
40 /* No table, release the lock */
41 ExReleaseRundownProtection(&Process
->RundownProtect
);
45 /* Return the handle table */
51 ObDereferenceProcessHandleTable(IN PEPROCESS Process
)
53 /* Release the process lock */
54 ExReleaseRundownProtection(&Process
->RundownProtect
);
59 ObGetProcessHandleCount(IN PEPROCESS Process
)
62 PHANDLE_TABLE HandleTable
;
66 /* Ensure the handle table doesn't go away while we use it */
67 HandleTable
= ObReferenceProcessHandleTable(Process
);
69 if (HandleTable
!= NULL
)
71 /* Count the number of handles the process has */
72 HandleCount
= HandleTable
->HandleCount
;
74 /* Let the handle table go */
75 ObDereferenceProcessHandleTable(Process
);
79 /* No handle table, no handles */
88 ObpReferenceProcessObjectByHandle(IN HANDLE Handle
,
90 IN PHANDLE_TABLE HandleTable
,
91 IN KPROCESSOR_MODE AccessMode
,
93 OUT POBJECT_HANDLE_INFORMATION HandleInformation
,
94 OUT PACCESS_MASK AuditMask
)
96 PHANDLE_TABLE_ENTRY HandleEntry
;
97 POBJECT_HEADER ObjectHeader
;
98 ACCESS_MASK GrantedAccess
;
100 PETHREAD Thread
= PsGetCurrentThread();
106 /* Check if this is a special handle */
107 if (HandleToLong(Handle
) < 0)
109 /* Check if the caller wants the current process */
110 if (Handle
== NtCurrentProcess())
112 /* Return handle info */
113 HandleInformation
->HandleAttributes
= 0;
114 HandleInformation
->GrantedAccess
= Process
->GrantedAccess
;
119 /* Reference ourselves */
120 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Process
);
121 InterlockedIncrement(&ObjectHeader
->PointerCount
);
123 /* Return the pointer */
125 ASSERT(*Object
!= NULL
);
126 return STATUS_SUCCESS
;
129 /* Check if the caller wants the current thread */
130 if (Handle
== NtCurrentThread())
132 /* Return handle information */
133 HandleInformation
->HandleAttributes
= 0;
134 HandleInformation
->GrantedAccess
= Thread
->GrantedAccess
;
136 /* Reference ourselves */
137 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Thread
);
138 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
, 1);
143 /* Return the pointer */
145 ASSERT(*Object
!= NULL
);
146 return STATUS_SUCCESS
;
149 /* This is a kernel handle... do we have access? */
150 if (AccessMode
== KernelMode
)
152 /* Use the kernel handle table and get the actual handle value */
153 Handle
= ObKernelHandleToHandle(Handle
);
154 HandleTable
= ObpKernelHandleTable
;
158 /* This is an illegal attempt to access a kernel handle */
159 return STATUS_INVALID_HANDLE
;
163 /* Enter a critical region while we touch the handle table */
164 ASSERT(HandleTable
!= NULL
);
165 KeEnterCriticalRegion();
167 /* Get the handle entry */
168 HandleEntry
= ExMapHandleToPointer(HandleTable
, Handle
);
171 /* Get the object header and validate the type*/
172 ObjectHeader
= ObpGetHandleObject(HandleEntry
);
174 /* Get the granted access and validate it */
175 GrantedAccess
= HandleEntry
->GrantedAccess
;
177 /* Mask out the internal attributes */
178 Attributes
= HandleEntry
->ObAttributes
& OBJ_HANDLE_ATTRIBUTES
;
180 /* Fill out the information */
181 HandleInformation
->HandleAttributes
= Attributes
;
182 HandleInformation
->GrantedAccess
= GrantedAccess
;
184 /* No audit mask (FIXME!) */
187 /* Return the pointer */
188 *Object
= &ObjectHeader
->Body
;
190 /* Add a reference */
191 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
, 1);
193 /* Unlock the handle */
194 ExUnlockHandleTableEntry(HandleTable
, HandleEntry
);
195 KeLeaveCriticalRegion();
198 ASSERT(*Object
!= NULL
);
199 return STATUS_SUCCESS
;
204 Status
= STATUS_INVALID_HANDLE
;
207 /* Return failure status */
208 KeLeaveCriticalRegion();
214 ObpEnumFindHandleProcedure(IN PHANDLE_TABLE_ENTRY HandleEntry
,
218 POBJECT_HEADER ObjectHeader
;
219 ACCESS_MASK GrantedAccess
;
220 ULONG HandleAttributes
;
221 POBP_FIND_HANDLE_DATA FindData
= Context
;
223 /* Get the object header */
224 ObjectHeader
= ObpGetHandleObject(HandleEntry
);
226 /* Make sure it's valid and matching */
227 if ((FindData
->ObjectHeader
) && (FindData
->ObjectHeader
!= ObjectHeader
))
233 /* Now attempt to match the object type */
234 if ((FindData
->ObjectType
) && (FindData
->ObjectType
!= ObjectHeader
->Type
))
240 /* Check if we have extra information */
241 if (FindData
->HandleInformation
)
243 /* Get the granted access and attributes */
244 GrantedAccess
= HandleEntry
->GrantedAccess
;
245 HandleAttributes
= HandleEntry
->ObAttributes
& OBJ_HANDLE_ATTRIBUTES
;
247 /* Attempt to match them */
248 if ((FindData
->HandleInformation
->HandleAttributes
!= HandleAttributes
) ||
249 (FindData
->HandleInformation
->GrantedAccess
!= GrantedAccess
))
256 /* We have a match */
260 POBJECT_HANDLE_COUNT_ENTRY
262 ObpInsertHandleCount(IN POBJECT_HEADER ObjectHeader
)
264 POBJECT_HEADER_HANDLE_INFO HandleInfo
;
265 POBJECT_HANDLE_COUNT_ENTRY FreeEntry
;
266 POBJECT_HANDLE_COUNT_DATABASE HandleDatabase
, OldHandleDatabase
;
269 OBJECT_HANDLE_COUNT_DATABASE SingleDatabase
;
272 /* Get the handle info */
273 HandleInfo
= OBJECT_HEADER_TO_HANDLE_INFO(ObjectHeader
);
274 if (!HandleInfo
) return NULL
;
276 /* Check if we only have one entry */
277 if (ObjectHeader
->Flags
& OB_FLAG_SINGLE_PROCESS
)
279 /* Fill out the single entry */
280 SingleDatabase
.CountEntries
= 1;
281 SingleDatabase
.HandleCountEntries
[0] = HandleInfo
->SingleEntry
;
283 /* Use this as the old size */
284 OldHandleDatabase
= &SingleDatabase
;
285 OldSize
= sizeof(SingleDatabase
);
287 /* Now we'll have two entries, and an entire DB */
289 Size
= sizeof(OBJECT_HANDLE_COUNT_DATABASE
) +
290 ((i
- 1) * sizeof(OBJECT_HANDLE_COUNT_ENTRY
));
294 /* We already have a DB, get the information from it */
295 OldHandleDatabase
= HandleInfo
->HandleCountDatabase
;
296 i
= OldHandleDatabase
->CountEntries
;
297 OldSize
= sizeof(OBJECT_HANDLE_COUNT_DATABASE
) +
298 ((i
- 1) * sizeof(OBJECT_HANDLE_COUNT_ENTRY
));
300 /* Add 4 more entries */
302 Size
= OldSize
+ (4 * sizeof(OBJECT_HANDLE_COUNT_ENTRY
));
305 /* Allocate the DB */
306 HandleDatabase
= ExAllocatePoolWithTag(PagedPool
, Size
, TAG_OB_HANDLE
);
307 if (!HandleDatabase
) return NULL
;
309 /* Copy the old database */
310 RtlCopyMemory(HandleDatabase
, OldHandleDatabase
, OldSize
);
312 /* Check if we he had a single entry before */
313 if (ObjectHeader
->Flags
& OB_FLAG_SINGLE_PROCESS
)
315 /* Now we have more */
316 ObjectHeader
->Flags
&= ~OB_FLAG_SINGLE_PROCESS
;
320 /* Otherwise we had a DB, free it */
321 ExFreePoolWithTag(OldHandleDatabase
, TAG_OB_HANDLE
);
324 /* Find the end of the copy and zero out the new data */
325 FreeEntry
= (PVOID
)((ULONG_PTR
)HandleDatabase
+ OldSize
);
326 RtlZeroMemory(FreeEntry
, Size
- OldSize
);
328 /* Set the new information and return the free entry */
329 HandleDatabase
->CountEntries
= i
;
330 HandleInfo
->HandleCountDatabase
= HandleDatabase
;
336 ObpIncrementHandleDataBase(IN POBJECT_HEADER ObjectHeader
,
337 IN PEPROCESS Process
,
338 IN OUT PULONG NewProcessHandleCount
)
340 POBJECT_HEADER_HANDLE_INFO HandleInfo
;
341 POBJECT_HANDLE_COUNT_ENTRY HandleEntry
, FreeEntry
= NULL
;
342 POBJECT_HANDLE_COUNT_DATABASE HandleDatabase
;
346 /* Get the handle info and check if we only have one entry */
347 HandleInfo
= OBJECT_HEADER_TO_HANDLE_INFO(ObjectHeader
);
348 if (ObjectHeader
->Flags
& OB_FLAG_SINGLE_PROCESS
)
350 /* Check if the entry is free */
351 if (!HandleInfo
->SingleEntry
.HandleCount
)
354 HandleInfo
->SingleEntry
.HandleCount
= 1;
355 HandleInfo
->SingleEntry
.Process
= Process
;
357 /* Return success and 1 handle */
358 *NewProcessHandleCount
= 1;
359 return STATUS_SUCCESS
;
361 else if (HandleInfo
->SingleEntry
.Process
== Process
)
363 /* Busy entry, but same process */
364 *NewProcessHandleCount
= ++HandleInfo
->SingleEntry
.HandleCount
;
365 return STATUS_SUCCESS
;
369 /* Insert a new entry */
370 FreeEntry
= ObpInsertHandleCount(ObjectHeader
);
371 if (!FreeEntry
) return STATUS_INSUFFICIENT_RESOURCES
;
372 ASSERT(!FreeEntry
->Process
);
373 ASSERT(!FreeEntry
->HandleCount
);
376 FreeEntry
->Process
= Process
;
377 FreeEntry
->HandleCount
= 1;
379 /* Return success and 1 handle */
380 *NewProcessHandleCount
= 1;
381 return STATUS_SUCCESS
;
385 /* We have a database instead */
386 HandleDatabase
= HandleInfo
->HandleCountDatabase
;
389 /* Get the entries and loop them */
390 i
= HandleDatabase
->CountEntries
;
391 HandleEntry
= &HandleDatabase
->HandleCountEntries
[0];
394 /* Check if this is a match */
395 if (HandleEntry
->Process
== Process
)
397 /* Found it, get the process handle count */
398 *NewProcessHandleCount
= ++HandleEntry
->HandleCount
;
399 return STATUS_SUCCESS
;
401 else if (!HandleEntry
->HandleCount
)
403 /* Found a free entry */
404 FreeEntry
= HandleEntry
;
412 /* Check if we couldn't find a free entry */
416 FreeEntry
= ObpInsertHandleCount(ObjectHeader
);
417 if (!FreeEntry
) return STATUS_INSUFFICIENT_RESOURCES
;
418 ASSERT(!FreeEntry
->Process
);
419 ASSERT(!FreeEntry
->HandleCount
);
422 /* Fill out the entry */
423 FreeEntry
->Process
= Process
;
424 FreeEntry
->HandleCount
= 1;
425 *NewProcessHandleCount
= 1;
428 /* Return success if we got here */
429 return STATUS_SUCCESS
;
434 ObpChargeQuotaForObject(IN POBJECT_HEADER ObjectHeader
,
435 IN POBJECT_TYPE ObjectType
,
436 OUT PBOOLEAN NewObject
)
438 POBJECT_HEADER_QUOTA_INFO ObjectQuota
;
439 ULONG PagedPoolCharge
, NonPagedPoolCharge
;
441 /* Get quota information */
442 ObjectQuota
= OBJECT_HEADER_TO_QUOTA_INFO(ObjectHeader
);
445 /* Check if this is a new object */
446 if (ObjectHeader
->Flags
& OB_FLAG_CREATE_INFO
)
448 /* Remove the flag */
449 ObjectHeader
->Flags
&= ~ OB_FLAG_CREATE_INFO
;
452 /* We have a quota, get the charges */
453 PagedPoolCharge
= ObjectQuota
->PagedPoolCharge
;
454 NonPagedPoolCharge
= ObjectQuota
->NonPagedPoolCharge
;
458 /* Get it from the object type */
459 PagedPoolCharge
= ObjectType
->TypeInfo
.DefaultPagedPoolCharge
;
460 NonPagedPoolCharge
= ObjectType
->TypeInfo
.DefaultNonPagedPoolCharge
;
463 /* Charge the quota */
464 ObjectHeader
->QuotaBlockCharged
= (PVOID
)1;
465 DPRINT("FIXME: Should charge: %lx %lx\n", PagedPoolCharge
, NonPagedPoolCharge
);
467 PsChargeSharedPoolQuota(PsGetCurrentProcess(),
472 /* Check if we don't have a quota block */
473 if (!ObjectHeader
->QuotaBlockCharged
) return STATUS_QUOTA_EXCEEDED
;
475 /* Now set the flag */
480 return STATUS_SUCCESS
;
485 ObpValidateAccessMask(IN PACCESS_STATE AccessState
)
488 return STATUS_SUCCESS
;
492 * @name ObpDecrementHandleCount
494 * The ObpDecrementHandleCount routine <FILLMEIN>
502 * @param GrantedAccess
512 ObpDecrementHandleCount(IN PVOID ObjectBody
,
513 IN PEPROCESS Process
,
514 IN ACCESS_MASK GrantedAccess
,
515 IN POBJECT_TYPE ObjectType
)
517 POBJECT_HEADER ObjectHeader
;
518 LONG SystemHandleCount
, ProcessHandleCount
;
521 POBJECT_HEADER_HANDLE_INFO HandleInfo
;
522 POBJECT_HANDLE_COUNT_ENTRY HandleEntry
;
523 POBJECT_HANDLE_COUNT_DATABASE HandleDatabase
;
527 /* Get the object type and header */
528 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(ObjectBody
);
529 OBTRACE(OB_HANDLE_DEBUG
,
530 "%s - Decrementing count for: %p. HC PC %lx %lx\n",
533 ObjectHeader
->HandleCount
,
534 ObjectHeader
->PointerCount
);
536 /* Lock the object */
537 ObpAcquireObjectLock(ObjectHeader
);
539 /* Set default counts */
540 SystemHandleCount
= ObjectHeader
->HandleCount
;
541 ProcessHandleCount
= 0;
543 /* Decrement the handle count */
544 NewCount
= InterlockedDecrement(&ObjectHeader
->HandleCount
);
546 /* Check if we're out of handles and this was an exclusive object */
547 if (!(NewCount
) && (ObjectHeader
->Flags
& OB_FLAG_EXCLUSIVE
))
549 /* Clear the exclusive flag */
550 OBJECT_HEADER_TO_QUOTA_INFO(ObjectHeader
)->ExclusiveProcess
= NULL
;
553 /* Is the object type keeping track of handles? */
554 if (ObjectType
->TypeInfo
.MaintainHandleCount
)
556 /* Get handle information */
557 HandleInfo
= OBJECT_HEADER_TO_HANDLE_INFO(ObjectHeader
);
559 /* Check if there's only a single entry */
560 if (ObjectHeader
->Flags
& OB_FLAG_SINGLE_PROCESS
)
562 /* It should be us */
563 ASSERT(HandleInfo
->SingleEntry
.Process
== Process
);
564 ASSERT(HandleInfo
->SingleEntry
.HandleCount
> 0);
566 /* Get the handle counts */
567 ProcessHandleCount
= HandleInfo
->SingleEntry
.HandleCount
--;
568 HandleEntry
= &HandleInfo
->SingleEntry
;
572 /* Otherwise, get the database */
573 HandleDatabase
= HandleInfo
->HandleCountDatabase
;
576 /* Get the entries and loop them */
577 i
= HandleDatabase
->CountEntries
;
578 HandleEntry
= &HandleDatabase
->HandleCountEntries
[0];
581 /* Check if this is a match */
582 if ((HandleEntry
->HandleCount
) &&
583 (HandleEntry
->Process
== Process
))
585 /* Found it, get the process handle count */
586 ProcessHandleCount
= HandleEntry
->HandleCount
--;
597 /* No database, so no entry */
602 /* Check if this is the last handle */
603 if (ProcessHandleCount
== 1)
605 /* Then clear the entry */
606 HandleEntry
->Process
= NULL
;
607 HandleEntry
->HandleCount
= 0;
611 /* Release the lock */
612 ObpReleaseObjectLock(ObjectHeader
);
614 /* Check if we have a close procedure */
615 if (ObjectType
->TypeInfo
.CloseProcedure
)
618 ObpCalloutStart(&CalloutIrql
);
619 ObjectType
->TypeInfo
.CloseProcedure(Process
,
624 ObpCalloutEnd(CalloutIrql
, "Close", ObjectType
, ObjectBody
);
627 /* Check if we should delete the object */
628 ObpDeleteNameCheck(ObjectBody
);
630 /* Decrease the total number of handles for this type */
631 InterlockedDecrement((PLONG
)&ObjectType
->TotalNumberOfHandles
);
632 OBTRACE(OB_HANDLE_DEBUG
,
633 "%s - Decremented count for: %p. HC PC %lx %lx\n",
636 ObjectHeader
->HandleCount
,
637 ObjectHeader
->PointerCount
);
641 * @name ObpCloseHandleTableEntry
643 * The ObpCloseHandleTableEntry routine <FILLMEIN>
657 * @param IgnoreHandleProtection
660 * @return <FILLMEIN>.
667 ObpCloseHandleTableEntry(IN PHANDLE_TABLE HandleTable
,
668 IN PHANDLE_TABLE_ENTRY HandleEntry
,
670 IN KPROCESSOR_MODE AccessMode
,
671 IN BOOLEAN IgnoreHandleProtection
)
674 POBJECT_TYPE ObjectType
;
675 POBJECT_HEADER ObjectHeader
;
676 ACCESS_MASK GrantedAccess
;
680 /* Get the object data */
681 ObjectHeader
= ObpGetHandleObject(HandleEntry
);
682 ObjectType
= ObjectHeader
->Type
;
683 Body
= &ObjectHeader
->Body
;
684 GrantedAccess
= HandleEntry
->GrantedAccess
;
685 OBTRACE(OB_HANDLE_DEBUG
,
686 "%s - Closing handle: %lx for %p. HC PC %lx %lx\n",
690 ObjectHeader
->HandleCount
,
691 ObjectHeader
->PointerCount
);
693 /* Check if the object has an Okay To Close procedure */
694 if (ObjectType
->TypeInfo
.OkayToCloseProcedure
)
696 /* Call it and check if it's not letting us close it */
697 ObpCalloutStart(&CalloutIrql
);
698 if (!ObjectType
->TypeInfo
.OkayToCloseProcedure(PsGetCurrentProcess(),
704 ObpCalloutEnd(CalloutIrql
, "NtClose", ObjectType
, Body
);
705 ExUnlockHandleTableEntry(HandleTable
, HandleEntry
);
706 return STATUS_HANDLE_NOT_CLOSABLE
;
709 /* Success, validate callout retrn */
710 ObpCalloutEnd(CalloutIrql
, "NtClose", ObjectType
, Body
);
713 /* The callback allowed us to close it, but does the handle itself? */
714 if ((HandleEntry
->ObAttributes
& OBJ_PROTECT_CLOSE
) &&
715 !(IgnoreHandleProtection
))
717 /* It doesn't, are we from user mode? */
718 if (AccessMode
!= KernelMode
)
720 /* We are! Unlock the entry */
721 ExUnlockHandleTableEntry(HandleTable
, HandleEntry
);
723 /* Make sure we have a debug port */
724 if (PsGetCurrentProcess()->DebugPort
)
726 /* Raise an exception */
727 return KeRaiseUserException(STATUS_HANDLE_NOT_CLOSABLE
);
731 /* Return the error instead */
732 return STATUS_HANDLE_NOT_CLOSABLE
;
737 /* Otherwise, bugcheck the OS */
738 KeBugCheckEx(INVALID_KERNEL_HANDLE
, (ULONG_PTR
)Handle
, 0, 0, 0);
742 /* Destroy and unlock the handle entry */
743 ExDestroyHandle(HandleTable
, Handle
, HandleEntry
);
745 /* Now decrement the handle count */
746 ObpDecrementHandleCount(Body
,
747 PsGetCurrentProcess(),
751 /* Dereference the object as well */
752 ObDereferenceObject(Body
);
754 /* Return to caller */
755 OBTRACE(OB_HANDLE_DEBUG
,
756 "%s - Closed handle: %lx for %p. HC PC %lx %lx\n",
760 ObjectHeader
->HandleCount
,
761 ObjectHeader
->PointerCount
);
762 return STATUS_SUCCESS
;
766 * @name ObpIncrementHandleCount
768 * The ObpIncrementHandleCount routine <FILLMEIN>
779 * @param HandleAttributes
788 * @return <FILLMEIN>.
795 ObpIncrementHandleCount(IN PVOID Object
,
796 IN PACCESS_STATE AccessState OPTIONAL
,
797 IN KPROCESSOR_MODE AccessMode
,
798 IN ULONG HandleAttributes
,
799 IN PEPROCESS Process
,
800 IN OB_OPEN_REASON OpenReason
)
802 POBJECT_HEADER ObjectHeader
;
803 POBJECT_TYPE ObjectType
;
804 ULONG ProcessHandleCount
;
806 PEPROCESS ExclusiveProcess
;
807 BOOLEAN Exclusive
= FALSE
, NewObject
;
808 POBJECT_HEADER_CREATOR_INFO CreatorInfo
;
810 KPROCESSOR_MODE ProbeMode
;
814 /* Get the object header and type */
815 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
816 ObjectType
= ObjectHeader
->Type
;
817 OBTRACE(OB_HANDLE_DEBUG
,
818 "%s - Incrementing count for: %p. Reason: %lx. HC PC %lx %lx\n",
822 ObjectHeader
->HandleCount
,
823 ObjectHeader
->PointerCount
);
825 /* Check if caller is forcing user mode */
826 if (HandleAttributes
& OBJ_FORCE_ACCESS_CHECK
)
829 ProbeMode
= UserMode
;
833 /* Keep original setting */
834 ProbeMode
= AccessMode
;
837 /* Lock the object */
838 ObpAcquireObjectLock(ObjectHeader
);
840 /* Charge quota and remove the creator info flag */
841 Status
= ObpChargeQuotaForObject(ObjectHeader
, ObjectType
, &NewObject
);
842 if (!NT_SUCCESS(Status
)) return Status
;
844 /* Check if the open is exclusive */
845 if (HandleAttributes
& OBJ_EXCLUSIVE
)
847 /* Check if the object allows this, or if the inherit flag was given */
848 if ((HandleAttributes
& OBJ_INHERIT
) ||
849 !(ObjectHeader
->Flags
& OB_FLAG_EXCLUSIVE
))
851 /* Incorrect attempt */
852 Status
= STATUS_INVALID_PARAMETER
;
856 /* Check if we have access to it */
857 ExclusiveProcess
= OBJECT_HEADER_TO_EXCLUSIVE_PROCESS(ObjectHeader
);
858 if ((!(ExclusiveProcess
) && (ObjectHeader
->HandleCount
)) ||
859 ((ExclusiveProcess
) && (ExclusiveProcess
!= PsGetCurrentProcess())))
861 /* This isn't the right process */
862 Status
= STATUS_ACCESS_DENIED
;
866 /* Now you got exclusive access */
869 else if ((ObjectHeader
->Flags
& OB_FLAG_EXCLUSIVE
) &&
870 (OBJECT_HEADER_TO_EXCLUSIVE_PROCESS(ObjectHeader
)))
872 /* Caller didn't want exclusive access, but the object is exclusive */
873 Status
= STATUS_ACCESS_DENIED
;
878 * Check if this is an object that went from 0 handles back to existence,
879 * but doesn't have an open procedure, only a close procedure. This means
880 * that it will never realize that the object is back alive, so we must
883 if (!(ObjectHeader
->HandleCount
) &&
885 (ObjectType
->TypeInfo
.MaintainHandleCount
) &&
886 !(ObjectType
->TypeInfo
.OpenProcedure
) &&
887 (ObjectType
->TypeInfo
.CloseProcedure
))
890 Status
= STATUS_UNSUCCESSFUL
;
894 /* Check if we're opening an existing handle */
895 if ((OpenReason
== ObOpenHandle
) ||
896 ((OpenReason
== ObDuplicateHandle
) && (AccessState
)))
898 /* Validate the caller's access to this object */
899 if (!ObCheckObjectAccess(Object
,
905 /* Access was denied, so fail */
909 else if (OpenReason
== ObCreateHandle
)
911 /* Convert MAXIMUM_ALLOWED to GENERIC_ALL */
912 if (AccessState
->RemainingDesiredAccess
& MAXIMUM_ALLOWED
)
914 /* Mask out MAXIMUM_ALLOWED and stick GENERIC_ALL instead */
915 AccessState
->RemainingDesiredAccess
&= ~MAXIMUM_ALLOWED
;
916 AccessState
->RemainingDesiredAccess
|= GENERIC_ALL
;
919 /* Check if we have to map the GENERIC mask */
920 if (AccessState
->RemainingDesiredAccess
& GENERIC_ACCESS
)
922 /* Map it to the correct access masks */
923 RtlMapGenericMask(&AccessState
->RemainingDesiredAccess
,
924 &ObjectType
->TypeInfo
.GenericMapping
);
927 /* Check if the caller is trying to access system security */
928 if (AccessState
->RemainingDesiredAccess
& ACCESS_SYSTEM_SECURITY
)
931 DPRINT1("ACCESS_SYSTEM_SECURITY not validated!\n");
935 /* Check if this is an exclusive handle */
938 /* Save the owner process */
939 OBJECT_HEADER_TO_QUOTA_INFO(ObjectHeader
)->ExclusiveProcess
= Process
;
942 /* Increase the handle count */
943 InterlockedIncrement(&ObjectHeader
->HandleCount
);
944 ProcessHandleCount
= 0;
946 /* Check if we have a handle database */
947 if (ObjectType
->TypeInfo
.MaintainHandleCount
)
949 /* Increment the handle database */
950 Status
= ObpIncrementHandleDataBase(ObjectHeader
,
952 &ProcessHandleCount
);
953 if (!NT_SUCCESS(Status
))
955 /* FIXME: This should never happen for now */
956 DPRINT1("Unhandled case\n");
962 /* Release the lock */
963 ObpReleaseObjectLock(ObjectHeader
);
965 /* Check if we have an open procedure */
966 Status
= STATUS_SUCCESS
;
967 if (ObjectType
->TypeInfo
.OpenProcedure
)
970 ObpCalloutStart(&CalloutIrql
);
971 Status
= ObjectType
->TypeInfo
.OpenProcedure(OpenReason
,
976 PreviouslyGrantedAccess
:
979 ObpCalloutEnd(CalloutIrql
, "Open", ObjectType
, Object
);
981 /* Check if the open procedure failed */
982 if (!NT_SUCCESS(Status
))
984 /* FIXME: This should never happen for now */
985 DPRINT1("Unhandled case\n");
991 /* Check if this is a create operation */
992 if (OpenReason
== ObCreateHandle
)
994 /* Check if we have creator info */
995 CreatorInfo
= OBJECT_HEADER_TO_CREATOR_INFO(ObjectHeader
);
998 /* We do, acquire the lock */
999 ObpEnterObjectTypeMutex(ObjectType
);
1001 /* Insert us on the list */
1002 InsertTailList(&ObjectType
->TypeList
, &CreatorInfo
->TypeList
);
1004 /* Release the lock */
1005 ObpLeaveObjectTypeMutex(ObjectType
);
1009 /* Increase total number of handles */
1010 Total
= InterlockedIncrement((PLONG
)&ObjectType
->TotalNumberOfHandles
);
1011 if (Total
> ObjectType
->HighWaterNumberOfHandles
)
1014 ObjectType
->HighWaterNumberOfHandles
= Total
;
1017 /* Trace call and return */
1018 OBTRACE(OB_HANDLE_DEBUG
,
1019 "%s - Incremented count for: %p. Reason: %lx HC PC %lx %lx\n",
1023 ObjectHeader
->HandleCount
,
1024 ObjectHeader
->PointerCount
);
1028 /* Release lock and return */
1029 ObpReleaseObjectLock(ObjectHeader
);
1034 * @name ObpIncrementUnnamedHandleCount
1036 * The ObpIncrementUnnamedHandleCount routine <FILLMEIN>
1041 * @param AccessState
1047 * @param HandleAttributes
1056 * @return <FILLMEIN>.
1063 ObpIncrementUnnamedHandleCount(IN PVOID Object
,
1064 IN PACCESS_MASK DesiredAccess
,
1065 IN KPROCESSOR_MODE AccessMode
,
1066 IN ULONG HandleAttributes
,
1067 IN PEPROCESS Process
)
1069 POBJECT_HEADER ObjectHeader
;
1070 POBJECT_TYPE ObjectType
;
1071 ULONG ProcessHandleCount
;
1073 PEPROCESS ExclusiveProcess
;
1074 BOOLEAN Exclusive
= FALSE
, NewObject
;
1075 POBJECT_HEADER_CREATOR_INFO CreatorInfo
;
1079 /* Get the object header and type */
1080 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
1081 ObjectType
= ObjectHeader
->Type
;
1082 OBTRACE(OB_HANDLE_DEBUG
,
1083 "%s - Incrementing count for: %p. UNNAMED. HC PC %lx %lx\n",
1086 ObjectHeader
->HandleCount
,
1087 ObjectHeader
->PointerCount
);
1089 /* Lock the object */
1090 ObpAcquireObjectLock(ObjectHeader
);
1092 /* Charge quota and remove the creator info flag */
1093 Status
= ObpChargeQuotaForObject(ObjectHeader
, ObjectType
, &NewObject
);
1094 if (!NT_SUCCESS(Status
)) return Status
;
1096 /* Check if the open is exclusive */
1097 if (HandleAttributes
& OBJ_EXCLUSIVE
)
1099 /* Check if the object allows this, or if the inherit flag was given */
1100 if ((HandleAttributes
& OBJ_INHERIT
) ||
1101 !(ObjectHeader
->Flags
& OB_FLAG_EXCLUSIVE
))
1103 /* Incorrect attempt */
1104 Status
= STATUS_INVALID_PARAMETER
;
1108 /* Check if we have access to it */
1109 ExclusiveProcess
= OBJECT_HEADER_TO_EXCLUSIVE_PROCESS(ObjectHeader
);
1110 if ((!(ExclusiveProcess
) && (ObjectHeader
->HandleCount
)) ||
1111 ((ExclusiveProcess
) && (ExclusiveProcess
!= PsGetCurrentProcess())))
1113 /* This isn't the right process */
1114 Status
= STATUS_ACCESS_DENIED
;
1118 /* Now you got exclusive access */
1121 else if ((ObjectHeader
->Flags
& OB_FLAG_EXCLUSIVE
) &&
1122 (OBJECT_HEADER_TO_EXCLUSIVE_PROCESS(ObjectHeader
)))
1124 /* Caller didn't want exclusive access, but the object is exclusive */
1125 Status
= STATUS_ACCESS_DENIED
;
1130 * Check if this is an object that went from 0 handles back to existence,
1131 * but doesn't have an open procedure, only a close procedure. This means
1132 * that it will never realize that the object is back alive, so we must
1135 if (!(ObjectHeader
->HandleCount
) &&
1137 (ObjectType
->TypeInfo
.MaintainHandleCount
) &&
1138 !(ObjectType
->TypeInfo
.OpenProcedure
) &&
1139 (ObjectType
->TypeInfo
.CloseProcedure
))
1142 Status
= STATUS_UNSUCCESSFUL
;
1146 /* Convert MAXIMUM_ALLOWED to GENERIC_ALL */
1147 if (*DesiredAccess
& MAXIMUM_ALLOWED
)
1149 /* Mask out MAXIMUM_ALLOWED and stick GENERIC_ALL instead */
1150 *DesiredAccess
&= ~MAXIMUM_ALLOWED
;
1151 *DesiredAccess
|= GENERIC_ALL
;
1154 /* Check if we have to map the GENERIC mask */
1155 if (*DesiredAccess
& GENERIC_ACCESS
)
1157 /* Map it to the correct access masks */
1158 RtlMapGenericMask(DesiredAccess
,
1159 &ObjectType
->TypeInfo
.GenericMapping
);
1162 /* Check if this is an exclusive handle */
1165 /* Save the owner process */
1166 OBJECT_HEADER_TO_QUOTA_INFO(ObjectHeader
)->ExclusiveProcess
= Process
;
1169 /* Increase the handle count */
1170 InterlockedIncrement(&ObjectHeader
->HandleCount
);
1171 ProcessHandleCount
= 0;
1173 /* Check if we have a handle database */
1174 if (ObjectType
->TypeInfo
.MaintainHandleCount
)
1176 /* Increment the handle database */
1177 Status
= ObpIncrementHandleDataBase(ObjectHeader
,
1179 &ProcessHandleCount
);
1180 if (!NT_SUCCESS(Status
))
1182 /* FIXME: This should never happen for now */
1183 DPRINT1("Unhandled case\n");
1189 /* Release the lock */
1190 ObpReleaseObjectLock(ObjectHeader
);
1192 /* Check if we have an open procedure */
1193 Status
= STATUS_SUCCESS
;
1194 if (ObjectType
->TypeInfo
.OpenProcedure
)
1197 ObpCalloutStart(&CalloutIrql
);
1198 Status
= ObjectType
->TypeInfo
.OpenProcedure(ObCreateHandle
,
1202 ProcessHandleCount
);
1203 ObpCalloutEnd(CalloutIrql
, "Open", ObjectType
, Object
);
1205 /* Check if the open procedure failed */
1206 if (!NT_SUCCESS(Status
))
1208 /* FIXME: This should never happen for now */
1209 DPRINT1("Unhandled case\n");
1215 /* Check if we have creator info */
1216 CreatorInfo
= OBJECT_HEADER_TO_CREATOR_INFO(ObjectHeader
);
1219 /* We do, acquire the lock */
1220 ObpEnterObjectTypeMutex(ObjectType
);
1222 /* Insert us on the list */
1223 InsertTailList(&ObjectType
->TypeList
, &CreatorInfo
->TypeList
);
1225 /* Release the lock */
1226 ObpLeaveObjectTypeMutex(ObjectType
);
1229 /* Increase total number of handles */
1230 Total
= InterlockedIncrement((PLONG
)&ObjectType
->TotalNumberOfHandles
);
1231 if (Total
> ObjectType
->HighWaterNumberOfHandles
)
1234 ObjectType
->HighWaterNumberOfHandles
= Total
;
1237 /* Trace call and return */
1238 OBTRACE(OB_HANDLE_DEBUG
,
1239 "%s - Incremented count for: %p. UNNAMED HC PC %lx %lx\n",
1242 ObjectHeader
->HandleCount
,
1243 ObjectHeader
->PointerCount
);
1247 /* Release lock and return */
1248 ObpReleaseObjectLock(ObjectHeader
);
1253 * @name ObpCreateUnnamedHandle
1255 * The ObpCreateUnnamedHandle routine <FILLMEIN>
1260 * @param DesiredAccess
1263 * @param AdditionalReferences
1266 * @param HandleAttributes
1272 * @param ReturnedObject
1275 * @param ReturnedHandle
1278 * @return <FILLMEIN>.
1285 ObpCreateUnnamedHandle(IN PVOID Object
,
1286 IN ACCESS_MASK DesiredAccess
,
1287 IN ULONG AdditionalReferences
,
1288 IN ULONG HandleAttributes
,
1289 IN KPROCESSOR_MODE AccessMode
,
1290 OUT PVOID
*ReturnedObject
,
1291 OUT PHANDLE ReturnedHandle
)
1293 HANDLE_TABLE_ENTRY NewEntry
;
1294 POBJECT_HEADER ObjectHeader
;
1296 KAPC_STATE ApcState
;
1297 BOOLEAN AttachedToProcess
= FALSE
, KernelHandle
= FALSE
;
1300 ACCESS_MASK GrantedAccess
;
1301 POBJECT_TYPE ObjectType
;
1304 /* Get the object header and type */
1305 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
1306 ObjectType
= ObjectHeader
->Type
;
1307 OBTRACE(OB_HANDLE_DEBUG
,
1308 "%s - Creating handle for: %p. UNNAMED. HC PC %lx %lx\n",
1311 ObjectHeader
->HandleCount
,
1312 ObjectHeader
->PointerCount
);
1314 /* Save the object header */
1315 NewEntry
.Object
= ObjectHeader
;
1317 /* Mask out the internal attributes */
1318 NewEntry
.ObAttributes
|= HandleAttributes
& OBJ_HANDLE_ATTRIBUTES
;
1320 /* Check if this is a kernel handle */
1321 if (HandleAttributes
& OBJ_KERNEL_HANDLE
)
1323 /* Set the handle table */
1324 HandleTable
= ObpKernelHandleTable
;
1325 KernelHandle
= TRUE
;
1327 /* Check if we're not in the system process */
1328 if (PsGetCurrentProcess() != PsInitialSystemProcess
)
1330 /* Attach to the system process */
1331 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
1332 AttachedToProcess
= TRUE
;
1337 /* Get the current handle table */
1338 HandleTable
= PsGetCurrentProcess()->ObjectTable
;
1341 /* Increment the handle count */
1342 Status
= ObpIncrementUnnamedHandleCount(Object
,
1346 PsGetCurrentProcess());
1347 if (!NT_SUCCESS(Status
))
1350 * We failed (meaning security failure, according to NT Internals)
1353 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1357 /* Remove what's not in the valid access mask */
1358 GrantedAccess
= DesiredAccess
& (ObjectType
->TypeInfo
.ValidAccessMask
|
1359 ACCESS_SYSTEM_SECURITY
);
1361 /* Handle extra references */
1362 if (AdditionalReferences
)
1364 /* Add them to the header */
1365 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
,
1366 AdditionalReferences
);
1369 /* Save the access mask */
1370 NewEntry
.GrantedAccess
= GrantedAccess
;
1373 * Create the actual handle. We'll need to do this *after* calling
1374 * ObpIncrementHandleCount to make sure that Object Security is valid
1375 * (specified in Gl00my documentation on Ob)
1377 OBTRACE(OB_HANDLE_DEBUG
,
1378 "%s - Handle Properties: [%p-%lx-%lx]\n",
1380 NewEntry
.Object
, NewEntry
.ObAttributes
& 3, NewEntry
.GrantedAccess
);
1381 Handle
= ExCreateHandle(HandleTable
, &NewEntry
);
1383 /* Make sure we got a handle */
1386 /* Check if this was a kernel handle */
1387 if (KernelHandle
) Handle
= ObMarkHandleAsKernelHandle(Handle
);
1389 /* Return handle and object */
1390 *ReturnedHandle
= Handle
;
1392 /* Return the new object only if caller wanted it biased */
1393 if ((AdditionalReferences
) && (ReturnedObject
))
1396 *ReturnedObject
= Object
;
1399 /* Detach if needed */
1400 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1402 /* Trace and return */
1403 OBTRACE(OB_HANDLE_DEBUG
,
1404 "%s - Returning Handle: %lx HC PC %lx %lx\n",
1407 ObjectHeader
->HandleCount
,
1408 ObjectHeader
->PointerCount
);
1409 return STATUS_SUCCESS
;
1412 /* Handle extra references */
1413 if (AdditionalReferences
)
1415 /* Dereference it as many times as required */
1416 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
,
1417 -(LONG
)AdditionalReferences
);
1420 /* Decrement the handle count and detach */
1421 ObpDecrementHandleCount(&ObjectHeader
->Body
,
1422 PsGetCurrentProcess(),
1426 /* Detach and fail */
1427 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1428 return STATUS_INSUFFICIENT_RESOURCES
;
1432 * @name ObpCreateHandle
1434 * The ObpCreateHandle routine <FILLMEIN>
1445 * @param AccessState
1448 * @param AdditionalReferences
1451 * @param HandleAttributes
1457 * @param ReturnedObject
1460 * @param ReturnedHandle
1463 * @return <FILLMEIN>.
1465 * @remarks Cleans up the Lookup Context on return.
1470 ObpCreateHandle(IN OB_OPEN_REASON OpenReason
,
1472 IN POBJECT_TYPE Type OPTIONAL
,
1473 IN PACCESS_STATE AccessState
,
1474 IN ULONG AdditionalReferences
,
1475 IN ULONG HandleAttributes
,
1476 IN POBP_LOOKUP_CONTEXT Context
,
1477 IN KPROCESSOR_MODE AccessMode
,
1478 OUT PVOID
*ReturnedObject
,
1479 OUT PHANDLE ReturnedHandle
)
1481 HANDLE_TABLE_ENTRY NewEntry
;
1482 POBJECT_HEADER ObjectHeader
;
1484 KAPC_STATE ApcState
;
1485 BOOLEAN AttachedToProcess
= FALSE
, KernelHandle
= FALSE
;
1486 POBJECT_TYPE ObjectType
;
1489 ACCESS_MASK DesiredAccess
, GrantedAccess
;
1490 PAUX_ACCESS_DATA AuxData
;
1493 /* Get the object header and type */
1494 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
1495 ObjectType
= ObjectHeader
->Type
;
1496 OBTRACE(OB_HANDLE_DEBUG
,
1497 "%s - Creating handle for: %p. Reason: %lx. HC PC %lx %lx\n",
1501 ObjectHeader
->HandleCount
,
1502 ObjectHeader
->PointerCount
);
1504 /* Check if the types match */
1505 if ((Type
) && (ObjectType
!= Type
))
1507 /* They don't, cleanup */
1508 if (Context
) ObpReleaseLookupContext(Context
);
1509 return STATUS_OBJECT_TYPE_MISMATCH
;
1512 /* Save the object header */
1513 NewEntry
.Object
= ObjectHeader
;
1515 /* Check if this is a kernel handle */
1516 if (HandleAttributes
& OBJ_KERNEL_HANDLE
)
1518 /* Set the handle table */
1519 HandleTable
= ObpKernelHandleTable
;
1520 KernelHandle
= TRUE
;
1522 /* Check if we're not in the system process */
1523 if (PsGetCurrentProcess() != PsInitialSystemProcess
)
1525 /* Attach to the system process */
1526 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
1527 AttachedToProcess
= TRUE
;
1532 /* Get the current handle table */
1533 HandleTable
= PsGetCurrentProcess()->ObjectTable
;
1536 /* Increment the handle count */
1537 Status
= ObpIncrementHandleCount(Object
,
1541 PsGetCurrentProcess(),
1543 if (!NT_SUCCESS(Status
))
1546 * We failed (meaning security failure, according to NT Internals)
1549 if (Context
) ObpReleaseLookupContext(Context
);
1550 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1554 /* Check if we are doing audits on close */
1555 if (AccessState
->GenerateOnClose
)
1557 /* Force the attribute on */
1558 HandleAttributes
|= OBJ_AUDIT_OBJECT_CLOSE
;
1561 /* Mask out the internal attributes */
1562 NewEntry
.ObAttributes
|= (HandleAttributes
& OBJ_HANDLE_ATTRIBUTES
);
1564 /* Get the original desired access */
1565 DesiredAccess
= AccessState
->RemainingDesiredAccess
|
1566 AccessState
->PreviouslyGrantedAccess
;
1568 /* Remove what's not in the valid access mask */
1569 GrantedAccess
= DesiredAccess
& (ObjectType
->TypeInfo
.ValidAccessMask
|
1570 ACCESS_SYSTEM_SECURITY
);
1572 /* Update the value in the access state */
1573 AccessState
->PreviouslyGrantedAccess
= GrantedAccess
;
1575 /* Get the auxiliary data */
1576 AuxData
= AccessState
->AuxData
;
1578 /* Handle extra references */
1579 if (AdditionalReferences
)
1581 /* Add them to the header */
1582 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
, AdditionalReferences
);
1585 /* Now we can release the object */
1586 if (Context
) ObpReleaseLookupContext(Context
);
1588 /* Save the access mask */
1589 NewEntry
.GrantedAccess
= GrantedAccess
;
1592 * Create the actual handle. We'll need to do this *after* calling
1593 * ObpIncrementHandleCount to make sure that Object Security is valid
1594 * (specified in Gl00my documentation on Ob)
1596 OBTRACE(OB_HANDLE_DEBUG
,
1597 "%s - Handle Properties: [%p-%lx-%lx]\n",
1599 NewEntry
.Object
, NewEntry
.ObAttributes
& 3, NewEntry
.GrantedAccess
);
1600 Handle
= ExCreateHandle(HandleTable
, &NewEntry
);
1602 /* Make sure we got a handle */
1605 /* Check if this was a kernel handle */
1606 if (KernelHandle
) Handle
= ObMarkHandleAsKernelHandle(Handle
);
1609 *ReturnedHandle
= Handle
;
1611 /* Check if we need to generate on audit */
1612 if (AccessState
->GenerateAudit
)
1614 /* Audit the handle creation */
1615 //SeAuditHandleCreation(AccessState, Handle);
1618 /* Check if this was a create */
1619 if (OpenReason
== ObCreateHandle
)
1621 /* Check if we need to audit the privileges */
1622 if ((AuxData
->PrivilegeSet
) &&
1623 (AuxData
->PrivilegeSet
->PrivilegeCount
))
1627 SePrivilegeObjectAuditAlarm(Handle
,
1629 SubjectSecurityContext
,
1631 AuxData
->PrivilegeSet
,
1633 ExGetPreviousMode());
1638 /* Return the new object only if caller wanted it biased */
1639 if ((AdditionalReferences
) && (ReturnedObject
))
1642 *ReturnedObject
= Object
;
1645 /* Detach if needed */
1646 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1648 /* Trace and return */
1649 OBTRACE(OB_HANDLE_DEBUG
,
1650 "%s - Returning Handle: %lx HC PC %lx %lx\n",
1653 ObjectHeader
->HandleCount
,
1654 ObjectHeader
->PointerCount
);
1655 return STATUS_SUCCESS
;
1658 /* Decrement the handle count and detach */
1659 ObpDecrementHandleCount(&ObjectHeader
->Body
,
1660 PsGetCurrentProcess(),
1664 /* Handle extra references */
1665 if (AdditionalReferences
)
1667 /* Check how many extra references were added */
1668 if (AdditionalReferences
> 1)
1670 /* Dereference it many times */
1671 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
,
1672 -(LONG
)(AdditionalReferences
- 1));
1675 /* Dereference the object one last time */
1676 ObDereferenceObject(Object
);
1679 /* Detach if necessary and fail */
1680 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1681 return STATUS_INSUFFICIENT_RESOURCES
;
1685 * @name ObpCloseHandle
1687 * The ObpCloseHandle routine <FILLMEIN>
1695 * @return <FILLMEIN>.
1702 ObpCloseHandle(IN HANDLE Handle
,
1703 IN KPROCESSOR_MODE AccessMode
)
1706 BOOLEAN AttachedToProcess
= FALSE
;
1707 KAPC_STATE ApcState
;
1708 PHANDLE_TABLE_ENTRY HandleTableEntry
;
1710 PEPROCESS Process
= PsGetCurrentProcess();
1712 OBTRACE(OB_HANDLE_DEBUG
,
1713 "%s - Closing handle: %lx\n", __FUNCTION__
, Handle
);
1715 /* Check if we're dealing with a kernel handle */
1716 if (ObIsKernelHandle(Handle
, AccessMode
))
1718 /* Use the kernel table and convert the handle */
1719 HandleTable
= ObpKernelHandleTable
;
1720 Handle
= ObKernelHandleToHandle(Handle
);
1722 /* Check if we're not in the system process */
1723 if (Process
!= PsInitialSystemProcess
)
1725 /* Attach to the system process */
1726 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
1727 AttachedToProcess
= TRUE
;
1732 /* Use the process's handle table */
1733 HandleTable
= Process
->ObjectTable
;
1736 /* Enter a critical region to protect handle access */
1737 KeEnterCriticalRegion();
1739 /* Get the handle entry */
1740 HandleTableEntry
= ExMapHandleToPointer(HandleTable
, Handle
);
1741 if (HandleTableEntry
)
1743 /* Now close the entry */
1744 Status
= ObpCloseHandleTableEntry(HandleTable
,
1750 /* We can quit the critical region now */
1751 KeLeaveCriticalRegion();
1753 /* Detach and return success */
1754 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1755 Status
= STATUS_SUCCESS
;
1759 /* We failed, quit the critical region */
1760 KeLeaveCriticalRegion();
1763 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1765 /* Check if we have a valid handle that's not the process or thread */
1767 (Handle
!= NtCurrentProcess()) &&
1768 (Handle
!= NtCurrentThread()))
1770 /* Check if we came from user mode */
1771 if (AccessMode
!= KernelMode
)
1773 /* Check if we have no debug port */
1774 if (Process
->DebugPort
)
1776 /* Make sure we're not attached */
1777 if (!KeIsAttachedProcess())
1779 /* Raise an exception */
1780 return KeRaiseUserException(STATUS_INVALID_HANDLE
);
1786 /* This is kernel mode. Check if we're exiting */
1787 if (!(PsIsThreadTerminating(PsGetCurrentThread())) &&
1790 /* Check if the debugger is enabled */
1791 if (KdDebuggerEnabled
)
1794 KeBugCheckEx(INVALID_KERNEL_HANDLE
, (ULONG_PTR
)Handle
, 1, 0, 0);
1800 /* Set invalid status */
1801 Status
= STATUS_INVALID_HANDLE
;
1805 OBTRACE(OB_HANDLE_DEBUG
,
1806 "%s - Closed handle: %lx S: %lx\n",
1807 __FUNCTION__
, Handle
, Status
);
1812 * @name ObpSetHandleAttributes
1814 * The ObpSetHandleAttributes routine <FILLMEIN>
1816 * @param HandleTableEntry
1822 * @return <FILLMEIN>.
1829 ObpSetHandleAttributes(IN OUT PHANDLE_TABLE_ENTRY HandleTableEntry
,
1830 IN ULONG_PTR Context
)
1832 POBP_SET_HANDLE_ATTRIBUTES_CONTEXT SetHandleInfo
= (PVOID
)Context
;
1833 POBJECT_HEADER ObjectHeader
= ObpGetHandleObject(HandleTableEntry
);
1835 /* Check if making the handle inheritable */
1836 if (SetHandleInfo
->Information
.Inherit
)
1838 /* Check if inheriting is not supported for this object */
1839 if (ObjectHeader
->Type
->TypeInfo
.InvalidAttributes
& OBJ_INHERIT
)
1841 /* Fail without changing anything */
1846 HandleTableEntry
->ObAttributes
|= OBJ_INHERIT
;
1850 /* Otherwise this implies we're removing the flag */
1851 HandleTableEntry
->ObAttributes
&= ~OBJ_INHERIT
;
1854 /* Check if making the handle protected */
1855 if (SetHandleInfo
->Information
.ProtectFromClose
)
1858 HandleTableEntry
->GrantedAccess
|= ObpAccessProtectCloseBit
;
1862 /* Otherwise, remove it */
1863 HandleTableEntry
->GrantedAccess
&= ~ObpAccessProtectCloseBit
;
1866 /* Return success */
1871 * @name ObpCloseHandleCallback
1873 * The ObpCloseHandleCallback routine <FILLMEIN>
1875 * @param HandleTable
1881 * @param GrantedAccess
1887 * @return <FILLMEIN>.
1894 ObpCloseHandleCallback(IN PHANDLE_TABLE_ENTRY HandleTableEntry
,
1898 POBP_CLOSE_HANDLE_CONTEXT CloseContext
= (POBP_CLOSE_HANDLE_CONTEXT
)Context
;
1900 /* Simply decrement the handle count */
1901 ObpCloseHandleTableEntry(CloseContext
->HandleTable
,
1904 CloseContext
->AccessMode
,
1910 * @name ObpDuplicateHandleCallback
1912 * The ObpDuplicateHandleCallback routine <FILLMEIN>
1914 * @param HandleTable
1917 * @param HandleTableEntry
1923 * @return <FILLMEIN>.
1930 ObpDuplicateHandleCallback(IN PEPROCESS Process
,
1931 IN PHANDLE_TABLE HandleTable
,
1932 IN PHANDLE_TABLE_ENTRY OldEntry
,
1933 IN PHANDLE_TABLE_ENTRY HandleTableEntry
)
1935 POBJECT_HEADER ObjectHeader
;
1936 BOOLEAN Ret
= FALSE
;
1937 ACCESS_STATE AccessState
;
1941 /* Make sure that the handle is inheritable */
1942 Ret
= (HandleTableEntry
->ObAttributes
& OBJ_INHERIT
) != 0;
1945 /* Get the object header */
1946 ObjectHeader
= ObpGetHandleObject(HandleTableEntry
);
1948 /* Increment the pointer count */
1949 InterlockedIncrement(&ObjectHeader
->PointerCount
);
1951 /* Release the handle lock */
1952 ExUnlockHandleTableEntry(HandleTable
, OldEntry
);
1954 /* Setup the access state */
1955 AccessState
.PreviouslyGrantedAccess
= HandleTableEntry
->GrantedAccess
;
1957 /* Call the shared routine for incrementing handles */
1958 Status
= ObpIncrementHandleCount(&ObjectHeader
->Body
,
1961 HandleTableEntry
->ObAttributes
& OBJ_HANDLE_ATTRIBUTES
,
1964 if (!NT_SUCCESS(Status
))
1966 /* Return failure */
1967 ObDereferenceObject(&ObjectHeader
->Body
);
1973 /* Release the handle lock */
1974 ExUnlockHandleTableEntry(HandleTable
, OldEntry
);
1977 /* Return duplication result */
1983 ObClearProcessHandleTable(IN PEPROCESS Process
)
1989 * @name ObpCreateHandleTable
1991 * The ObpCreateHandleTable routine <FILLMEIN>
1999 * @return <FILLMEIN>.
2006 ObInitProcess(IN PEPROCESS Parent OPTIONAL
,
2007 IN PEPROCESS Process
)
2009 PHANDLE_TABLE ParentTable
, ObjectTable
;
2011 /* Check for a parent */
2014 /* Reference the parent's table */
2015 ParentTable
= ObReferenceProcessHandleTable(Parent
);
2016 if (!ParentTable
) return STATUS_PROCESS_IS_TERMINATING
;
2019 ObjectTable
= ExDupHandleTable(Process
,
2021 ObpDuplicateHandleCallback
,
2026 /* Otherwise just create a new table */
2028 ObjectTable
= ExCreateHandleTable(Process
);
2031 /* Make sure we have a table */
2035 Process
->ObjectTable
= ObjectTable
;
2037 /* Check for auditing */
2038 if (SeDetailedAuditingWithToken(NULL
))
2041 DPRINT1("Need auditing!\n");
2044 /* Get rid of the old table now */
2045 if (ParentTable
) ObDereferenceProcessHandleTable(Parent
);
2048 return STATUS_SUCCESS
;
2053 Process
->ObjectTable
= NULL
;
2054 if (ParentTable
) ObDereferenceProcessHandleTable(Parent
);
2055 return STATUS_INSUFFICIENT_RESOURCES
;
2060 * @name ObKillProcess
2062 * The ObKillProcess routine <FILLMEIN>
2074 ObKillProcess(IN PEPROCESS Process
)
2076 PHANDLE_TABLE HandleTable
;
2077 OBP_CLOSE_HANDLE_CONTEXT Context
;
2081 /* Wait for process rundown and then complete it */
2082 ExWaitForRundownProtectionRelease(&Process
->RundownProtect
);
2083 ExRundownCompleted(&Process
->RundownProtect
);
2085 /* Get the object table */
2086 HandleTable
= Process
->ObjectTable
;
2087 if (!HandleTable
) return;
2089 /* Disable hard errors while we close handles */
2090 HardErrors
= IoSetThreadHardErrorMode(FALSE
);
2092 /* Enter a critical region */
2093 KeEnterCriticalRegion();
2095 /* Fill out the context */
2096 Context
.AccessMode
= KernelMode
;
2097 Context
.HandleTable
= HandleTable
;
2099 /* Sweep the handle table to close all handles */
2100 ExSweepHandleTable(HandleTable
,
2101 ObpCloseHandleCallback
,
2103 ASSERT(HandleTable
->HandleCount
== 0);
2105 /* Leave the critical region */
2106 KeLeaveCriticalRegion();
2108 /* Re-enable hard errors */
2109 IoSetThreadHardErrorMode(HardErrors
);
2111 /* Destroy the object table */
2112 Process
->ObjectTable
= NULL
;
2113 ExDestroyHandleTable(HandleTable
, NULL
);
2118 ObDuplicateObject(IN PEPROCESS SourceProcess
,
2119 IN HANDLE SourceHandle
,
2120 IN PEPROCESS TargetProcess OPTIONAL
,
2121 IN PHANDLE TargetHandle OPTIONAL
,
2122 IN ACCESS_MASK DesiredAccess
,
2123 IN ULONG HandleAttributes
,
2125 IN KPROCESSOR_MODE PreviousMode
)
2127 HANDLE_TABLE_ENTRY NewHandleEntry
;
2128 BOOLEAN AttachedToProcess
= FALSE
;
2130 POBJECT_HEADER ObjectHeader
;
2131 POBJECT_TYPE ObjectType
;
2133 KAPC_STATE ApcState
;
2135 ACCESS_MASK TargetAccess
, SourceAccess
;
2136 ACCESS_STATE AccessState
;
2137 PACCESS_STATE PassedAccessState
= NULL
;
2138 AUX_ACCESS_DATA AuxData
;
2139 PHANDLE_TABLE HandleTable
;
2140 OBJECT_HANDLE_INFORMATION HandleInformation
;
2143 OBTRACE(OB_HANDLE_DEBUG
,
2144 "%s - Duplicating handle: %lx for %p into %p\n",
2150 /* Assume failure */
2151 if (TargetHandle
) *TargetHandle
= NULL
;
2153 /* Check if we're not duplicating the same access */
2154 if (!(Options
& DUPLICATE_SAME_ACCESS
))
2156 /* Validate the desired access */
2157 Status
= STATUS_SUCCESS
; //ObpValidateDesiredAccess(DesiredAccess);
2158 if (!NT_SUCCESS(Status
)) return Status
;
2161 /* Reference the object table */
2162 HandleTable
= ObReferenceProcessHandleTable(SourceProcess
);
2163 if (!HandleTable
) return STATUS_PROCESS_IS_TERMINATING
;
2165 /* Reference the process object */
2166 Status
= ObpReferenceProcessObjectByHandle(SourceHandle
,
2173 if (!NT_SUCCESS(Status
))
2176 ObDereferenceProcessHandleTable(SourceProcess
);
2181 /* Check if we have to don't have to audit object close */
2182 if (!(HandleInformation
.HandleAttributes
& OBJ_AUDIT_OBJECT_CLOSE
))
2184 /* Then there is no audit mask */
2189 /* Check if there's no target process */
2192 /* Check if the caller wanted actual duplication */
2193 if (!(Options
& DUPLICATE_CLOSE_SOURCE
))
2195 /* Invalid request */
2196 Status
= STATUS_INVALID_PARAMETER
;
2200 /* Otherwise, do the attach */
2201 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
2203 /* Close the handle and detach */
2204 NtClose(SourceHandle
);
2205 KeUnstackDetachProcess(&ApcState
);
2209 ObDereferenceProcessHandleTable(SourceProcess
);
2210 ObDereferenceObject(SourceObject
);
2214 /* Get the target handle table */
2215 HandleTable
= ObReferenceProcessHandleTable(TargetProcess
);
2218 /* Check if the caller wanted us to close the handle */
2219 if (Options
& DUPLICATE_CLOSE_SOURCE
)
2222 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
2224 /* Close the handle and detach */
2225 NtClose(SourceHandle
);
2226 KeUnstackDetachProcess(&ApcState
);
2230 ObDereferenceProcessHandleTable(SourceProcess
);
2231 ObDereferenceObject(SourceObject
);
2232 return STATUS_PROCESS_IS_TERMINATING
;
2235 /* Get the source access */
2236 SourceAccess
= HandleInformation
.GrantedAccess
;
2238 /* Check if we're not in the target process */
2239 if (TargetProcess
!= PsGetCurrentProcess())
2242 KeStackAttachProcess(&TargetProcess
->Pcb
, &ApcState
);
2243 AttachedToProcess
= TRUE
;
2246 /* Check if we're duplicating the attributes */
2247 if (Options
& DUPLICATE_SAME_ATTRIBUTES
)
2249 /* Duplicate them */
2250 HandleAttributes
= HandleInformation
.HandleAttributes
;
2254 /* Don't allow caller to bypass auditing */
2255 HandleAttributes
|= HandleInformation
.HandleAttributes
&
2256 OBJ_AUDIT_OBJECT_CLOSE
;
2259 /* Check if we're duplicating the access */
2260 if (Options
& DUPLICATE_SAME_ACCESS
) DesiredAccess
= SourceAccess
;
2262 /* Get object data */
2263 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(SourceObject
);
2264 ObjectType
= ObjectHeader
->Type
;
2266 /* Fill out the entry */
2267 RtlZeroMemory(&NewHandleEntry
, sizeof(HANDLE_TABLE_ENTRY
));
2268 NewHandleEntry
.Object
= ObjectHeader
;
2269 NewHandleEntry
.ObAttributes
|= (HandleAttributes
& OBJ_HANDLE_ATTRIBUTES
);
2271 /* Check if we're using a generic mask */
2272 if (DesiredAccess
& GENERIC_ACCESS
)
2275 RtlMapGenericMask(&DesiredAccess
,
2276 &ObjectType
->TypeInfo
.GenericMapping
);
2279 /* Set the target access, always propagate ACCESS_SYSTEM_SECURITY */
2280 TargetAccess
= DesiredAccess
& (ObjectType
->TypeInfo
.ValidAccessMask
|
2281 ACCESS_SYSTEM_SECURITY
);
2282 NewHandleEntry
.GrantedAccess
= TargetAccess
;
2284 /* Check if we're asking for new access */
2285 if (TargetAccess
& ~SourceAccess
)
2287 /* We are. We need the security procedure to validate this */
2288 if (ObjectType
->TypeInfo
.SecurityProcedure
== SeDefaultObjectMethod
)
2290 /* Use our built-in access state */
2291 PassedAccessState
= &AccessState
;
2292 Status
= SeCreateAccessState(&AccessState
,
2295 &ObjectType
->TypeInfo
.GenericMapping
);
2299 /* Otherwise we can't allow this privilege elevation */
2300 Status
= STATUS_ACCESS_DENIED
;
2305 /* We don't need an access state */
2306 Status
= STATUS_SUCCESS
;
2309 /* Make sure the access state was created OK */
2310 if (NT_SUCCESS(Status
))
2312 /* Add a new handle */
2313 Status
= ObpIncrementHandleCount(SourceObject
,
2317 PsGetCurrentProcess(),
2321 /* Check if we were attached */
2322 if (AttachedToProcess
)
2324 /* We can safely detach now */
2325 KeUnstackDetachProcess(&ApcState
);
2326 AttachedToProcess
= FALSE
;
2329 /* Check if we have to close the source handle */
2330 if (Options
& DUPLICATE_CLOSE_SOURCE
)
2332 /* Attach and close */
2333 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
2334 NtClose(SourceHandle
);
2335 KeUnstackDetachProcess(&ApcState
);
2338 /* Check if we had an access state */
2339 if (PassedAccessState
) SeDeleteAccessState(PassedAccessState
);
2341 /* Now check if incrementing actually failed */
2342 if (!NT_SUCCESS(Status
))
2344 /* Dereference handle tables */
2345 ObDereferenceProcessHandleTable(SourceProcess
);
2346 ObDereferenceProcessHandleTable(TargetProcess
);
2348 /* Dereference the source object */
2349 ObDereferenceObject(SourceObject
);
2353 /* Now create the handle */
2354 NewHandle
= ExCreateHandle(HandleTable
, &NewHandleEntry
);
2357 /* Undo the increment */
2358 ObpDecrementHandleCount(SourceObject
,
2363 /* Deference the object and set failure status */
2364 ObDereferenceObject(SourceObject
);
2365 Status
= STATUS_INSUFFICIENT_RESOURCES
;
2368 /* Return the handle */
2369 if (TargetHandle
) *TargetHandle
= NewHandle
;
2371 /* Dereference handle tables */
2372 ObDereferenceProcessHandleTable(SourceProcess
);
2373 ObDereferenceProcessHandleTable(TargetProcess
);
2376 OBTRACE(OB_HANDLE_DEBUG
,
2377 "%s - Duplicated handle: %lx for %p into %p. Source: %p HC PC %lx %lx\n",
2383 ObjectHeader
->PointerCount
,
2384 ObjectHeader
->HandleCount
);
2388 /* PUBLIC FUNCTIONS *********************************************************/
2391 * @name ObOpenObjectByName
2394 * The ObOpenObjectByName routine <FILLMEIN>
2396 * @param ObjectAttributes
2405 * @param PassedAccessState
2408 * @param DesiredAccess
2411 * @param ParseContext
2417 * @return <FILLMEIN>.
2424 ObOpenObjectByName(IN POBJECT_ATTRIBUTES ObjectAttributes
,
2425 IN POBJECT_TYPE ObjectType
,
2426 IN KPROCESSOR_MODE AccessMode
,
2427 IN PACCESS_STATE PassedAccessState
,
2428 IN ACCESS_MASK DesiredAccess
,
2429 IN OUT PVOID ParseContext
,
2432 PVOID Object
= NULL
;
2433 UNICODE_STRING ObjectName
;
2435 POBJECT_HEADER ObjectHeader
;
2436 PGENERIC_MAPPING GenericMapping
= NULL
;
2437 OB_OPEN_REASON OpenReason
;
2438 POB_TEMP_BUFFER TempBuffer
;
2441 /* Assume failure */
2444 /* Check if we didn't get any Object Attributes */
2445 if (!ObjectAttributes
)
2447 /* Fail with special status code */
2448 return STATUS_INVALID_PARAMETER
;
2451 /* Allocate the temporary buffer */
2452 TempBuffer
= ExAllocatePoolWithTag(NonPagedPool
,
2453 sizeof(OB_TEMP_BUFFER
),
2454 TAG_OB_TEMP_STORAGE
);
2455 if (!TempBuffer
) return STATUS_INSUFFICIENT_RESOURCES
;
2457 /* Capture all the info */
2458 Status
= ObpCaptureObjectCreateInformation(ObjectAttributes
,
2461 &TempBuffer
->ObjectCreateInfo
,
2463 if (!NT_SUCCESS(Status
))
2466 ExFreePoolWithTag(TempBuffer
, TAG_OB_TEMP_STORAGE
);
2470 /* Check if we didn't get an access state */
2471 if (!PassedAccessState
)
2473 /* Try to get the generic mapping if we can */
2474 if (ObjectType
) GenericMapping
= &ObjectType
->TypeInfo
.GenericMapping
;
2476 /* Use our built-in access state */
2477 PassedAccessState
= &TempBuffer
->LocalAccessState
;
2478 Status
= SeCreateAccessState(&TempBuffer
->LocalAccessState
,
2479 &TempBuffer
->AuxData
,
2482 if (!NT_SUCCESS(Status
)) goto Quickie
;
2485 /* Get the security descriptor */
2486 if (TempBuffer
->ObjectCreateInfo
.SecurityDescriptor
)
2488 /* Save it in the access state */
2489 PassedAccessState
->SecurityDescriptor
=
2490 TempBuffer
->ObjectCreateInfo
.SecurityDescriptor
;
2493 /* Now do the lookup */
2494 Status
= ObpLookupObjectName(TempBuffer
->ObjectCreateInfo
.RootDirectory
,
2496 TempBuffer
->ObjectCreateInfo
.Attributes
,
2500 TempBuffer
->ObjectCreateInfo
.SecurityQos
,
2503 &TempBuffer
->LookupContext
,
2505 if (!NT_SUCCESS(Status
))
2507 /* Cleanup after lookup */
2508 ObpReleaseLookupContext(&TempBuffer
->LookupContext
);
2512 /* Check if this object has create information */
2513 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
2514 if (ObjectHeader
->Flags
& OB_FLAG_CREATE_INFO
)
2516 /* Then we are creating a new handle */
2517 OpenReason
= ObCreateHandle
;
2519 /* Check if we still have create info */
2520 if (ObjectHeader
->ObjectCreateInfo
)
2523 ObpFreeObjectCreateInformation(ObjectHeader
->
2525 ObjectHeader
->ObjectCreateInfo
= NULL
;
2530 /* Otherwise, we are merely opening it */
2531 OpenReason
= ObOpenHandle
;
2534 /* Check if we have invalid object attributes */
2535 if (ObjectHeader
->Type
->TypeInfo
.InvalidAttributes
&
2536 TempBuffer
->ObjectCreateInfo
.Attributes
)
2538 /* Set failure code */
2539 Status
= STATUS_INVALID_PARAMETER
;
2541 /* Cleanup after lookup */
2542 ObpReleaseLookupContext(&TempBuffer
->LookupContext
);
2544 /* Dereference the object */
2545 ObDereferenceObject(Object
);
2549 /* Create the actual handle now */
2550 Status
= ObpCreateHandle(OpenReason
,
2555 TempBuffer
->ObjectCreateInfo
.Attributes
,
2556 &TempBuffer
->LookupContext
,
2560 if (!NT_SUCCESS(Status
)) ObDereferenceObject(Object
);
2564 /* Delete the access state */
2565 if (PassedAccessState
== &TempBuffer
->LocalAccessState
)
2567 SeDeleteAccessState(PassedAccessState
);
2571 /* Release the object attributes and temporary buffer */
2572 ObpReleaseObjectCreateInformation(&TempBuffer
->ObjectCreateInfo
);
2573 if (ObjectName
.Buffer
) ObpFreeObjectNameBuffer(&ObjectName
);
2574 ExFreePoolWithTag(TempBuffer
, TAG_OB_TEMP_STORAGE
);
2577 OBTRACE(OB_HANDLE_DEBUG
,
2578 "%s - returning Object %p with PC S: %lx %lx\n",
2581 Object
? OBJECT_TO_OBJECT_HEADER(Object
)->PointerCount
: -1,
2587 * @name ObOpenObjectByPointer
2590 * The ObOpenObjectByPointer routine <FILLMEIN>
2595 * @param HandleAttributes
2598 * @param PassedAccessState
2601 * @param DesiredAccess
2613 * @return <FILLMEIN>.
2620 ObOpenObjectByPointer(IN PVOID Object
,
2621 IN ULONG HandleAttributes
,
2622 IN PACCESS_STATE PassedAccessState
,
2623 IN ACCESS_MASK DesiredAccess
,
2624 IN POBJECT_TYPE ObjectType
,
2625 IN KPROCESSOR_MODE AccessMode
,
2628 POBJECT_HEADER Header
;
2630 ACCESS_STATE AccessState
;
2631 AUX_ACCESS_DATA AuxData
;
2634 /* Assume failure */
2637 /* Reference the object */
2638 Status
= ObReferenceObjectByPointer(Object
,
2642 if (!NT_SUCCESS(Status
)) return Status
;
2644 /* Get the Header Info */
2645 Header
= OBJECT_TO_OBJECT_HEADER(Object
);
2647 /* Check if we didn't get an access state */
2648 if (!PassedAccessState
)
2650 /* Use our built-in access state */
2651 PassedAccessState
= &AccessState
;
2652 Status
= SeCreateAccessState(&AccessState
,
2655 &Header
->Type
->TypeInfo
.GenericMapping
);
2656 if (!NT_SUCCESS(Status
))
2659 ObDereferenceObject(Object
);
2664 /* Check if we have invalid object attributes */
2665 if (Header
->Type
->TypeInfo
.InvalidAttributes
& HandleAttributes
)
2667 /* Delete the access state */
2668 if (PassedAccessState
== &AccessState
)
2670 SeDeleteAccessState(PassedAccessState
);
2673 /* Dereference the object */
2674 ObDereferenceObject(Object
);
2675 return STATUS_INVALID_PARAMETER
;
2678 /* Create the handle */
2679 Status
= ObpCreateHandle(ObOpenHandle
,
2689 if (!NT_SUCCESS(Status
)) ObDereferenceObject(Object
);
2691 /* Delete the access state */
2692 if (PassedAccessState
== &AccessState
)
2694 SeDeleteAccessState(PassedAccessState
);
2698 OBTRACE(OB_HANDLE_DEBUG
,
2699 "%s - returning Object with PC S: %lx %lx\n",
2701 OBJECT_TO_OBJECT_HEADER(Object
)->PointerCount
,
2707 * @name ObFindHandleForObject
2710 * The ObFindHandleForObject routine <FILLMEIN>
2721 * @param HandleInformation
2724 * @param HandleReturn
2727 * @return <FILLMEIN>.
2734 ObFindHandleForObject(IN PEPROCESS Process
,
2736 IN POBJECT_TYPE ObjectType
,
2737 IN POBJECT_HANDLE_INFORMATION HandleInformation
,
2740 OBP_FIND_HANDLE_DATA FindData
;
2741 BOOLEAN Result
= FALSE
;
2744 /* Make sure we have an object table */
2745 ObjectTable
= ObReferenceProcessHandleTable(Process
);
2748 /* Check if we have an object */
2751 /* Set its header */
2752 FindData
.ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
2756 /* Otherwise, no object to match*/
2757 FindData
.ObjectHeader
= NULL
;
2760 /* Set other information */
2761 FindData
.ObjectType
= ObjectType
;
2762 FindData
.HandleInformation
= HandleInformation
;
2764 /* Enumerate the handle table */
2765 if (ExEnumHandleTable(Process
->ObjectTable
,
2766 ObpEnumFindHandleProcedure
,
2774 /* Let go of the table */
2775 ObDereferenceProcessHandleTable(Process
);
2778 /* Return the result */
2783 * @name ObInsertObject
2786 * The ObInsertObject routine <FILLMEIN>
2791 * @param PassedAccessState
2794 * @param DesiredAccess
2797 * @param AdditionalReferences
2800 * @param ReferencedObject
2806 * @return <FILLMEIN>.
2813 ObInsertObject(IN PVOID Object
,
2814 IN PACCESS_STATE AccessState OPTIONAL
,
2815 IN ACCESS_MASK DesiredAccess
,
2816 IN ULONG ObjectPointerBias
,
2817 OUT PVOID
*NewObject OPTIONAL
,
2820 POBJECT_CREATE_INFORMATION ObjectCreateInfo
;
2821 POBJECT_HEADER ObjectHeader
;
2822 POBJECT_TYPE ObjectType
;
2823 PUNICODE_STRING ObjectName
;
2825 PSECURITY_DESCRIPTOR ParentDescriptor
= NULL
;
2826 BOOLEAN SdAllocated
= FALSE
;
2827 POBJECT_HEADER_NAME_INFO ObjectNameInfo
;
2828 OBP_LOOKUP_CONTEXT Context
;
2829 ACCESS_STATE LocalAccessState
;
2830 AUX_ACCESS_DATA AuxData
;
2831 OB_OPEN_REASON OpenReason
;
2832 KPROCESSOR_MODE PreviousMode
;
2833 NTSTATUS Status
= STATUS_SUCCESS
, RealStatus
;
2834 BOOLEAN IsNewObject
;
2837 /* Get the Header */
2838 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
2840 /* Detect invalid insert */
2841 if (!(ObjectHeader
->Flags
& OB_FLAG_CREATE_INFO
))
2843 /* Display warning and break into debugger */
2844 DPRINT1("OB: Attempting to insert existing object %08x\n", Object
);
2847 /* Allow debugger to continue */
2848 ObDereferenceObject(Object
);
2849 return STATUS_INVALID_PARAMETER
;
2852 /* Get the create and name info, as well as the object type */
2853 ObjectCreateInfo
= ObjectHeader
->ObjectCreateInfo
;
2854 ObjectNameInfo
= ObpReferenceNameInfo(ObjectHeader
);
2855 ObjectType
= ObjectHeader
->Type
;
2858 /* Check if this is an named object */
2859 if ((ObjectNameInfo
) && (ObjectNameInfo
->Name
.Buffer
))
2861 /* Get the object name */
2862 ObjectName
= &ObjectNameInfo
->Name
;
2867 ((ObjectPointerBias
== 0) &&
2868 (ObjectName
== NULL
) &&
2869 (ObjectType
->TypeInfo
.SecurityRequired
) &&
2870 (NewObject
== NULL
)));
2872 /* Check if the object is unnamed and also doesn't have security */
2873 PreviousMode
= KeGetPreviousMode();
2874 if (!(ObjectType
->TypeInfo
.SecurityRequired
) && !(ObjectName
))
2876 /* Assume failure */
2878 ObjectHeader
->ObjectCreateInfo
= NULL
;
2880 /* Create the handle */
2881 Status
= ObpCreateUnnamedHandle(Object
,
2883 ObjectPointerBias
+ 1,
2884 ObjectCreateInfo
->Attributes
,
2889 /* Free the create information */
2890 ObpFreeObjectCreateInformation(ObjectCreateInfo
);
2892 /* Release the object name information */
2893 ObpDereferenceNameInfo(ObjectNameInfo
);
2895 /* Remove the extra keep-alive reference */
2896 ObDereferenceObject(Object
);
2899 OBTRACE(OB_HANDLE_DEBUG
,
2900 "%s - returning Object with PC S: %lx %lx\n",
2902 ObjectHeader
->PointerCount
,
2907 /* Check if we didn't get an access state */
2910 /* Use our built-in access state */
2911 AccessState
= &LocalAccessState
;
2912 Status
= SeCreateAccessState(&LocalAccessState
,
2915 &ObjectType
->TypeInfo
.GenericMapping
);
2916 if (!NT_SUCCESS(Status
))
2919 ObpDereferenceNameInfo(ObjectNameInfo
);
2920 ObDereferenceObject(Object
);
2925 /* Save the security descriptor */
2926 AccessState
->SecurityDescriptor
= ObjectCreateInfo
->SecurityDescriptor
;
2928 /* Validate the access mask */
2929 Status
= ObpValidateAccessMask(AccessState
);
2930 if (!NT_SUCCESS(Status
))
2933 ObpDereferenceNameInfo(ObjectNameInfo
);
2934 ObDereferenceObject(Object
);
2938 /* Setup a lookup context */
2939 ObpInitializeLookupContext(&Context
);
2940 InsertObject
= Object
;
2941 OpenReason
= ObCreateHandle
;
2943 /* Check if the object is named */
2947 Status
= ObpLookupObjectName(ObjectCreateInfo
->RootDirectory
,
2949 ObjectCreateInfo
->Attributes
,
2951 (ObjectHeader
->Flags
& OB_FLAG_KERNEL_MODE
) ?
2952 KernelMode
: UserMode
,
2953 ObjectCreateInfo
->ParseContext
,
2954 ObjectCreateInfo
->SecurityQos
,
2960 /* Check if we found an object that doesn't match the one requested */
2961 if ((NT_SUCCESS(Status
)) && (InsertObject
) && (Object
!= InsertObject
))
2963 /* This means we're opening an object, not creating a new one */
2964 OpenReason
= ObOpenHandle
;
2966 /* Make sure the caller said it's OK to do this */
2967 if (ObjectCreateInfo
->Attributes
& OBJ_OPENIF
)
2969 /* He did, but did he want this type? */
2970 if (ObjectType
!= OBJECT_TO_OBJECT_HEADER(InsertObject
)->Type
)
2972 /* Wrong type, so fail */
2973 Status
= STATUS_OBJECT_TYPE_MISMATCH
;
2977 /* Right type, so warn */
2978 Status
= STATUS_OBJECT_NAME_EXISTS
;
2983 /* Check if this was a symbolic link */
2984 if (OBJECT_TO_OBJECT_HEADER(InsertObject
)->Type
==
2987 /* Dereference it */
2988 ObDereferenceObject(InsertObject
);
2991 /* Caller wanted to create a new object, fail */
2992 Status
= STATUS_OBJECT_NAME_COLLISION
;
2996 /* Check if anything until now failed */
2997 if (!NT_SUCCESS(Status
))
2999 /* Cleanup after lookup */
3000 ObpReleaseLookupContext(&Context
);
3002 /* Remove query reference that we added */
3003 ObpDereferenceNameInfo(ObjectNameInfo
);
3005 /* Dereference the object and delete the access state */
3006 ObDereferenceObject(Object
);
3007 if (AccessState
== &LocalAccessState
)
3009 /* We used a local one; delete it */
3010 SeDeleteAccessState(AccessState
);
3013 /* Return failure code */
3018 /* Check if this is a symbolic link */
3019 if (ObjectType
== ObSymbolicLinkType
)
3021 /* Create the internal name */
3022 ObpCreateSymbolicLinkName(Object
);
3027 /* Now check if this object is being created */
3028 if (InsertObject
== Object
)
3030 /* Check if it's named or forces security */
3031 if ((ObjectName
) || (ObjectType
->TypeInfo
.SecurityRequired
))
3033 /* Make sure it's inserted into an object directory */
3034 if ((ObjectNameInfo
) && (ObjectNameInfo
->Directory
))
3036 /* Get the current descriptor */
3037 ObGetObjectSecurity(ObjectNameInfo
->Directory
,
3043 Status
= ObAssignSecurity(AccessState
,
3048 /* Check if we captured one */
3049 if (ParentDescriptor
)
3051 /* We did, release it */
3052 ObReleaseObjectSecurity(ParentDescriptor
, SdAllocated
);
3054 else if (NT_SUCCESS(Status
))
3056 /* Other we didn't, but we were able to use the current SD */
3057 SeReleaseSecurityDescriptor(ObjectCreateInfo
->SecurityDescriptor
,
3058 ObjectCreateInfo
->ProbeMode
,
3061 /* Clear the current one */
3062 AccessState
->SecurityDescriptor
=
3063 ObjectCreateInfo
->SecurityDescriptor
= NULL
;
3067 /* Check if anything until now failed */
3068 if (!NT_SUCCESS(Status
))
3070 /* Check if the directory was added */
3071 if (Context
.DirectoryLocked
)
3073 /* Weird case where we need to do a manual delete */
3074 DPRINT1("Unhandled path\n");
3078 /* Cleanup the lookup */
3079 ObpReleaseLookupContext(&Context
);
3081 /* Remove query reference that we added */
3082 ObpDereferenceNameInfo(ObjectNameInfo
);
3084 /* Dereference the object and delete the access state */
3085 ObDereferenceObject(Object
);
3086 if (AccessState
== &LocalAccessState
)
3088 /* We used a local one; delete it */
3089 SeDeleteAccessState(AccessState
);
3092 /* Return failure code */
3098 /* Save the actual status until here */
3099 RealStatus
= Status
;
3101 /* Check if caller wants us to create a handle */
3102 ObjectHeader
->ObjectCreateInfo
= NULL
;
3105 /* Create the handle */
3106 Status
= ObpCreateHandle(OpenReason
,
3110 ObjectPointerBias
+ 1,
3111 ObjectCreateInfo
->Attributes
,
3116 if (!NT_SUCCESS(Status
))
3118 /* If the object had a name, backout everything */
3119 if (ObjectName
) ObpDeleteNameCheck(Object
);
3121 /* Return the status of the failure */
3123 RealStatus
= Status
;
3126 /* Remove a query reference */
3127 ObpDereferenceNameInfo(ObjectNameInfo
);
3129 /* Remove the extra keep-alive reference */
3130 ObDereferenceObject(Object
);
3134 /* Otherwise, lock the object */
3135 ObpAcquireObjectLock(ObjectHeader
);
3137 /* And charge quota for the process to make it appear as used */
3138 RealStatus
= ObpChargeQuotaForObject(ObjectHeader
,
3142 /* Release the lock */
3143 ObpReleaseObjectLock(ObjectHeader
);
3145 /* Check if we failed and dereference the object if so */
3146 if (!NT_SUCCESS(RealStatus
)) ObDereferenceObject(Object
);
3149 /* We can delete the Create Info now */
3150 ObpFreeObjectCreateInformation(ObjectCreateInfo
);
3152 /* Check if we created our own access state and delete it if so */
3153 if (AccessState
== &LocalAccessState
) SeDeleteAccessState(AccessState
);
3155 /* Return status code */
3156 OBTRACE(OB_HANDLE_DEBUG
,
3157 "%s - returning Object with PC RS/S: %lx %lx %lx\n",
3159 OBJECT_TO_OBJECT_HEADER(Object
)->PointerCount
,
3160 RealStatus
, Status
);
3165 * @name ObCloseHandle
3166 * @implemented NT5.1
3168 * The ObCloseHandle routine <FILLMEIN>
3176 * @return <FILLMEIN>.
3183 ObCloseHandle(IN HANDLE Handle
,
3184 IN KPROCESSOR_MODE AccessMode
)
3186 /* Call the internal API */
3187 return ObpCloseHandle(Handle
, AccessMode
);
3194 * The NtClose routine <FILLMEIN>
3199 * @return <FILLMEIN>.
3206 NtClose(IN HANDLE Handle
)
3208 /* Call the internal API */
3209 return ObpCloseHandle(Handle
, ExGetPreviousMode());
3214 NtDuplicateObject(IN HANDLE SourceProcessHandle
,
3215 IN HANDLE SourceHandle
,
3216 IN HANDLE TargetProcessHandle OPTIONAL
,
3217 OUT PHANDLE TargetHandle OPTIONAL
,
3218 IN ACCESS_MASK DesiredAccess
,
3219 IN ULONG HandleAttributes
,
3222 PEPROCESS SourceProcess
, TargetProcess
, Target
;
3224 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3226 OBTRACE(OB_HANDLE_DEBUG
,
3227 "%s - Duplicating handle: %lx for %lx into %lx.\n",
3230 SourceProcessHandle
,
3231 TargetProcessHandle
);
3233 /* Check if we have a target handle */
3234 if ((TargetHandle
) && (PreviousMode
!= KernelMode
))
3239 /* Probe the handle and assume failure */
3240 ProbeForWriteHandle(TargetHandle
);
3241 *TargetHandle
= NULL
;
3243 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3245 /* Return the exception code */
3246 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3251 /* Now reference the input handle */
3252 Status
= ObReferenceObjectByHandle(SourceProcessHandle
,
3256 (PVOID
*)&SourceProcess
,
3258 if (!NT_SUCCESS(Status
)) return(Status
);
3260 /* Check if got a target handle */
3261 if (TargetProcessHandle
)
3263 /* Now reference the output handle */
3264 Status
= ObReferenceObjectByHandle(TargetProcessHandle
,
3268 (PVOID
*)&TargetProcess
,
3270 if (NT_SUCCESS(Status
))
3272 /* Use this target process */
3273 Target
= TargetProcess
;
3277 /* No target process */
3283 /* No target process */
3284 Status
= STATUS_SUCCESS
;
3288 /* Call the internal routine */
3289 Status
= ObDuplicateObject(SourceProcess
,
3298 /* Check if the caller wanted the return handle */
3301 /* Protect the write to user mode */
3304 /* Write the new handle */
3305 *TargetHandle
= hTarget
;
3307 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3309 /* Otherwise, get the exception code */
3310 Status
= _SEH2_GetExceptionCode();
3315 /* Dereference the processes */
3316 OBTRACE(OB_HANDLE_DEBUG
,
3317 "%s - Duplicated handle: %lx into %lx S %lx\n",
3320 TargetProcessHandle
,
3322 if (Target
) ObDereferenceObject(Target
);
3323 ObDereferenceObject(SourceProcess
);
3327 #undef ObIsKernelHandle
3330 ObIsKernelHandle(IN HANDLE Handle
)
3332 /* We know we're kernel mode, so just check for the kernel handle flag */
3333 return (BOOLEAN
)(((ULONG_PTR
)Handle
& KERNEL_HANDLE_FLAG
) != 0);