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
);
1758 /* We failed, quit the critical region */
1759 KeLeaveCriticalRegion();
1762 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1764 /* Check if we have a valid handle that's not the process or thread */
1766 (Handle
!= NtCurrentProcess()) &&
1767 (Handle
!= NtCurrentThread()))
1769 /* Check if we came from user mode */
1770 if (AccessMode
!= KernelMode
)
1772 /* Check if we have no debug port */
1773 if (Process
->DebugPort
)
1775 /* Make sure we're not attached */
1776 if (!KeIsAttachedProcess())
1778 /* Raise an exception */
1779 return KeRaiseUserException(STATUS_INVALID_HANDLE
);
1785 /* This is kernel mode. Check if we're exiting */
1786 if (!(PsIsThreadTerminating(PsGetCurrentThread())) &&
1789 /* Check if the debugger is enabled */
1790 if (KdDebuggerEnabled
)
1793 KeBugCheckEx(INVALID_KERNEL_HANDLE
, (ULONG_PTR
)Handle
, 1, 0, 0);
1799 /* Set invalid status */
1800 Status
= STATUS_INVALID_HANDLE
;
1804 OBTRACE(OB_HANDLE_DEBUG
,
1805 "%s - Closed handle: %lx S: %lx\n",
1806 __FUNCTION__
, Handle
, Status
);
1811 * @name ObpSetHandleAttributes
1813 * The ObpSetHandleAttributes routine <FILLMEIN>
1815 * @param HandleTableEntry
1821 * @return <FILLMEIN>.
1828 ObpSetHandleAttributes(IN OUT PHANDLE_TABLE_ENTRY HandleTableEntry
,
1829 IN ULONG_PTR Context
)
1831 POBP_SET_HANDLE_ATTRIBUTES_CONTEXT SetHandleInfo
= (PVOID
)Context
;
1832 POBJECT_HEADER ObjectHeader
= ObpGetHandleObject(HandleTableEntry
);
1834 /* Check if making the handle inheritable */
1835 if (SetHandleInfo
->Information
.Inherit
)
1837 /* Check if inheriting is not supported for this object */
1838 if (ObjectHeader
->Type
->TypeInfo
.InvalidAttributes
& OBJ_INHERIT
)
1840 /* Fail without changing anything */
1845 HandleTableEntry
->ObAttributes
|= OBJ_INHERIT
;
1849 /* Otherwise this implies we're removing the flag */
1850 HandleTableEntry
->ObAttributes
&= ~OBJ_INHERIT
;
1853 /* Check if making the handle protected */
1854 if (SetHandleInfo
->Information
.ProtectFromClose
)
1857 HandleTableEntry
->GrantedAccess
|= ObpAccessProtectCloseBit
;
1861 /* Otherwise, remove it */
1862 HandleTableEntry
->GrantedAccess
&= ~ObpAccessProtectCloseBit
;
1865 /* Return success */
1870 * @name ObpCloseHandleCallback
1872 * The ObpCloseHandleCallback routine <FILLMEIN>
1874 * @param HandleTable
1880 * @param GrantedAccess
1886 * @return <FILLMEIN>.
1893 ObpCloseHandleCallback(IN PHANDLE_TABLE_ENTRY HandleTableEntry
,
1897 POBP_CLOSE_HANDLE_CONTEXT CloseContext
= (POBP_CLOSE_HANDLE_CONTEXT
)Context
;
1899 /* Simply decrement the handle count */
1900 ObpCloseHandleTableEntry(CloseContext
->HandleTable
,
1903 CloseContext
->AccessMode
,
1909 * @name ObpDuplicateHandleCallback
1911 * The ObpDuplicateHandleCallback routine <FILLMEIN>
1913 * @param HandleTable
1916 * @param HandleTableEntry
1922 * @return <FILLMEIN>.
1929 ObpDuplicateHandleCallback(IN PEPROCESS Process
,
1930 IN PHANDLE_TABLE HandleTable
,
1931 IN PHANDLE_TABLE_ENTRY OldEntry
,
1932 IN PHANDLE_TABLE_ENTRY HandleTableEntry
)
1934 POBJECT_HEADER ObjectHeader
;
1935 BOOLEAN Ret
= FALSE
;
1936 ACCESS_STATE AccessState
;
1940 /* Make sure that the handle is inheritable */
1941 Ret
= (HandleTableEntry
->ObAttributes
& OBJ_INHERIT
) != 0;
1944 /* Get the object header */
1945 ObjectHeader
= ObpGetHandleObject(HandleTableEntry
);
1947 /* Increment the pointer count */
1948 InterlockedIncrement(&ObjectHeader
->PointerCount
);
1950 /* Release the handle lock */
1951 ExUnlockHandleTableEntry(HandleTable
, OldEntry
);
1953 /* Setup the access state */
1954 AccessState
.PreviouslyGrantedAccess
= HandleTableEntry
->GrantedAccess
;
1956 /* Call the shared routine for incrementing handles */
1957 Status
= ObpIncrementHandleCount(&ObjectHeader
->Body
,
1960 HandleTableEntry
->ObAttributes
& OBJ_HANDLE_ATTRIBUTES
,
1963 if (!NT_SUCCESS(Status
))
1965 /* Return failure */
1966 ObDereferenceObject(&ObjectHeader
->Body
);
1972 /* Release the handle lock */
1973 ExUnlockHandleTableEntry(HandleTable
, OldEntry
);
1976 /* Return duplication result */
1982 ObClearProcessHandleTable(IN PEPROCESS Process
)
1988 * @name ObpCreateHandleTable
1990 * The ObpCreateHandleTable routine <FILLMEIN>
1998 * @return <FILLMEIN>.
2005 ObInitProcess(IN PEPROCESS Parent OPTIONAL
,
2006 IN PEPROCESS Process
)
2008 PHANDLE_TABLE ParentTable
, ObjectTable
;
2010 /* Check for a parent */
2013 /* Reference the parent's table */
2014 ParentTable
= ObReferenceProcessHandleTable(Parent
);
2015 if (!ParentTable
) return STATUS_PROCESS_IS_TERMINATING
;
2018 ObjectTable
= ExDupHandleTable(Process
,
2020 ObpDuplicateHandleCallback
,
2025 /* Otherwise just create a new table */
2027 ObjectTable
= ExCreateHandleTable(Process
);
2030 /* Make sure we have a table */
2034 Process
->ObjectTable
= ObjectTable
;
2036 /* Check for auditing */
2037 if (SeDetailedAuditingWithToken(NULL
))
2040 DPRINT1("Need auditing!\n");
2043 /* Get rid of the old table now */
2044 if (ParentTable
) ObDereferenceProcessHandleTable(Parent
);
2047 return STATUS_SUCCESS
;
2052 Process
->ObjectTable
= NULL
;
2053 if (ParentTable
) ObDereferenceProcessHandleTable(Parent
);
2054 return STATUS_INSUFFICIENT_RESOURCES
;
2059 * @name ObKillProcess
2061 * The ObKillProcess routine <FILLMEIN>
2073 ObKillProcess(IN PEPROCESS Process
)
2075 PHANDLE_TABLE HandleTable
;
2076 OBP_CLOSE_HANDLE_CONTEXT Context
;
2080 /* Wait for process rundown and then complete it */
2081 ExWaitForRundownProtectionRelease(&Process
->RundownProtect
);
2082 ExRundownCompleted(&Process
->RundownProtect
);
2084 /* Get the object table */
2085 HandleTable
= Process
->ObjectTable
;
2086 if (!HandleTable
) return;
2088 /* Disable hard errors while we close handles */
2089 HardErrors
= IoSetThreadHardErrorMode(FALSE
);
2091 /* Enter a critical region */
2092 KeEnterCriticalRegion();
2094 /* Fill out the context */
2095 Context
.AccessMode
= KernelMode
;
2096 Context
.HandleTable
= HandleTable
;
2098 /* Sweep the handle table to close all handles */
2099 ExSweepHandleTable(HandleTable
,
2100 ObpCloseHandleCallback
,
2102 ASSERT(HandleTable
->HandleCount
== 0);
2104 /* Leave the critical region */
2105 KeLeaveCriticalRegion();
2107 /* Re-enable hard errors */
2108 IoSetThreadHardErrorMode(HardErrors
);
2110 /* Destroy the object table */
2111 Process
->ObjectTable
= NULL
;
2112 ExDestroyHandleTable(HandleTable
, NULL
);
2117 ObDuplicateObject(IN PEPROCESS SourceProcess
,
2118 IN HANDLE SourceHandle
,
2119 IN PEPROCESS TargetProcess OPTIONAL
,
2120 IN PHANDLE TargetHandle OPTIONAL
,
2121 IN ACCESS_MASK DesiredAccess
,
2122 IN ULONG HandleAttributes
,
2124 IN KPROCESSOR_MODE PreviousMode
)
2126 HANDLE_TABLE_ENTRY NewHandleEntry
;
2127 BOOLEAN AttachedToProcess
= FALSE
;
2129 POBJECT_HEADER ObjectHeader
;
2130 POBJECT_TYPE ObjectType
;
2132 KAPC_STATE ApcState
;
2134 ACCESS_MASK TargetAccess
, SourceAccess
;
2135 ACCESS_STATE AccessState
;
2136 PACCESS_STATE PassedAccessState
= NULL
;
2137 AUX_ACCESS_DATA AuxData
;
2138 PHANDLE_TABLE HandleTable
;
2139 OBJECT_HANDLE_INFORMATION HandleInformation
;
2142 OBTRACE(OB_HANDLE_DEBUG
,
2143 "%s - Duplicating handle: %lx for %p into %p\n",
2149 /* Assume failure */
2150 if (TargetHandle
) *TargetHandle
= NULL
;
2152 /* Check if we're not duplicating the same access */
2153 if (!(Options
& DUPLICATE_SAME_ACCESS
))
2155 /* Validate the desired access */
2156 Status
= STATUS_SUCCESS
; //ObpValidateDesiredAccess(DesiredAccess);
2157 if (!NT_SUCCESS(Status
)) return Status
;
2160 /* Reference the object table */
2161 HandleTable
= ObReferenceProcessHandleTable(SourceProcess
);
2162 if (!HandleTable
) return STATUS_PROCESS_IS_TERMINATING
;
2164 /* Reference the process object */
2165 Status
= ObpReferenceProcessObjectByHandle(SourceHandle
,
2172 if (!NT_SUCCESS(Status
))
2175 ObDereferenceProcessHandleTable(SourceProcess
);
2180 /* Check if we have to don't have to audit object close */
2181 if (!(HandleInformation
.HandleAttributes
& OBJ_AUDIT_OBJECT_CLOSE
))
2183 /* Then there is no audit mask */
2188 /* Check if there's no target process */
2191 /* Check if the caller wanted actual duplication */
2192 if (!(Options
& DUPLICATE_CLOSE_SOURCE
))
2194 /* Invalid request */
2195 Status
= STATUS_INVALID_PARAMETER
;
2199 /* Otherwise, do the attach */
2200 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
2202 /* Close the handle and detach */
2203 NtClose(SourceHandle
);
2204 KeUnstackDetachProcess(&ApcState
);
2208 ObDereferenceProcessHandleTable(SourceProcess
);
2209 ObDereferenceObject(SourceObject
);
2213 /* Get the target handle table */
2214 HandleTable
= ObReferenceProcessHandleTable(TargetProcess
);
2217 /* Check if the caller wanted us to close the handle */
2218 if (Options
& DUPLICATE_CLOSE_SOURCE
)
2221 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
2223 /* Close the handle and detach */
2224 NtClose(SourceHandle
);
2225 KeUnstackDetachProcess(&ApcState
);
2229 ObDereferenceProcessHandleTable(SourceProcess
);
2230 ObDereferenceObject(SourceObject
);
2231 return STATUS_PROCESS_IS_TERMINATING
;
2234 /* Get the source access */
2235 SourceAccess
= HandleInformation
.GrantedAccess
;
2237 /* Check if we're not in the target process */
2238 if (TargetProcess
!= PsGetCurrentProcess())
2241 KeStackAttachProcess(&TargetProcess
->Pcb
, &ApcState
);
2242 AttachedToProcess
= TRUE
;
2245 /* Check if we're duplicating the attributes */
2246 if (Options
& DUPLICATE_SAME_ATTRIBUTES
)
2248 /* Duplicate them */
2249 HandleAttributes
= HandleInformation
.HandleAttributes
;
2253 /* Don't allow caller to bypass auditing */
2254 HandleAttributes
|= HandleInformation
.HandleAttributes
&
2255 OBJ_AUDIT_OBJECT_CLOSE
;
2258 /* Check if we're duplicating the access */
2259 if (Options
& DUPLICATE_SAME_ACCESS
) DesiredAccess
= SourceAccess
;
2261 /* Get object data */
2262 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(SourceObject
);
2263 ObjectType
= ObjectHeader
->Type
;
2265 /* Fill out the entry */
2266 RtlZeroMemory(&NewHandleEntry
, sizeof(HANDLE_TABLE_ENTRY
));
2267 NewHandleEntry
.Object
= ObjectHeader
;
2268 NewHandleEntry
.ObAttributes
|= (HandleAttributes
& OBJ_HANDLE_ATTRIBUTES
);
2270 /* Check if we're using a generic mask */
2271 if (DesiredAccess
& GENERIC_ACCESS
)
2274 RtlMapGenericMask(&DesiredAccess
,
2275 &ObjectType
->TypeInfo
.GenericMapping
);
2278 /* Set the target access, always propagate ACCESS_SYSTEM_SECURITY */
2279 TargetAccess
= DesiredAccess
& (ObjectType
->TypeInfo
.ValidAccessMask
|
2280 ACCESS_SYSTEM_SECURITY
);
2281 NewHandleEntry
.GrantedAccess
= TargetAccess
;
2283 /* Check if we're asking for new access */
2284 if (TargetAccess
& ~SourceAccess
)
2286 /* We are. We need the security procedure to validate this */
2287 if (ObjectType
->TypeInfo
.SecurityProcedure
== SeDefaultObjectMethod
)
2289 /* Use our built-in access state */
2290 PassedAccessState
= &AccessState
;
2291 Status
= SeCreateAccessState(&AccessState
,
2294 &ObjectType
->TypeInfo
.GenericMapping
);
2298 /* Otherwise we can't allow this privilege elevation */
2299 Status
= STATUS_ACCESS_DENIED
;
2304 /* We don't need an access state */
2305 Status
= STATUS_SUCCESS
;
2308 /* Make sure the access state was created OK */
2309 if (NT_SUCCESS(Status
))
2311 /* Add a new handle */
2312 Status
= ObpIncrementHandleCount(SourceObject
,
2316 PsGetCurrentProcess(),
2320 /* Check if we were attached */
2321 if (AttachedToProcess
)
2323 /* We can safely detach now */
2324 KeUnstackDetachProcess(&ApcState
);
2325 AttachedToProcess
= FALSE
;
2328 /* Check if we have to close the source handle */
2329 if (Options
& DUPLICATE_CLOSE_SOURCE
)
2331 /* Attach and close */
2332 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
2333 NtClose(SourceHandle
);
2334 KeUnstackDetachProcess(&ApcState
);
2337 /* Check if we had an access state */
2338 if (PassedAccessState
) SeDeleteAccessState(PassedAccessState
);
2340 /* Now check if incrementing actually failed */
2341 if (!NT_SUCCESS(Status
))
2343 /* Dereference handle tables */
2344 ObDereferenceProcessHandleTable(SourceProcess
);
2345 ObDereferenceProcessHandleTable(TargetProcess
);
2347 /* Dereference the source object */
2348 ObDereferenceObject(SourceObject
);
2352 /* Now create the handle */
2353 NewHandle
= ExCreateHandle(HandleTable
, &NewHandleEntry
);
2356 /* Undo the increment */
2357 ObpDecrementHandleCount(SourceObject
,
2362 /* Deference the object and set failure status */
2363 ObDereferenceObject(SourceObject
);
2364 Status
= STATUS_INSUFFICIENT_RESOURCES
;
2367 /* Return the handle */
2368 if (TargetHandle
) *TargetHandle
= NewHandle
;
2370 /* Dereference handle tables */
2371 ObDereferenceProcessHandleTable(SourceProcess
);
2372 ObDereferenceProcessHandleTable(TargetProcess
);
2375 OBTRACE(OB_HANDLE_DEBUG
,
2376 "%s - Duplicated handle: %lx for %p into %p. Source: %p HC PC %lx %lx\n",
2382 ObjectHeader
->PointerCount
,
2383 ObjectHeader
->HandleCount
);
2387 /* PUBLIC FUNCTIONS *********************************************************/
2390 * @name ObOpenObjectByName
2393 * The ObOpenObjectByName routine <FILLMEIN>
2395 * @param ObjectAttributes
2404 * @param PassedAccessState
2407 * @param DesiredAccess
2410 * @param ParseContext
2416 * @return <FILLMEIN>.
2423 ObOpenObjectByName(IN POBJECT_ATTRIBUTES ObjectAttributes
,
2424 IN POBJECT_TYPE ObjectType
,
2425 IN KPROCESSOR_MODE AccessMode
,
2426 IN PACCESS_STATE PassedAccessState
,
2427 IN ACCESS_MASK DesiredAccess
,
2428 IN OUT PVOID ParseContext
,
2431 PVOID Object
= NULL
;
2432 UNICODE_STRING ObjectName
;
2434 POBJECT_HEADER ObjectHeader
;
2435 PGENERIC_MAPPING GenericMapping
= NULL
;
2436 OB_OPEN_REASON OpenReason
;
2437 POB_TEMP_BUFFER TempBuffer
;
2440 /* Assume failure */
2443 /* Check if we didn't get any Object Attributes */
2444 if (!ObjectAttributes
)
2446 /* Fail with special status code */
2447 return STATUS_INVALID_PARAMETER
;
2450 /* Allocate the temporary buffer */
2451 TempBuffer
= ExAllocatePoolWithTag(NonPagedPool
,
2452 sizeof(OB_TEMP_BUFFER
),
2453 TAG_OB_TEMP_STORAGE
);
2454 if (!TempBuffer
) return STATUS_INSUFFICIENT_RESOURCES
;
2456 /* Capture all the info */
2457 Status
= ObpCaptureObjectCreateInformation(ObjectAttributes
,
2460 &TempBuffer
->ObjectCreateInfo
,
2462 if (!NT_SUCCESS(Status
))
2465 ExFreePoolWithTag(TempBuffer
, TAG_OB_TEMP_STORAGE
);
2469 /* Check if we didn't get an access state */
2470 if (!PassedAccessState
)
2472 /* Try to get the generic mapping if we can */
2473 if (ObjectType
) GenericMapping
= &ObjectType
->TypeInfo
.GenericMapping
;
2475 /* Use our built-in access state */
2476 PassedAccessState
= &TempBuffer
->LocalAccessState
;
2477 Status
= SeCreateAccessState(&TempBuffer
->LocalAccessState
,
2478 &TempBuffer
->AuxData
,
2481 if (!NT_SUCCESS(Status
)) goto Quickie
;
2484 /* Get the security descriptor */
2485 if (TempBuffer
->ObjectCreateInfo
.SecurityDescriptor
)
2487 /* Save it in the access state */
2488 PassedAccessState
->SecurityDescriptor
=
2489 TempBuffer
->ObjectCreateInfo
.SecurityDescriptor
;
2492 /* Now do the lookup */
2493 Status
= ObpLookupObjectName(TempBuffer
->ObjectCreateInfo
.RootDirectory
,
2495 TempBuffer
->ObjectCreateInfo
.Attributes
,
2499 TempBuffer
->ObjectCreateInfo
.SecurityQos
,
2502 &TempBuffer
->LookupContext
,
2504 if (!NT_SUCCESS(Status
))
2506 /* Cleanup after lookup */
2507 ObpReleaseLookupContext(&TempBuffer
->LookupContext
);
2511 /* Check if this object has create information */
2512 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
2513 if (ObjectHeader
->Flags
& OB_FLAG_CREATE_INFO
)
2515 /* Then we are creating a new handle */
2516 OpenReason
= ObCreateHandle
;
2518 /* Check if we still have create info */
2519 if (ObjectHeader
->ObjectCreateInfo
)
2522 ObpFreeObjectCreateInformation(ObjectHeader
->
2524 ObjectHeader
->ObjectCreateInfo
= NULL
;
2529 /* Otherwise, we are merely opening it */
2530 OpenReason
= ObOpenHandle
;
2533 /* Check if we have invalid object attributes */
2534 if (ObjectHeader
->Type
->TypeInfo
.InvalidAttributes
&
2535 TempBuffer
->ObjectCreateInfo
.Attributes
)
2537 /* Set failure code */
2538 Status
= STATUS_INVALID_PARAMETER
;
2540 /* Cleanup after lookup */
2541 ObpReleaseLookupContext(&TempBuffer
->LookupContext
);
2543 /* Dereference the object */
2544 ObDereferenceObject(Object
);
2548 /* Create the actual handle now */
2549 Status
= ObpCreateHandle(OpenReason
,
2554 TempBuffer
->ObjectCreateInfo
.Attributes
,
2555 &TempBuffer
->LookupContext
,
2559 if (!NT_SUCCESS(Status
)) ObDereferenceObject(Object
);
2563 /* Delete the access state */
2564 if (PassedAccessState
== &TempBuffer
->LocalAccessState
)
2566 SeDeleteAccessState(PassedAccessState
);
2570 /* Release the object attributes and temporary buffer */
2571 ObpReleaseObjectCreateInformation(&TempBuffer
->ObjectCreateInfo
);
2572 if (ObjectName
.Buffer
) ObpFreeObjectNameBuffer(&ObjectName
);
2573 ExFreePoolWithTag(TempBuffer
, TAG_OB_TEMP_STORAGE
);
2576 OBTRACE(OB_HANDLE_DEBUG
,
2577 "%s - returning Object %p with PC S: %lx %lx\n",
2580 Object
? OBJECT_TO_OBJECT_HEADER(Object
)->PointerCount
: -1,
2586 * @name ObOpenObjectByPointer
2589 * The ObOpenObjectByPointer routine <FILLMEIN>
2594 * @param HandleAttributes
2597 * @param PassedAccessState
2600 * @param DesiredAccess
2612 * @return <FILLMEIN>.
2619 ObOpenObjectByPointer(IN PVOID Object
,
2620 IN ULONG HandleAttributes
,
2621 IN PACCESS_STATE PassedAccessState
,
2622 IN ACCESS_MASK DesiredAccess
,
2623 IN POBJECT_TYPE ObjectType
,
2624 IN KPROCESSOR_MODE AccessMode
,
2627 POBJECT_HEADER Header
;
2629 ACCESS_STATE AccessState
;
2630 AUX_ACCESS_DATA AuxData
;
2633 /* Assume failure */
2636 /* Reference the object */
2637 Status
= ObReferenceObjectByPointer(Object
,
2641 if (!NT_SUCCESS(Status
)) return Status
;
2643 /* Get the Header Info */
2644 Header
= OBJECT_TO_OBJECT_HEADER(Object
);
2646 /* Check if we didn't get an access state */
2647 if (!PassedAccessState
)
2649 /* Use our built-in access state */
2650 PassedAccessState
= &AccessState
;
2651 Status
= SeCreateAccessState(&AccessState
,
2654 &Header
->Type
->TypeInfo
.GenericMapping
);
2655 if (!NT_SUCCESS(Status
))
2658 ObDereferenceObject(Object
);
2663 /* Check if we have invalid object attributes */
2664 if (Header
->Type
->TypeInfo
.InvalidAttributes
& HandleAttributes
)
2666 /* Delete the access state */
2667 if (PassedAccessState
== &AccessState
)
2669 SeDeleteAccessState(PassedAccessState
);
2672 /* Dereference the object */
2673 ObDereferenceObject(Object
);
2674 return STATUS_INVALID_PARAMETER
;
2677 /* Create the handle */
2678 Status
= ObpCreateHandle(ObOpenHandle
,
2688 if (!NT_SUCCESS(Status
)) ObDereferenceObject(Object
);
2690 /* Delete the access state */
2691 if (PassedAccessState
== &AccessState
)
2693 SeDeleteAccessState(PassedAccessState
);
2697 OBTRACE(OB_HANDLE_DEBUG
,
2698 "%s - returning Object with PC S: %lx %lx\n",
2700 OBJECT_TO_OBJECT_HEADER(Object
)->PointerCount
,
2706 * @name ObFindHandleForObject
2709 * The ObFindHandleForObject routine <FILLMEIN>
2720 * @param HandleInformation
2723 * @param HandleReturn
2726 * @return <FILLMEIN>.
2733 ObFindHandleForObject(IN PEPROCESS Process
,
2735 IN POBJECT_TYPE ObjectType
,
2736 IN POBJECT_HANDLE_INFORMATION HandleInformation
,
2739 OBP_FIND_HANDLE_DATA FindData
;
2740 BOOLEAN Result
= FALSE
;
2743 /* Make sure we have an object table */
2744 ObjectTable
= ObReferenceProcessHandleTable(Process
);
2747 /* Check if we have an object */
2750 /* Set its header */
2751 FindData
.ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
2755 /* Otherwise, no object to match*/
2756 FindData
.ObjectHeader
= NULL
;
2759 /* Set other information */
2760 FindData
.ObjectType
= ObjectType
;
2761 FindData
.HandleInformation
= HandleInformation
;
2763 /* Enumerate the handle table */
2764 if (ExEnumHandleTable(Process
->ObjectTable
,
2765 ObpEnumFindHandleProcedure
,
2773 /* Let go of the table */
2774 ObDereferenceProcessHandleTable(Process
);
2777 /* Return the result */
2782 * @name ObInsertObject
2785 * The ObInsertObject routine <FILLMEIN>
2790 * @param PassedAccessState
2793 * @param DesiredAccess
2796 * @param AdditionalReferences
2799 * @param ReferencedObject
2805 * @return <FILLMEIN>.
2812 ObInsertObject(IN PVOID Object
,
2813 IN PACCESS_STATE AccessState OPTIONAL
,
2814 IN ACCESS_MASK DesiredAccess
,
2815 IN ULONG ObjectPointerBias
,
2816 OUT PVOID
*NewObject OPTIONAL
,
2819 POBJECT_CREATE_INFORMATION ObjectCreateInfo
;
2820 POBJECT_HEADER ObjectHeader
;
2821 POBJECT_TYPE ObjectType
;
2822 PUNICODE_STRING ObjectName
;
2824 PSECURITY_DESCRIPTOR ParentDescriptor
= NULL
;
2825 BOOLEAN SdAllocated
= FALSE
;
2826 POBJECT_HEADER_NAME_INFO ObjectNameInfo
;
2827 OBP_LOOKUP_CONTEXT Context
;
2828 ACCESS_STATE LocalAccessState
;
2829 AUX_ACCESS_DATA AuxData
;
2830 OB_OPEN_REASON OpenReason
;
2831 KPROCESSOR_MODE PreviousMode
;
2832 NTSTATUS Status
= STATUS_SUCCESS
, RealStatus
;
2833 BOOLEAN IsNewObject
;
2836 /* Get the Header */
2837 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
2839 /* Detect invalid insert */
2840 if (!(ObjectHeader
->Flags
& OB_FLAG_CREATE_INFO
))
2842 /* Display warning and break into debugger */
2843 DPRINT1("OB: Attempting to insert existing object %08x\n", Object
);
2846 /* Allow debugger to continue */
2847 ObDereferenceObject(Object
);
2848 return STATUS_INVALID_PARAMETER
;
2851 /* Get the create and name info, as well as the object type */
2852 ObjectCreateInfo
= ObjectHeader
->ObjectCreateInfo
;
2853 ObjectNameInfo
= ObpReferenceNameInfo(ObjectHeader
);
2854 ObjectType
= ObjectHeader
->Type
;
2857 /* Check if this is an named object */
2858 if ((ObjectNameInfo
) && (ObjectNameInfo
->Name
.Buffer
))
2860 /* Get the object name */
2861 ObjectName
= &ObjectNameInfo
->Name
;
2866 ((ObjectPointerBias
== 0) &&
2867 (ObjectName
== NULL
) &&
2868 (ObjectType
->TypeInfo
.SecurityRequired
) &&
2869 (NewObject
== NULL
)));
2871 /* Check if the object is unnamed and also doesn't have security */
2872 PreviousMode
= KeGetPreviousMode();
2873 if (!(ObjectType
->TypeInfo
.SecurityRequired
) && !(ObjectName
))
2875 /* Assume failure */
2877 ObjectHeader
->ObjectCreateInfo
= NULL
;
2879 /* Create the handle */
2880 Status
= ObpCreateUnnamedHandle(Object
,
2882 ObjectPointerBias
+ 1,
2883 ObjectCreateInfo
->Attributes
,
2888 /* Free the create information */
2889 ObpFreeObjectCreateInformation(ObjectCreateInfo
);
2891 /* Release the object name information */
2892 ObpDereferenceNameInfo(ObjectNameInfo
);
2894 /* Remove the extra keep-alive reference */
2895 ObDereferenceObject(Object
);
2898 OBTRACE(OB_HANDLE_DEBUG
,
2899 "%s - returning Object with PC S: %lx %lx\n",
2901 ObjectHeader
->PointerCount
,
2906 /* Check if we didn't get an access state */
2909 /* Use our built-in access state */
2910 AccessState
= &LocalAccessState
;
2911 Status
= SeCreateAccessState(&LocalAccessState
,
2914 &ObjectType
->TypeInfo
.GenericMapping
);
2915 if (!NT_SUCCESS(Status
))
2918 ObpDereferenceNameInfo(ObjectNameInfo
);
2919 ObDereferenceObject(Object
);
2924 /* Save the security descriptor */
2925 AccessState
->SecurityDescriptor
= ObjectCreateInfo
->SecurityDescriptor
;
2927 /* Validate the access mask */
2928 Status
= ObpValidateAccessMask(AccessState
);
2929 if (!NT_SUCCESS(Status
))
2932 ObpDereferenceNameInfo(ObjectNameInfo
);
2933 ObDereferenceObject(Object
);
2937 /* Setup a lookup context */
2938 ObpInitializeLookupContext(&Context
);
2939 InsertObject
= Object
;
2940 OpenReason
= ObCreateHandle
;
2942 /* Check if the object is named */
2946 Status
= ObpLookupObjectName(ObjectCreateInfo
->RootDirectory
,
2948 ObjectCreateInfo
->Attributes
,
2950 (ObjectHeader
->Flags
& OB_FLAG_KERNEL_MODE
) ?
2951 KernelMode
: UserMode
,
2952 ObjectCreateInfo
->ParseContext
,
2953 ObjectCreateInfo
->SecurityQos
,
2959 /* Check if we found an object that doesn't match the one requested */
2960 if ((NT_SUCCESS(Status
)) && (InsertObject
) && (Object
!= InsertObject
))
2962 /* This means we're opening an object, not creating a new one */
2963 OpenReason
= ObOpenHandle
;
2965 /* Make sure the caller said it's OK to do this */
2966 if (ObjectCreateInfo
->Attributes
& OBJ_OPENIF
)
2968 /* He did, but did he want this type? */
2969 if (ObjectType
!= OBJECT_TO_OBJECT_HEADER(InsertObject
)->Type
)
2971 /* Wrong type, so fail */
2972 Status
= STATUS_OBJECT_TYPE_MISMATCH
;
2976 /* Right type, so warn */
2977 Status
= STATUS_OBJECT_NAME_EXISTS
;
2982 /* Check if this was a symbolic link */
2983 if (OBJECT_TO_OBJECT_HEADER(InsertObject
)->Type
==
2986 /* Dereference it */
2987 ObDereferenceObject(InsertObject
);
2990 /* Caller wanted to create a new object, fail */
2991 Status
= STATUS_OBJECT_NAME_COLLISION
;
2995 /* Check if anything until now failed */
2996 if (!NT_SUCCESS(Status
))
2998 /* Cleanup after lookup */
2999 ObpReleaseLookupContext(&Context
);
3001 /* Remove query reference that we added */
3002 ObpDereferenceNameInfo(ObjectNameInfo
);
3004 /* Dereference the object and delete the access state */
3005 ObDereferenceObject(Object
);
3006 if (AccessState
== &LocalAccessState
)
3008 /* We used a local one; delete it */
3009 SeDeleteAccessState(AccessState
);
3012 /* Return failure code */
3017 /* Check if this is a symbolic link */
3018 if (ObjectType
== ObSymbolicLinkType
)
3020 /* Create the internal name */
3021 ObpCreateSymbolicLinkName(Object
);
3026 /* Now check if this object is being created */
3027 if (InsertObject
== Object
)
3029 /* Check if it's named or forces security */
3030 if ((ObjectName
) || (ObjectType
->TypeInfo
.SecurityRequired
))
3032 /* Make sure it's inserted into an object directory */
3033 if ((ObjectNameInfo
) && (ObjectNameInfo
->Directory
))
3035 /* Get the current descriptor */
3036 ObGetObjectSecurity(ObjectNameInfo
->Directory
,
3042 Status
= ObAssignSecurity(AccessState
,
3047 /* Check if we captured one */
3048 if (ParentDescriptor
)
3050 /* We did, release it */
3051 ObReleaseObjectSecurity(ParentDescriptor
, SdAllocated
);
3053 else if (NT_SUCCESS(Status
))
3055 /* Other we didn't, but we were able to use the current SD */
3056 SeReleaseSecurityDescriptor(ObjectCreateInfo
->SecurityDescriptor
,
3057 ObjectCreateInfo
->ProbeMode
,
3060 /* Clear the current one */
3061 AccessState
->SecurityDescriptor
=
3062 ObjectCreateInfo
->SecurityDescriptor
= NULL
;
3066 /* Check if anything until now failed */
3067 if (!NT_SUCCESS(Status
))
3069 /* Check if the directory was added */
3070 if (Context
.DirectoryLocked
)
3072 /* Weird case where we need to do a manual delete */
3073 DPRINT1("Unhandled path\n");
3077 /* Cleanup the lookup */
3078 ObpReleaseLookupContext(&Context
);
3080 /* Remove query reference that we added */
3081 ObpDereferenceNameInfo(ObjectNameInfo
);
3083 /* Dereference the object and delete the access state */
3084 ObDereferenceObject(Object
);
3085 if (AccessState
== &LocalAccessState
)
3087 /* We used a local one; delete it */
3088 SeDeleteAccessState(AccessState
);
3091 /* Return failure code */
3097 /* Save the actual status until here */
3098 RealStatus
= Status
;
3100 /* Check if caller wants us to create a handle */
3101 ObjectHeader
->ObjectCreateInfo
= NULL
;
3104 /* Create the handle */
3105 Status
= ObpCreateHandle(OpenReason
,
3109 ObjectPointerBias
+ 1,
3110 ObjectCreateInfo
->Attributes
,
3115 if (!NT_SUCCESS(Status
))
3117 /* If the object had a name, backout everything */
3118 if (ObjectName
) ObpDeleteNameCheck(Object
);
3120 /* Return the status of the failure */
3122 RealStatus
= Status
;
3125 /* Remove a query reference */
3126 ObpDereferenceNameInfo(ObjectNameInfo
);
3128 /* Remove the extra keep-alive reference */
3129 ObDereferenceObject(Object
);
3133 /* Otherwise, lock the object */
3134 ObpAcquireObjectLock(ObjectHeader
);
3136 /* And charge quota for the process to make it appear as used */
3137 RealStatus
= ObpChargeQuotaForObject(ObjectHeader
,
3141 /* Release the lock */
3142 ObpReleaseObjectLock(ObjectHeader
);
3144 /* Check if we failed and dereference the object if so */
3145 if (!NT_SUCCESS(RealStatus
)) ObDereferenceObject(Object
);
3148 /* We can delete the Create Info now */
3149 ObpFreeObjectCreateInformation(ObjectCreateInfo
);
3151 /* Check if we created our own access state and delete it if so */
3152 if (AccessState
== &LocalAccessState
) SeDeleteAccessState(AccessState
);
3154 /* Return status code */
3155 OBTRACE(OB_HANDLE_DEBUG
,
3156 "%s - returning Object with PC RS/S: %lx %lx %lx\n",
3158 OBJECT_TO_OBJECT_HEADER(Object
)->PointerCount
,
3159 RealStatus
, Status
);
3164 * @name ObCloseHandle
3165 * @implemented NT5.1
3167 * The ObCloseHandle routine <FILLMEIN>
3175 * @return <FILLMEIN>.
3182 ObCloseHandle(IN HANDLE Handle
,
3183 IN KPROCESSOR_MODE AccessMode
)
3185 /* Call the internal API */
3186 return ObpCloseHandle(Handle
, AccessMode
);
3193 * The NtClose routine <FILLMEIN>
3198 * @return <FILLMEIN>.
3205 NtClose(IN HANDLE Handle
)
3207 /* Call the internal API */
3208 return ObpCloseHandle(Handle
, ExGetPreviousMode());
3213 NtDuplicateObject(IN HANDLE SourceProcessHandle
,
3214 IN HANDLE SourceHandle
,
3215 IN HANDLE TargetProcessHandle OPTIONAL
,
3216 OUT PHANDLE TargetHandle OPTIONAL
,
3217 IN ACCESS_MASK DesiredAccess
,
3218 IN ULONG HandleAttributes
,
3221 PEPROCESS SourceProcess
, TargetProcess
, Target
;
3223 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3225 OBTRACE(OB_HANDLE_DEBUG
,
3226 "%s - Duplicating handle: %lx for %lx into %lx.\n",
3229 SourceProcessHandle
,
3230 TargetProcessHandle
);
3232 /* Check if we have a target handle */
3233 if ((TargetHandle
) && (PreviousMode
!= KernelMode
))
3238 /* Probe the handle and assume failure */
3239 ProbeForWriteHandle(TargetHandle
);
3240 *TargetHandle
= NULL
;
3242 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3244 /* Return the exception code */
3245 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3250 /* Now reference the input handle */
3251 Status
= ObReferenceObjectByHandle(SourceProcessHandle
,
3255 (PVOID
*)&SourceProcess
,
3257 if (!NT_SUCCESS(Status
)) return(Status
);
3259 /* Check if got a target handle */
3260 if (TargetProcessHandle
)
3262 /* Now reference the output handle */
3263 Status
= ObReferenceObjectByHandle(TargetProcessHandle
,
3267 (PVOID
*)&TargetProcess
,
3269 if (NT_SUCCESS(Status
))
3271 /* Use this target process */
3272 Target
= TargetProcess
;
3276 /* No target process */
3282 /* No target process */
3283 Status
= STATUS_SUCCESS
;
3287 /* Call the internal routine */
3288 Status
= ObDuplicateObject(SourceProcess
,
3297 /* Check if the caller wanted the return handle */
3300 /* Protect the write to user mode */
3303 /* Write the new handle */
3304 *TargetHandle
= hTarget
;
3306 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3308 /* Otherwise, get the exception code */
3309 Status
= _SEH2_GetExceptionCode();
3314 /* Dereference the processes */
3315 OBTRACE(OB_HANDLE_DEBUG
,
3316 "%s - Duplicated handle: %lx into %lx S %lx\n",
3319 TargetProcessHandle
,
3321 if (Target
) ObDereferenceObject(Target
);
3322 ObDereferenceObject(SourceProcess
);
3326 #undef ObIsKernelHandle
3329 ObIsKernelHandle(IN HANDLE Handle
)
3331 /* We know we're kernel mode, so just check for the kernel handle flag */
3332 return (BOOLEAN
)(((ULONG_PTR
)Handle
& KERNEL_HANDLE_FLAG
) != 0);