2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/io/iomgr/file.c
5 * PURPOSE: Functions that deal with managing the FILE_OBJECT itself.
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
9 * Filip Navara (navaraf@reactos.org)
13 /* INCLUDES *****************************************************************/
19 extern ERESOURCE IopSecurityResource
;
21 /* PRIVATE FUNCTIONS *********************************************************/
25 IopCheckBackupRestorePrivilege(IN PACCESS_STATE AccessState
,
26 IN OUT PULONG CreateOptions
,
27 IN KPROCESSOR_MODE PreviousMode
,
30 ACCESS_MASK DesiredAccess
, ReadAccess
, WriteAccess
;
31 PRIVILEGE_SET Privileges
;
32 BOOLEAN AccessGranted
, HaveBackupPriv
= FALSE
, CheckRestore
= FALSE
;
35 /* Don't do anything if privileges were checked already */
36 if (AccessState
->Flags
& SE_BACKUP_PRIVILEGES_CHECKED
) return;
38 /* Check if the file was actually opened for backup purposes */
39 if (*CreateOptions
& FILE_OPEN_FOR_BACKUP_INTENT
)
41 /* Set the check flag since were doing it now */
42 AccessState
->Flags
|= SE_BACKUP_PRIVILEGES_CHECKED
;
44 /* Set the access masks required */
45 ReadAccess
= READ_CONTROL
|
46 ACCESS_SYSTEM_SECURITY
|
49 WriteAccess
= WRITE_DAC
|
51 ACCESS_SYSTEM_SECURITY
|
54 FILE_ADD_SUBDIRECTORY
|
56 DesiredAccess
= AccessState
->RemainingDesiredAccess
;
58 /* Check if desired access was the maximum */
59 if (DesiredAccess
& MAXIMUM_ALLOWED
)
61 /* Then add all the access masks required */
62 DesiredAccess
|= (ReadAccess
| WriteAccess
);
65 /* Check if the file already exists */
66 if (Disposition
& FILE_OPEN
)
68 /* Check if desired access has the read mask */
69 if (ReadAccess
& DesiredAccess
)
71 /* Setup the privilege check lookup */
72 Privileges
.PrivilegeCount
= 1;
73 Privileges
.Control
= PRIVILEGE_SET_ALL_NECESSARY
;
74 Privileges
.Privilege
[0].Luid
= SeBackupPrivilege
;
75 Privileges
.Privilege
[0].Attributes
= 0;
76 AccessGranted
= SePrivilegeCheck(&Privileges
,
78 SubjectSecurityContext
,
82 /* Remember that backup was allowed */
83 HaveBackupPriv
= TRUE
;
85 /* Append the privileges and update the access state */
86 SeAppendPrivileges(AccessState
, &Privileges
);
87 AccessState
->PreviouslyGrantedAccess
|= (DesiredAccess
& ReadAccess
);
88 AccessState
->RemainingDesiredAccess
&= ~ReadAccess
;
89 DesiredAccess
&= ~ReadAccess
;
91 /* Set backup privilege for the token */
92 AccessState
->Flags
|= TOKEN_HAS_BACKUP_PRIVILEGE
;
98 /* Caller is creating the file, check restore privileges later */
102 /* Check if caller wants write access or if it's creating a file */
103 if ((WriteAccess
& DesiredAccess
) || (CheckRestore
))
105 /* Setup the privilege lookup and do it */
106 Privileges
.PrivilegeCount
= 1;
107 Privileges
.Control
= PRIVILEGE_SET_ALL_NECESSARY
;
108 Privileges
.Privilege
[0].Luid
= SeRestorePrivilege
;
109 Privileges
.Privilege
[0].Attributes
= 0;
110 AccessGranted
= SePrivilegeCheck(&Privileges
,
111 &AccessState
->SubjectSecurityContext
,
115 /* Remember that privilege was given */
116 HaveBackupPriv
= TRUE
;
118 /* Append the privileges and update the access state */
119 SeAppendPrivileges(AccessState
, &Privileges
);
120 AccessState
->PreviouslyGrantedAccess
|= (DesiredAccess
& WriteAccess
);
121 AccessState
->RemainingDesiredAccess
&= ~WriteAccess
;
123 /* Set restore privilege for the token */
124 AccessState
->Flags
|= TOKEN_HAS_RESTORE_PRIVILEGE
;
128 /* If we don't have the privilege, remove the option */
129 if (!HaveBackupPriv
) *CreateOptions
&= ~FILE_OPEN_FOR_BACKUP_INTENT
;
135 IopCheckDeviceAndDriver(IN POPEN_PACKET OpenPacket
,
136 IN PDEVICE_OBJECT DeviceObject
)
138 /* Make sure the object is valid */
139 if ((IoGetDevObjExtension(DeviceObject
)->ExtensionFlags
&
140 (DOE_UNLOAD_PENDING
|
143 DOE_REMOVE_PROCESSED
)) ||
144 (DeviceObject
->Flags
& DO_DEVICE_INITIALIZING
))
146 /* It's unloading or initializing, so fail */
147 DPRINT1("You are seeing this because the following ROS driver: %wZ\n"
148 " sucks. Please fix it's AddDevice Routine\n",
149 &DeviceObject
->DriverObject
->DriverName
);
150 return STATUS_NO_SUCH_DEVICE
;
152 else if ((DeviceObject
->Flags
& DO_EXCLUSIVE
) &&
153 (DeviceObject
->ReferenceCount
) &&
154 !(OpenPacket
->RelatedFileObject
) &&
155 !(OpenPacket
->Options
& IO_ATTACH_DEVICE
))
157 return STATUS_ACCESS_DENIED
;
162 /* Increase reference count */
163 InterlockedIncrement(&DeviceObject
->ReferenceCount
);
164 return STATUS_SUCCESS
;
170 IopDoNameTransmogrify(IN PIRP Irp
,
171 IN PFILE_OBJECT FileObject
,
172 IN PREPARSE_DATA_BUFFER DataBuffer
)
176 USHORT RequiredLength
;
181 ASSERT(Irp
->IoStatus
.Status
== STATUS_REPARSE
);
182 ASSERT(Irp
->IoStatus
.Information
== IO_REPARSE_TAG_MOUNT_POINT
);
183 ASSERT(Irp
->Tail
.Overlay
.AuxiliaryBuffer
!= NULL
);
184 ASSERT(DataBuffer
!= NULL
);
185 ASSERT(DataBuffer
->ReparseTag
== IO_REPARSE_TAG_MOUNT_POINT
);
186 ASSERT(DataBuffer
->ReparseDataLength
< MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
187 ASSERT(DataBuffer
->Reserved
< MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
189 /* First of all, validate data */
190 if (DataBuffer
->ReparseDataLength
< REPARSE_DATA_BUFFER_HEADER_SIZE
||
191 (DataBuffer
->SymbolicLinkReparseBuffer
.PrintNameLength
+
192 DataBuffer
->SymbolicLinkReparseBuffer
.SubstituteNameLength
+
193 FIELD_OFFSET(REPARSE_DATA_BUFFER
, MountPointReparseBuffer
.PathBuffer
[0])) > MAXIMUM_REPARSE_DATA_BUFFER_SIZE
)
195 Irp
->IoStatus
.Status
= STATUS_IO_REPARSE_DATA_INVALID
;
198 /* Everything went right */
199 if (NT_SUCCESS(Irp
->IoStatus
.Status
))
201 /* Compute buffer & length */
202 Buffer
= (PWSTR
)((ULONG_PTR
)DataBuffer
->MountPointReparseBuffer
.PathBuffer
+
203 DataBuffer
->MountPointReparseBuffer
.SubstituteNameOffset
);
204 Length
= DataBuffer
->MountPointReparseBuffer
.SubstituteNameLength
;
206 /* Check we don't overflow */
207 if (((ULONG
)MAXUSHORT
- DataBuffer
->Reserved
) <= (Length
+ sizeof(UNICODE_NULL
)))
209 Irp
->IoStatus
.Status
= STATUS_IO_REPARSE_DATA_INVALID
;
213 /* Compute how much mem we'll need */
214 RequiredLength
= DataBuffer
->Reserved
+ Length
+ sizeof(UNICODE_NULL
);
216 /* Check if FileObject can already hold what we need */
217 if (FileObject
->FileName
.MaximumLength
>= RequiredLength
)
219 NewBuffer
= FileObject
->FileName
.Buffer
;
223 /* Allocate otherwise */
224 NewBuffer
= ExAllocatePoolWithTag(PagedPool
, RequiredLength
, TAG_IO_NAME
);
225 if (NewBuffer
== NULL
)
227 Irp
->IoStatus
.Status
= STATUS_INSUFFICIENT_RESOURCES
;
233 /* Everything went right */
234 if (NT_SUCCESS(Irp
->IoStatus
.Status
))
237 if (DataBuffer
->Reserved
)
239 RtlMoveMemory((PWSTR
)((ULONG_PTR
)NewBuffer
+ Length
),
240 (PWSTR
)((ULONG_PTR
)FileObject
->FileName
.Buffer
+ FileObject
->FileName
.Length
- DataBuffer
->Reserved
),
241 DataBuffer
->Reserved
);
247 RtlCopyMemory(NewBuffer
, Buffer
, Length
);
250 /* And finally replace buffer if new one was allocated */
251 FileObject
->FileName
.Length
= RequiredLength
- sizeof(UNICODE_NULL
);
252 if (NewBuffer
!= FileObject
->FileName
.Buffer
)
254 if (FileObject
->FileName
.Buffer
)
256 ExFreePoolWithTag(FileObject
->FileName
.Buffer
, TAG_IO_NAME
);
259 FileObject
->FileName
.Buffer
= NewBuffer
;
260 FileObject
->FileName
.MaximumLength
= RequiredLength
;
261 FileObject
->FileName
.Buffer
[RequiredLength
/ sizeof(WCHAR
) - 1] = UNICODE_NULL
;
265 /* We don't need them anymore - it was allocated by the driver */
266 ExFreePool(DataBuffer
);
271 IopParseDevice(IN PVOID ParseObject
,
273 IN OUT PACCESS_STATE AccessState
,
274 IN KPROCESSOR_MODE AccessMode
,
276 IN OUT PUNICODE_STRING CompleteName
,
277 IN OUT PUNICODE_STRING RemainingName
,
278 IN OUT PVOID Context
,
279 IN PSECURITY_QUALITY_OF_SERVICE SecurityQos OPTIONAL
,
282 POPEN_PACKET OpenPacket
= (POPEN_PACKET
)Context
;
283 PDEVICE_OBJECT OriginalDeviceObject
= (PDEVICE_OBJECT
)ParseObject
;
284 PDEVICE_OBJECT DeviceObject
, OwnerDevice
;
286 PFILE_OBJECT FileObject
;
289 PIO_STACK_LOCATION StackLoc
;
290 IO_SECURITY_CONTEXT SecurityContext
;
291 IO_STATUS_BLOCK IoStatusBlock
;
292 BOOLEAN DirectOpen
= FALSE
, OpenCancelled
, UseDummyFile
;
293 OBJECT_ATTRIBUTES ObjectAttributes
;
295 PDUMMY_FILE_OBJECT LocalFileObject
;
296 PFILE_BASIC_INFORMATION FileBasicInfo
;
298 KPROCESSOR_MODE CheckMode
;
299 BOOLEAN VolumeOpen
= FALSE
;
300 ACCESS_MASK DesiredAccess
, GrantedAccess
;
301 BOOLEAN AccessGranted
, LockHeld
= FALSE
;
302 PPRIVILEGE_SET Privileges
= NULL
;
303 UNICODE_STRING FileString
;
305 IOTRACE(IO_FILE_DEBUG
, "ParseObject: %p. RemainingName: %wZ\n",
306 ParseObject
, RemainingName
);
308 for (Attempt
= 0; Attempt
< IOP_MAX_REPARSE_TRAVERSAL
; ++Attempt
)
313 /* Validate the open packet */
314 if (!IopValidateOpenPacket(OpenPacket
)) return STATUS_OBJECT_TYPE_MISMATCH
;
316 /* Valide reparse point in case we traversed a mountpoint */
317 if (OpenPacket
->TraversedMountPoint
)
319 /* This is a reparse point we understand */
320 ASSERT(OpenPacket
->Information
== IO_REPARSE_TAG_MOUNT_POINT
);
322 /* Make sure we're dealing with correct DO */
323 if (OriginalDeviceObject
->DeviceType
!= FILE_DEVICE_DISK
&&
324 OriginalDeviceObject
->DeviceType
!= FILE_DEVICE_CD_ROM
&&
325 OriginalDeviceObject
->DeviceType
!= FILE_DEVICE_VIRTUAL_DISK
&&
326 OriginalDeviceObject
->DeviceType
!= FILE_DEVICE_TAPE
)
328 OpenPacket
->FinalStatus
= STATUS_IO_REPARSE_DATA_INVALID
;
329 return STATUS_IO_REPARSE_DATA_INVALID
;
333 /* Check if we have a related file object */
334 if (OpenPacket
->RelatedFileObject
)
336 /* Use the related file object's device object */
337 OriginalDeviceObject
= OpenPacket
->RelatedFileObject
->DeviceObject
;
340 /* Validate device status */
341 Status
= IopCheckDeviceAndDriver(OpenPacket
, OriginalDeviceObject
);
342 if (!NT_SUCCESS(Status
))
344 /* We failed, return status */
345 OpenPacket
->FinalStatus
= Status
;
349 /* Map the generic mask and set the new mapping in the access state */
350 RtlMapGenericMask(&AccessState
->RemainingDesiredAccess
,
351 &IoFileObjectType
->TypeInfo
.GenericMapping
);
352 RtlMapGenericMask(&AccessState
->OriginalDesiredAccess
,
353 &IoFileObjectType
->TypeInfo
.GenericMapping
);
354 SeSetAccessStateGenericMapping(AccessState
,
355 &IoFileObjectType
->TypeInfo
.GenericMapping
);
356 DesiredAccess
= AccessState
->RemainingDesiredAccess
;
358 /* Check what kind of access checks to do */
359 if ((AccessMode
!= KernelMode
) ||
360 (OpenPacket
->Options
& IO_FORCE_ACCESS_CHECK
))
362 /* Call is from user-mode or kernel is forcing checks */
363 CheckMode
= UserMode
;
367 /* Call is from the kernel */
368 CheckMode
= KernelMode
;
371 /* Check privilege for backup or restore operation */
372 IopCheckBackupRestorePrivilege(AccessState
,
373 &OpenPacket
->CreateOptions
,
375 OpenPacket
->Disposition
);
377 /* Check if we are re-parsing */
378 if (((OpenPacket
->Override
) && !(RemainingName
->Length
)) ||
379 (AccessState
->Flags
& SE_BACKUP_PRIVILEGES_CHECKED
))
381 /* Get granted access from the last call */
382 DesiredAccess
|= AccessState
->PreviouslyGrantedAccess
;
385 /* Check if this is a volume open */
386 if ((OpenPacket
->RelatedFileObject
) &&
387 (OpenPacket
->RelatedFileObject
->Flags
& FO_VOLUME_OPEN
) &&
388 !(RemainingName
->Length
))
394 /* Now check if we need access checks */
395 if (((AccessMode
!= KernelMode
) ||
396 (OpenPacket
->Options
& IO_FORCE_ACCESS_CHECK
)) &&
397 (!(OpenPacket
->RelatedFileObject
) || (VolumeOpen
)) &&
398 !(OpenPacket
->Override
))
400 KeEnterCriticalRegion();
401 ExAcquireResourceSharedLite(&IopSecurityResource
, TRUE
);
403 /* Check if a device object is being parsed */
404 if (!RemainingName
->Length
)
406 /* Lock the subject context */
407 SeLockSubjectContext(&AccessState
->SubjectSecurityContext
);
410 /* Do access check */
411 AccessGranted
= SeAccessCheck(OriginalDeviceObject
->
413 &AccessState
->SubjectSecurityContext
,
419 TypeInfo
.GenericMapping
,
425 /* Append and free the privileges */
426 SeAppendPrivileges(AccessState
, Privileges
);
427 SeFreePrivileges(Privileges
);
430 /* Check if we got access */
433 /* Update access state */
434 AccessState
->PreviouslyGrantedAccess
|= GrantedAccess
;
435 AccessState
->RemainingDesiredAccess
&= ~(GrantedAccess
|
437 OpenPacket
->Override
= TRUE
;
440 FileString
.Length
= 8;
441 FileString
.MaximumLength
= 8;
442 FileString
.Buffer
= L
"File";
444 /* Do Audit/Alarm for open operation */
445 SeOpenObjectAuditAlarm(&FileString
,
446 OriginalDeviceObject
,
448 OriginalDeviceObject
->SecurityDescriptor
,
453 &AccessState
->GenerateOnClose
);
457 /* Check if we need to do traverse validation */
458 if (!(AccessState
->Flags
& TOKEN_HAS_TRAVERSE_PRIVILEGE
) ||
459 ((OriginalDeviceObject
->DeviceType
== FILE_DEVICE_DISK
) ||
460 (OriginalDeviceObject
->DeviceType
== FILE_DEVICE_CD_ROM
)))
462 /* Check if this is a restricted token */
463 if (!(AccessState
->Flags
& TOKEN_IS_RESTRICTED
))
465 /* Do the FAST traverse check */
466 AccessGranted
= SeFastTraverseCheck(OriginalDeviceObject
->SecurityDescriptor
,
474 AccessGranted
= FALSE
;
477 /* Check if we failed to get access */
480 /* Lock the subject context */
481 SeLockSubjectContext(&AccessState
->SubjectSecurityContext
);
484 /* Do access check */
485 AccessGranted
= SeAccessCheck(OriginalDeviceObject
->
487 &AccessState
->SubjectSecurityContext
,
493 TypeInfo
.GenericMapping
,
499 /* Append and free the privileges */
500 SeAppendPrivileges(AccessState
, Privileges
);
501 SeFreePrivileges(Privileges
);
505 /* FIXME: Do Audit/Alarm for traverse check */
509 /* Access automatically granted */
510 AccessGranted
= TRUE
;
514 ExReleaseResourceLite(&IopSecurityResource
);
515 KeLeaveCriticalRegion();
517 /* Check if we hold the lock */
521 SeUnlockSubjectContext(&AccessState
->SubjectSecurityContext
);
524 /* Check if access failed */
527 /* Dereference the device and fail */
528 DPRINT1("Traverse access failed!\n");
529 IopDereferenceDeviceObject(OriginalDeviceObject
, FALSE
);
530 return STATUS_ACCESS_DENIED
;
534 /* Check if we can simply use a dummy file */
535 UseDummyFile
= ((OpenPacket
->QueryOnly
) || (OpenPacket
->DeleteOnly
));
538 /* FIXME: Small hack still exists, have to check why...
539 * This is triggered multiple times by usetup and then once per boot.
541 if (ExpInTextModeSetup
&&
543 !(RemainingName
->Length
) &&
544 !(OpenPacket
->RelatedFileObject
) &&
545 ((wcsstr(CompleteName
->Buffer
, L
"Harddisk")) ||
546 (wcsstr(CompleteName
->Buffer
, L
"Floppy"))) &&
549 DPRINT1("Using IopParseDevice() hack. Requested invalid attributes: %lx\n",
550 DesiredAccess
& ~(SYNCHRONIZE
|
551 FILE_READ_ATTRIBUTES
|
553 ACCESS_SYSTEM_SECURITY
|
560 /* Check if this is a direct open */
561 if (!(RemainingName
->Length
) &&
562 !(OpenPacket
->RelatedFileObject
) &&
563 ((DesiredAccess
& ~(SYNCHRONIZE
|
564 FILE_READ_ATTRIBUTES
|
566 ACCESS_SYSTEM_SECURITY
|
571 /* Remember this for later */
575 /* Check if we have a related FO that wasn't a direct open */
576 if ((OpenPacket
->RelatedFileObject
) &&
577 !(OpenPacket
->RelatedFileObject
->Flags
& FO_DIRECT_DEVICE_OPEN
))
579 /* The device object is the one we were given */
580 DeviceObject
= ParseObject
;
582 /* Check if the related FO had a VPB */
583 if (OpenPacket
->RelatedFileObject
->Vpb
)
585 /* Yes, remember it */
586 Vpb
= OpenPacket
->RelatedFileObject
->Vpb
;
589 InterlockedIncrement((PLONG
)&Vpb
->ReferenceCount
);
591 /* Check if we were given a specific top level device to use */
592 if (OpenPacket
->InternalFlags
& IOP_USE_TOP_LEVEL_DEVICE_HINT
)
594 DeviceObject
= Vpb
->DeviceObject
;
600 /* Check if it has a VPB */
601 if ((OriginalDeviceObject
->Vpb
) && !(DirectOpen
))
603 /* Check if the VPB is mounted, and mount it */
604 Vpb
= IopCheckVpbMounted(OpenPacket
,
605 OriginalDeviceObject
,
608 if (!Vpb
) return Status
;
610 /* Get the VPB's device object */
611 DeviceObject
= Vpb
->DeviceObject
;
615 /* The device object is the one we were given */
616 DeviceObject
= OriginalDeviceObject
;
619 /* If we weren't given a specific top level device, look for an attached device */
620 if (!(OpenPacket
->InternalFlags
& IOP_USE_TOP_LEVEL_DEVICE_HINT
) &&
621 DeviceObject
->AttachedDevice
)
623 /* Get the attached device */
624 DeviceObject
= IoGetAttachedDevice(DeviceObject
);
628 if (OpenPacket
->InternalFlags
& IOP_USE_TOP_LEVEL_DEVICE_HINT
)
630 // FIXME: Verify our device object is good to use
631 ASSERT(DirectOpen
== FALSE
);
634 /* If we traversed a mount point, reset the information */
635 if (OpenPacket
->TraversedMountPoint
)
637 OpenPacket
->TraversedMountPoint
= FALSE
;
640 /* Check if this is a secure FSD */
641 if ((DeviceObject
->Characteristics
& FILE_DEVICE_SECURE_OPEN
) &&
642 ((OpenPacket
->RelatedFileObject
) || (RemainingName
->Length
)) &&
648 KeEnterCriticalRegion();
649 ExAcquireResourceSharedLite(&IopSecurityResource
, TRUE
);
651 /* Lock the subject context */
652 SeLockSubjectContext(&AccessState
->SubjectSecurityContext
);
654 /* Do access check */
655 AccessGranted
= SeAccessCheck(OriginalDeviceObject
->SecurityDescriptor
,
656 &AccessState
->SubjectSecurityContext
,
661 &IoFileObjectType
->TypeInfo
.GenericMapping
,
665 if (Privileges
!= NULL
)
667 /* Append and free the privileges */
668 SeAppendPrivileges(AccessState
, Privileges
);
669 SeFreePrivileges(Privileges
);
672 /* Check if we got access */
675 AccessState
->PreviouslyGrantedAccess
|= GrantedAccess
;
676 AccessState
->RemainingDesiredAccess
&= ~(GrantedAccess
| MAXIMUM_ALLOWED
);
679 FileString
.Length
= 8;
680 FileString
.MaximumLength
= 8;
681 FileString
.Buffer
= L
"File";
683 /* Do Audit/Alarm for open operation
684 * NOTA: we audit target device object
686 SeOpenObjectAuditAlarm(&FileString
,
689 OriginalDeviceObject
->SecurityDescriptor
,
694 &AccessState
->GenerateOnClose
);
696 SeUnlockSubjectContext(&AccessState
->SubjectSecurityContext
);
698 ExReleaseResourceLite(&IopSecurityResource
);
699 KeLeaveCriticalRegion();
701 /* Check if access failed */
704 /* Dereference the device and fail */
705 IopDereferenceDeviceObject(OriginalDeviceObject
, FALSE
);
706 if (Vpb
) IopDereferenceVpbAndFree(Vpb
);
707 return STATUS_ACCESS_DENIED
;
711 /* Allocate the IRP */
712 Irp
= IoAllocateIrp(DeviceObject
->StackSize
, TRUE
);
715 /* Dereference the device and VPB, then fail */
716 IopDereferenceDeviceObject(OriginalDeviceObject
, FALSE
);
717 if (Vpb
) IopDereferenceVpbAndFree(Vpb
);
718 return STATUS_INSUFFICIENT_RESOURCES
;
721 /* Now set the IRP data */
722 Irp
->RequestorMode
= AccessMode
;
723 Irp
->Flags
= IRP_CREATE_OPERATION
| IRP_SYNCHRONOUS_API
| IRP_DEFER_IO_COMPLETION
;
724 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
725 Irp
->UserIosb
= &IoStatusBlock
;
726 Irp
->MdlAddress
= NULL
;
727 Irp
->PendingReturned
= FALSE
;
728 Irp
->UserEvent
= NULL
;
730 Irp
->CancelRoutine
= NULL
;
731 Irp
->Tail
.Overlay
.AuxiliaryBuffer
= NULL
;
733 /* Setup the security context */
734 SecurityContext
.SecurityQos
= SecurityQos
;
735 SecurityContext
.AccessState
= AccessState
;
736 SecurityContext
.DesiredAccess
= AccessState
->RemainingDesiredAccess
;
737 SecurityContext
.FullCreateOptions
= OpenPacket
->CreateOptions
;
739 /* Get the I/O Stack location */
740 StackLoc
= IoGetNextIrpStackLocation(Irp
);
741 StackLoc
->Control
= 0;
743 /* Check what kind of file this is */
744 switch (OpenPacket
->CreateFileType
)
747 case CreateFileTypeNone
:
749 /* Set the major function and EA Length */
750 StackLoc
->MajorFunction
= IRP_MJ_CREATE
;
751 StackLoc
->Parameters
.Create
.EaLength
= OpenPacket
->EaLength
;
754 StackLoc
->Flags
= (UCHAR
)OpenPacket
->Options
;
755 StackLoc
->Flags
|= !(Attributes
& OBJ_CASE_INSENSITIVE
) ? SL_CASE_SENSITIVE
: 0;
759 case CreateFileTypeNamedPipe
:
761 /* Set the named pipe MJ and set the parameters */
762 StackLoc
->MajorFunction
= IRP_MJ_CREATE_NAMED_PIPE
;
763 StackLoc
->Parameters
.CreatePipe
.Parameters
= OpenPacket
->ExtraCreateParameters
;
767 case CreateFileTypeMailslot
:
769 /* Set the mailslot MJ and set the parameters */
770 StackLoc
->MajorFunction
= IRP_MJ_CREATE_MAILSLOT
;
771 StackLoc
->Parameters
.CreateMailslot
.Parameters
= OpenPacket
->ExtraCreateParameters
;
775 /* Set the common data */
776 Irp
->Overlay
.AllocationSize
= OpenPacket
->AllocationSize
;
777 Irp
->AssociatedIrp
.SystemBuffer
= OpenPacket
->EaBuffer
;
778 StackLoc
->Parameters
.Create
.Options
= (OpenPacket
->Disposition
<< 24) |
779 (OpenPacket
->CreateOptions
&
781 StackLoc
->Parameters
.Create
.FileAttributes
= OpenPacket
->FileAttributes
;
782 StackLoc
->Parameters
.Create
.ShareAccess
= OpenPacket
->ShareAccess
;
783 StackLoc
->Parameters
.Create
.SecurityContext
= &SecurityContext
;
785 /* Check if we really need to create an object */
788 ULONG ObjectSize
= sizeof(FILE_OBJECT
);
790 /* Tag on space for a file object extension */
791 if (OpenPacket
->InternalFlags
& IOP_CREATE_FILE_OBJECT_EXTENSION
)
792 ObjectSize
+= sizeof(FILE_OBJECT_EXTENSION
);
794 /* Create the actual file object */
795 InitializeObjectAttributes(&ObjectAttributes
,
800 Status
= ObCreateObject(KernelMode
,
808 (PVOID
*)&FileObject
);
809 if (!NT_SUCCESS(Status
))
811 /* Create failed, free the IRP */
814 /* Dereference the device and VPB */
815 IopDereferenceDeviceObject(OriginalDeviceObject
, FALSE
);
816 if (Vpb
) IopDereferenceVpbAndFree(Vpb
);
818 /* We failed, return status */
819 OpenPacket
->FinalStatus
= Status
;
823 /* Clear the file object */
824 RtlZeroMemory(FileObject
, sizeof(FILE_OBJECT
));
826 /* Check if this is Synch I/O */
827 if (OpenPacket
->CreateOptions
&
828 (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
))
830 /* Set the synch flag */
831 FileObject
->Flags
|= FO_SYNCHRONOUS_IO
;
833 /* Check if it's also alertable */
834 if (OpenPacket
->CreateOptions
& FILE_SYNCHRONOUS_IO_ALERT
)
836 /* It is, set the alertable flag */
837 FileObject
->Flags
|= FO_ALERTABLE_IO
;
841 /* Check if this is synch I/O */
842 if (FileObject
->Flags
& FO_SYNCHRONOUS_IO
)
844 /* Initialize the event */
845 KeInitializeEvent(&FileObject
->Lock
, SynchronizationEvent
, FALSE
);
848 /* Check if the caller requested no intermediate buffering */
849 if (OpenPacket
->CreateOptions
& FILE_NO_INTERMEDIATE_BUFFERING
)
851 /* Set the correct flag for the FSD to read */
852 FileObject
->Flags
|= FO_NO_INTERMEDIATE_BUFFERING
;
855 /* Check if the caller requested write through support */
856 if (OpenPacket
->CreateOptions
& FILE_WRITE_THROUGH
)
858 /* Set the correct flag for the FSD to read */
859 FileObject
->Flags
|= FO_WRITE_THROUGH
;
862 /* Check if the caller says the file will be only read sequentially */
863 if (OpenPacket
->CreateOptions
& FILE_SEQUENTIAL_ONLY
)
865 /* Set the correct flag for the FSD to read */
866 FileObject
->Flags
|= FO_SEQUENTIAL_ONLY
;
869 /* Check if the caller believes the file will be only read randomly */
870 if (OpenPacket
->CreateOptions
& FILE_RANDOM_ACCESS
)
872 /* Set the correct flag for the FSD to read */
873 FileObject
->Flags
|= FO_RANDOM_ACCESS
;
876 /* Check if we were asked to setup a file object extension */
877 if (OpenPacket
->InternalFlags
& IOP_CREATE_FILE_OBJECT_EXTENSION
)
879 PFILE_OBJECT_EXTENSION FileObjectExtension
;
881 /* Make sure the file object knows it has an extension */
882 FileObject
->Flags
|= FO_FILE_OBJECT_HAS_EXTENSION
;
884 FileObjectExtension
= (PFILE_OBJECT_EXTENSION
)(FileObject
+ 1);
885 FileObject
->FileObjectExtension
= FileObjectExtension
;
887 /* Add the top level device which we'll send the request to */
888 if (OpenPacket
->InternalFlags
& IOP_USE_TOP_LEVEL_DEVICE_HINT
)
890 FileObjectExtension
->TopDeviceObjectHint
= DeviceObject
;
896 /* Use the dummy object instead */
897 LocalFileObject
= OpenPacket
->LocalFileObject
;
898 RtlZeroMemory(LocalFileObject
, sizeof(DUMMY_FILE_OBJECT
));
901 FileObject
= (PFILE_OBJECT
)&LocalFileObject
->ObjectHeader
.Body
;
902 LocalFileObject
->ObjectHeader
.Type
= IoFileObjectType
;
903 LocalFileObject
->ObjectHeader
.PointerCount
= 1;
906 /* Setup the file header */
907 FileObject
->Type
= IO_TYPE_FILE
;
908 FileObject
->Size
= sizeof(FILE_OBJECT
);
909 FileObject
->RelatedFileObject
= OpenPacket
->RelatedFileObject
;
910 FileObject
->DeviceObject
= OriginalDeviceObject
;
912 /* Check if this is a direct device open */
913 if (DirectOpen
) FileObject
->Flags
|= FO_DIRECT_DEVICE_OPEN
;
915 /* Check if the caller wants case sensitivity */
916 if (!(Attributes
& OBJ_CASE_INSENSITIVE
))
918 /* Tell the driver about it */
919 FileObject
->Flags
|= FO_OPENED_CASE_SENSITIVE
;
922 /* Now set the file object */
923 Irp
->Tail
.Overlay
.OriginalFileObject
= FileObject
;
924 StackLoc
->FileObject
= FileObject
;
926 /* Check if the file object has a name */
927 if (RemainingName
->Length
)
929 /* Setup the unicode string */
930 FileObject
->FileName
.MaximumLength
= RemainingName
->Length
+
932 FileObject
->FileName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
937 if (!FileObject
->FileName
.Buffer
)
939 /* Failed to allocate the name, free the IRP */
942 /* Dereference the device object and VPB */
943 IopDereferenceDeviceObject(OriginalDeviceObject
, FALSE
);
944 if (Vpb
) IopDereferenceVpbAndFree(Vpb
);
946 /* Clear the FO and dereference it */
947 FileObject
->DeviceObject
= NULL
;
948 if (!UseDummyFile
) ObDereferenceObject(FileObject
);
951 return STATUS_INSUFFICIENT_RESOURCES
;
956 RtlCopyUnicodeString(&FileObject
->FileName
, RemainingName
);
958 /* Initialize the File Object event and set the FO */
959 KeInitializeEvent(&FileObject
->Event
, NotificationEvent
, FALSE
);
960 OpenPacket
->FileObject
= FileObject
;
962 /* Queue the IRP and call the driver */
963 IopQueueIrpToThread(Irp
);
964 Status
= IoCallDriver(DeviceObject
, Irp
);
965 if (Status
== STATUS_PENDING
)
967 /* Wait for the driver to complete the create */
968 KeWaitForSingleObject(&FileObject
->Event
,
974 /* Get the new status */
975 Status
= IoStatusBlock
.Status
;
979 /* We'll have to complete it ourselves */
980 ASSERT(!Irp
->PendingReturned
);
981 ASSERT(!Irp
->MdlAddress
);
983 /* Handle name change if required */
984 if (Status
== STATUS_REPARSE
)
986 /* Check this is a mount point */
987 if (Irp
->IoStatus
.Information
== IO_REPARSE_TAG_MOUNT_POINT
)
989 PREPARSE_DATA_BUFFER ReparseData
;
991 /* Reparse point attributes were passed by the driver in the auxiliary buffer */
992 ASSERT(Irp
->Tail
.Overlay
.AuxiliaryBuffer
!= NULL
);
993 ReparseData
= (PREPARSE_DATA_BUFFER
)Irp
->Tail
.Overlay
.AuxiliaryBuffer
;
995 ASSERT(ReparseData
->ReparseTag
== IO_REPARSE_TAG_MOUNT_POINT
);
996 ASSERT(ReparseData
->ReparseDataLength
< MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
997 ASSERT(ReparseData
->Reserved
< MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
999 IopDoNameTransmogrify(Irp
, FileObject
, ReparseData
);
1003 /* Completion happens at APC_LEVEL */
1004 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
1006 /* Get the new I/O Status block ourselves */
1007 IoStatusBlock
= Irp
->IoStatus
;
1008 Status
= IoStatusBlock
.Status
;
1010 /* Manually signal the even, we can't have any waiters */
1011 FileObject
->Event
.Header
.SignalState
= 1;
1013 /* Now that we've signaled the events, de-associate the IRP */
1014 IopUnQueueIrpFromThread(Irp
);
1016 /* Check if the IRP had an input buffer */
1017 if ((Irp
->Flags
& IRP_BUFFERED_IO
) &&
1018 (Irp
->Flags
& IRP_DEALLOCATE_BUFFER
))
1020 /* Free it. A driver might've tacked one on */
1021 ExFreePool(Irp
->AssociatedIrp
.SystemBuffer
);
1024 /* Free the IRP and bring the IRQL back down */
1026 KeLowerIrql(OldIrql
);
1029 /* Copy the I/O Status */
1030 OpenPacket
->Information
= IoStatusBlock
.Information
;
1032 /* The driver failed to create the file */
1033 if (!NT_SUCCESS(Status
))
1035 /* Check if we have a name */
1036 if (FileObject
->FileName
.Length
)
1039 ExFreePoolWithTag(FileObject
->FileName
.Buffer
, TAG_IO_NAME
);
1040 FileObject
->FileName
.Length
= 0;
1043 /* Clear its device object */
1044 FileObject
->DeviceObject
= NULL
;
1046 /* Save this now because the FO might go away */
1047 OpenCancelled
= FileObject
->Flags
& FO_FILE_OPEN_CANCELLED
?
1050 /* Clear the file object in the open packet */
1051 OpenPacket
->FileObject
= NULL
;
1053 /* Dereference the file object */
1054 if (!UseDummyFile
) ObDereferenceObject(FileObject
);
1056 /* Dereference the device object */
1057 IopDereferenceDeviceObject(OriginalDeviceObject
, FALSE
);
1059 /* Unless the driver cancelled the open, dereference the VPB */
1060 if (!(OpenCancelled
) && (Vpb
)) IopDereferenceVpbAndFree(Vpb
);
1062 /* Set the status and return */
1063 OpenPacket
->FinalStatus
= Status
;
1066 else if (Status
== STATUS_REPARSE
)
1068 if (OpenPacket
->Information
== IO_REPARSE
||
1069 OpenPacket
->Information
== IO_REPARSE_TAG_MOUNT_POINT
)
1071 /* Update CompleteName with reparse info which got updated in IopDoNameTransmogrify() */
1072 if (CompleteName
->MaximumLength
< FileObject
->FileName
.Length
)
1074 PWSTR NewCompleteName
;
1076 /* Allocate a new buffer for the string */
1077 NewCompleteName
= ExAllocatePoolWithTag(PagedPool
, FileObject
->FileName
.Length
, TAG_IO_NAME
);
1078 if (NewCompleteName
== NULL
)
1080 OpenPacket
->FinalStatus
= STATUS_INSUFFICIENT_RESOURCES
;
1081 return STATUS_INSUFFICIENT_RESOURCES
;
1084 /* Release the old one */
1085 if (CompleteName
->Buffer
!= NULL
)
1087 ExFreePoolWithTag(CompleteName
->Buffer
, 0);
1090 /* And setup the new one */
1091 CompleteName
->Buffer
= NewCompleteName
;
1092 CompleteName
->MaximumLength
= FileObject
->FileName
.Length
;
1095 /* Copy our new complete name */
1096 RtlCopyUnicodeString(CompleteName
, &FileObject
->FileName
);
1098 if (OpenPacket
->Information
== IO_REPARSE_TAG_MOUNT_POINT
)
1100 OpenPacket
->RelatedFileObject
= NULL
;
1104 /* Check if we have a name */
1105 if (FileObject
->FileName
.Length
)
1108 ExFreePoolWithTag(FileObject
->FileName
.Buffer
, 0);
1109 FileObject
->FileName
.Length
= 0;
1112 /* Clear its device object */
1113 FileObject
->DeviceObject
= NULL
;
1115 /* Clear the file object in the open packet */
1116 OpenPacket
->FileObject
= NULL
;
1118 /* Dereference the file object */
1119 if (!UseDummyFile
) ObDereferenceObject(FileObject
);
1121 /* Dereference the device object */
1122 IopDereferenceDeviceObject(OriginalDeviceObject
, FALSE
);
1124 /* Unless the driver cancelled the open, dereference the VPB */
1125 if (Vpb
!= NULL
) IopDereferenceVpbAndFree(Vpb
);
1127 if (OpenPacket
->Information
!= IO_REMOUNT
)
1129 OpenPacket
->RelatedFileObject
= NULL
;
1131 /* Inform we traversed a mount point for later attempt */
1132 if (OpenPacket
->Information
== IO_REPARSE_TAG_MOUNT_POINT
)
1134 OpenPacket
->TraversedMountPoint
= 1;
1137 /* In case we override checks, but got this on volume open, fail hard */
1138 if (OpenPacket
->Override
)
1140 KeBugCheckEx(DRIVER_RETURNED_STATUS_REPARSE_FOR_VOLUME_OPEN
,
1141 (ULONG_PTR
)OriginalDeviceObject
,
1142 (ULONG_PTR
)DeviceObject
,
1143 (ULONG_PTR
)CompleteName
,
1144 OpenPacket
->Information
);
1147 /* Return to IO/OB so that information can be upgraded */
1148 return STATUS_REPARSE
;
1151 /* Loop again and reattempt an opening */
1158 if (Attempt
== IOP_MAX_REPARSE_TRAVERSAL
)
1159 return STATUS_UNSUCCESSFUL
;
1161 /* Get the owner of the File Object */
1162 OwnerDevice
= IoGetRelatedDeviceObject(FileObject
);
1165 * It's possible that the device to whom we sent the IRP to
1166 * isn't actually the device that ended opening the file object
1169 if (OwnerDevice
!= DeviceObject
)
1171 /* We have to de-reference the VPB we had associated */
1172 if (Vpb
) IopDereferenceVpbAndFree(Vpb
);
1174 /* And re-associate with the actual one */
1175 Vpb
= FileObject
->Vpb
;
1176 if (Vpb
) InterlockedIncrement((PLONG
)&Vpb
->ReferenceCount
);
1179 /* Make sure we are not using a dummy */
1182 /* Check if this was a volume open */
1183 if ((!(FileObject
->RelatedFileObject
) ||
1184 (FileObject
->RelatedFileObject
->Flags
& FO_VOLUME_OPEN
)) &&
1185 !(FileObject
->FileName
.Length
))
1187 /* All signs point to it, but make sure it was actually an FSD */
1188 if ((OwnerDevice
->DeviceType
== FILE_DEVICE_DISK_FILE_SYSTEM
) ||
1189 (OwnerDevice
->DeviceType
== FILE_DEVICE_CD_ROM_FILE_SYSTEM
) ||
1190 (OwnerDevice
->DeviceType
== FILE_DEVICE_TAPE_FILE_SYSTEM
) ||
1191 (OwnerDevice
->DeviceType
== FILE_DEVICE_FILE_SYSTEM
))
1193 /* The owner device is an FSD, so this is a volume open for real */
1194 FileObject
->Flags
|= FO_VOLUME_OPEN
;
1198 /* Reference the object and set the parse check */
1199 ObReferenceObject(FileObject
);
1200 *Object
= FileObject
;
1201 OpenPacket
->FinalStatus
= IoStatusBlock
.Status
;
1202 OpenPacket
->ParseCheck
= TRUE
;
1203 return OpenPacket
->FinalStatus
;
1207 /* Check if this was a query */
1208 if (OpenPacket
->QueryOnly
)
1210 /* Check if the caller wants basic info only */
1211 if (!OpenPacket
->FullAttributes
)
1213 /* Allocate the buffer */
1214 FileBasicInfo
= ExAllocatePoolWithTag(NonPagedPool
,
1215 sizeof(*FileBasicInfo
),
1220 Status
= IoQueryFileInformation(FileObject
,
1221 FileBasicInformation
,
1222 sizeof(*FileBasicInfo
),
1225 if (NT_SUCCESS(Status
))
1228 RtlCopyMemory(OpenPacket
->BasicInformation
,
1233 /* Free our buffer */
1234 ExFreePoolWithTag(FileBasicInfo
, TAG_IO
);
1239 Status
= STATUS_INSUFFICIENT_RESOURCES
;
1244 /* This is a full query */
1245 Status
= IoQueryFileInformation(
1247 FileNetworkOpenInformation
,
1248 sizeof(FILE_NETWORK_OPEN_INFORMATION
),
1249 OpenPacket
->NetworkInformation
,
1251 if (!NT_SUCCESS(Status
)) ASSERT(Status
!= STATUS_NOT_IMPLEMENTED
);
1255 /* Delete the file object */
1256 IopDeleteFile(FileObject
);
1258 /* Clear out the file */
1259 OpenPacket
->FileObject
= NULL
;
1261 /* Set and return status */
1262 OpenPacket
->FinalStatus
= Status
;
1263 OpenPacket
->ParseCheck
= TRUE
;
1270 IopParseFile(IN PVOID ParseObject
,
1271 IN PVOID ObjectType
,
1272 IN OUT PACCESS_STATE AccessState
,
1273 IN KPROCESSOR_MODE AccessMode
,
1274 IN ULONG Attributes
,
1275 IN OUT PUNICODE_STRING CompleteName
,
1276 IN OUT PUNICODE_STRING RemainingName
,
1277 IN OUT PVOID Context OPTIONAL
,
1278 IN PSECURITY_QUALITY_OF_SERVICE SecurityQos OPTIONAL
,
1282 POPEN_PACKET OpenPacket
= (POPEN_PACKET
)Context
;
1284 /* Validate the open packet */
1285 if (!IopValidateOpenPacket(OpenPacket
)) return STATUS_OBJECT_TYPE_MISMATCH
;
1287 /* Get the device object */
1288 DeviceObject
= IoGetRelatedDeviceObject(ParseObject
);
1289 OpenPacket
->RelatedFileObject
= ParseObject
;
1291 /* Call the main routine */
1292 return IopParseDevice(DeviceObject
,
1306 IopDeleteFile(IN PVOID ObjectBody
)
1308 PFILE_OBJECT FileObject
= (PFILE_OBJECT
)ObjectBody
;
1310 PIO_STACK_LOCATION StackPtr
;
1313 PDEVICE_OBJECT DeviceObject
;
1314 BOOLEAN DereferenceDone
= FALSE
;
1317 IOTRACE(IO_FILE_DEBUG
, "ObjectBody: %p\n", ObjectBody
);
1319 /* Check if the file has a device object */
1320 if (FileObject
->DeviceObject
)
1322 /* Check if this is a direct open or not */
1323 if (FileObject
->Flags
& FO_DIRECT_DEVICE_OPEN
)
1325 /* Get the attached device */
1326 DeviceObject
= IoGetAttachedDevice(FileObject
->DeviceObject
);
1330 /* Use the file object's device object */
1331 DeviceObject
= IoGetRelatedDeviceObject(FileObject
);
1335 ASSERT(!(FileObject
->Flags
& FO_SYNCHRONOUS_IO
) ||
1336 (InterlockedExchange((PLONG
)&FileObject
->Busy
, TRUE
) == FALSE
));
1338 /* Check if the handle wasn't created yet */
1339 if (!(FileObject
->Flags
& FO_HANDLE_CREATED
))
1341 /* Send the cleanup IRP */
1342 IopCloseFile(NULL
, ObjectBody
, 0, 1, 1);
1345 /* Clear and set up Events */
1346 KeClearEvent(&FileObject
->Event
);
1347 KeInitializeEvent(&Event
, SynchronizationEvent
, FALSE
);
1349 /* Allocate an IRP */
1350 Irp
= IopAllocateIrpMustSucceed(DeviceObject
->StackSize
);
1353 Irp
->UserEvent
= &Event
;
1354 Irp
->UserIosb
= &Irp
->IoStatus
;
1355 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
1356 Irp
->Tail
.Overlay
.OriginalFileObject
= FileObject
;
1357 Irp
->Flags
= IRP_CLOSE_OPERATION
| IRP_SYNCHRONOUS_API
;
1359 /* Set up Stack Pointer Data */
1360 StackPtr
= IoGetNextIrpStackLocation(Irp
);
1361 StackPtr
->MajorFunction
= IRP_MJ_CLOSE
;
1362 StackPtr
->FileObject
= FileObject
;
1365 IopQueueIrpToThread(Irp
);
1367 /* Get the VPB and check if this isn't a direct open */
1368 Vpb
= FileObject
->Vpb
;
1369 if ((Vpb
) && !(FileObject
->Flags
& FO_DIRECT_DEVICE_OPEN
))
1371 /* Dereference the VPB before the close */
1372 InterlockedDecrement((PLONG
)&Vpb
->ReferenceCount
);
1375 /* Check if the FS will never disappear by itself */
1376 if (FileObject
->DeviceObject
->Flags
& DO_NEVER_LAST_DEVICE
)
1378 /* Dereference it */
1379 InterlockedDecrement(&FileObject
->DeviceObject
->ReferenceCount
);
1380 DereferenceDone
= TRUE
;
1383 /* Call the FS Driver */
1384 Status
= IoCallDriver(DeviceObject
, Irp
);
1385 if (Status
== STATUS_PENDING
)
1387 /* Wait for completion */
1388 KeWaitForSingleObject(&Event
, Executive
, KernelMode
, FALSE
, NULL
);
1391 /* De-queue the IRP */
1392 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
1393 IopUnQueueIrpFromThread(Irp
);
1394 KeLowerIrql(OldIrql
);
1399 /* Clear the file name */
1400 if (FileObject
->FileName
.Buffer
)
1402 ExFreePoolWithTag(FileObject
->FileName
.Buffer
, TAG_IO_NAME
);
1403 FileObject
->FileName
.Buffer
= NULL
;
1406 /* Check if the FO had a completion port */
1407 if (FileObject
->CompletionContext
)
1410 ObDereferenceObject(FileObject
->CompletionContext
->Port
);
1411 ExFreePool(FileObject
->CompletionContext
);
1414 /* Check if the FO had extension */
1415 if (FileObject
->Flags
& FO_FILE_OBJECT_HAS_EXTENSION
)
1417 /* Release filter context structure if any */
1418 FsRtlPTeardownPerFileObjectContexts(FileObject
);
1421 /* Check if dereference has been done yet */
1422 if (!DereferenceDone
)
1424 /* Dereference device object */
1425 IopDereferenceDeviceObject(FileObject
->DeviceObject
, FALSE
);
1432 IopGetDeviceAttachmentBase(IN PDEVICE_OBJECT DeviceObject
)
1434 PDEVICE_OBJECT PDO
= DeviceObject
;
1436 /* Go down the stack to attempt to get the PDO */
1437 for (; ((PEXTENDED_DEVOBJ_EXTENSION
)PDO
->DeviceObjectExtension
)->AttachedTo
!= NULL
;
1438 PDO
= ((PEXTENDED_DEVOBJ_EXTENSION
)PDO
->DeviceObjectExtension
)->AttachedTo
);
1445 IopGetDevicePDO(IN PDEVICE_OBJECT DeviceObject
)
1450 ASSERT(DeviceObject
!= NULL
);
1452 OldIrql
= KeAcquireQueuedSpinLock(LockQueueIoDatabaseLock
);
1453 /* Get the base DO */
1454 PDO
= IopGetDeviceAttachmentBase(DeviceObject
);
1455 /* Check whether that's really a PDO and if so, keep it */
1456 if ((PDO
->Flags
& DO_BUS_ENUMERATED_DEVICE
) != DO_BUS_ENUMERATED_DEVICE
)
1462 ObReferenceObject(PDO
);
1464 KeReleaseQueuedSpinLock(LockQueueIoDatabaseLock
, OldIrql
);
1471 IopSetDeviceSecurityDescriptor(IN PDEVICE_OBJECT DeviceObject
,
1472 IN PSECURITY_INFORMATION SecurityInformation
,
1473 IN PSECURITY_DESCRIPTOR SecurityDescriptor
,
1474 IN POOL_TYPE PoolType
,
1475 IN PGENERIC_MAPPING GenericMapping
)
1478 PSECURITY_DESCRIPTOR OldSecurityDescriptor
, CachedSecurityDescriptor
, NewSecurityDescriptor
;
1482 /* Keep attempting till we find our old SD or fail */
1485 KeEnterCriticalRegion();
1486 ExAcquireResourceSharedLite(&IopSecurityResource
, TRUE
);
1488 /* Get our old SD and reference it */
1489 OldSecurityDescriptor
= DeviceObject
->SecurityDescriptor
;
1490 if (OldSecurityDescriptor
!= NULL
)
1492 ObReferenceSecurityDescriptor(OldSecurityDescriptor
, 1);
1495 ExReleaseResourceLite(&IopSecurityResource
);
1496 KeLeaveCriticalRegion();
1498 /* Set the SD information */
1499 NewSecurityDescriptor
= OldSecurityDescriptor
;
1500 Status
= SeSetSecurityDescriptorInfo(NULL
, SecurityInformation
,
1501 SecurityDescriptor
, &NewSecurityDescriptor
,
1502 PoolType
, GenericMapping
);
1504 if (!NT_SUCCESS(Status
))
1506 if (OldSecurityDescriptor
!= NULL
)
1508 ObDereferenceSecurityDescriptor(OldSecurityDescriptor
, 1);
1514 /* Add the new DS to the internal cache */
1515 Status
= ObLogSecurityDescriptor(NewSecurityDescriptor
,
1516 &CachedSecurityDescriptor
, 1);
1517 ExFreePool(NewSecurityDescriptor
);
1518 if (!NT_SUCCESS(Status
))
1520 ObDereferenceSecurityDescriptor(OldSecurityDescriptor
, 1);
1524 KeEnterCriticalRegion();
1525 ExAcquireResourceExclusiveLite(&IopSecurityResource
, TRUE
);
1526 /* Check if someone changed it in our back */
1527 if (DeviceObject
->SecurityDescriptor
== OldSecurityDescriptor
)
1529 /* We're clear, do the swap */
1530 DeviceObject
->SecurityDescriptor
= CachedSecurityDescriptor
;
1531 ExReleaseResourceLite(&IopSecurityResource
);
1532 KeLeaveCriticalRegion();
1534 /* And dereference old SD (twice - us + not in use) */
1535 ObDereferenceSecurityDescriptor(OldSecurityDescriptor
, 2);
1539 ExReleaseResourceLite(&IopSecurityResource
);
1540 KeLeaveCriticalRegion();
1542 /* If so, try again */
1543 ObDereferenceSecurityDescriptor(OldSecurityDescriptor
, 1);
1544 ObDereferenceSecurityDescriptor(CachedSecurityDescriptor
, 1);
1552 IopSetDeviceSecurityDescriptors(IN PDEVICE_OBJECT UpperDeviceObject
,
1553 IN PDEVICE_OBJECT PhysicalDeviceObject
,
1554 IN PSECURITY_INFORMATION SecurityInformation
,
1555 IN PSECURITY_DESCRIPTOR SecurityDescriptor
,
1556 IN POOL_TYPE PoolType
,
1557 IN PGENERIC_MAPPING GenericMapping
)
1559 PDEVICE_OBJECT CurrentDO
= PhysicalDeviceObject
, NextDevice
;
1560 NTSTATUS Status
= STATUS_SUCCESS
, TmpStatus
;
1564 ASSERT(PhysicalDeviceObject
!= NULL
);
1566 /* We always reference the DO we're working on */
1567 ObReferenceObject(CurrentDO
);
1569 /* Go up from PDO to latest DO */
1572 /* Attempt to set the new SD on it */
1573 TmpStatus
= IopSetDeviceSecurityDescriptor(CurrentDO
, SecurityInformation
,
1574 SecurityDescriptor
, PoolType
,
1576 /* Was our last one? Remember that status then */
1577 if (CurrentDO
== UpperDeviceObject
)
1582 /* Try to move to the next DO (and thus, reference it) */
1583 NextDevice
= CurrentDO
->AttachedDevice
;
1586 ObReferenceObject(NextDevice
);
1589 /* Dereference current DO and move to the next one */
1590 ObDereferenceObject(CurrentDO
);
1591 CurrentDO
= NextDevice
;
1593 while (CurrentDO
!= NULL
);
1600 IopGetSetSecurityObject(IN PVOID ObjectBody
,
1601 IN SECURITY_OPERATION_CODE OperationCode
,
1602 IN PSECURITY_INFORMATION SecurityInformation
,
1603 IN PSECURITY_DESCRIPTOR SecurityDescriptor
,
1604 IN OUT PULONG BufferLength
,
1605 IN OUT PSECURITY_DESCRIPTOR
*OldSecurityDescriptor
,
1606 IN POOL_TYPE PoolType
,
1607 IN OUT PGENERIC_MAPPING GenericMapping
)
1609 IO_STATUS_BLOCK IoStatusBlock
;
1610 PIO_STACK_LOCATION StackPtr
;
1611 PFILE_OBJECT FileObject
;
1612 PDEVICE_OBJECT DeviceObject
;
1614 BOOLEAN LocalEvent
= FALSE
;
1616 NTSTATUS Status
= STATUS_SUCCESS
;
1618 IOTRACE(IO_FILE_DEBUG
, "ObjectBody: %p\n", ObjectBody
);
1620 /* Check if this is a device or file */
1621 if (((PFILE_OBJECT
)ObjectBody
)->Type
== IO_TYPE_DEVICE
)
1624 DeviceObject
= (PDEVICE_OBJECT
)ObjectBody
;
1630 FileObject
= (PFILE_OBJECT
)ObjectBody
;
1632 /* Check if this is a direct open */
1633 if (FileObject
->Flags
& FO_DIRECT_DEVICE_OPEN
)
1635 /* Get the Device Object */
1636 DeviceObject
= IoGetAttachedDevice(FileObject
->DeviceObject
);
1640 /* Otherwise, use the direct device*/
1641 DeviceObject
= FileObject
->DeviceObject
;
1645 /* Check if the request was for a device object */
1646 if (!(FileObject
) ||
1647 (!(FileObject
->FileName
.Length
) && !(FileObject
->RelatedFileObject
)) ||
1648 (FileObject
->Flags
& FO_DIRECT_DEVICE_OPEN
))
1650 /* Check what kind of request this was */
1651 if (OperationCode
== QuerySecurityDescriptor
)
1653 return SeQuerySecurityDescriptorInfo(SecurityInformation
,
1656 &DeviceObject
->SecurityDescriptor
);
1658 else if (OperationCode
== DeleteSecurityDescriptor
)
1660 /* Simply return success */
1661 return STATUS_SUCCESS
;
1663 else if (OperationCode
== AssignSecurityDescriptor
)
1665 Status
= STATUS_SUCCESS
;
1667 /* Make absolutely sure this is a device object */
1668 if (!(FileObject
) || !(FileObject
->Flags
& FO_STREAM_FILE
))
1670 PSECURITY_DESCRIPTOR CachedSecurityDescriptor
;
1672 /* Add the security descriptor in cache */
1673 Status
= ObLogSecurityDescriptor(SecurityDescriptor
, &CachedSecurityDescriptor
, 1);
1674 if (NT_SUCCESS(Status
))
1676 KeEnterCriticalRegion();
1677 ExAcquireResourceExclusiveLite(&IopSecurityResource
, TRUE
);
1679 /* Assign the Security Descriptor */
1680 DeviceObject
->SecurityDescriptor
= CachedSecurityDescriptor
;
1682 ExReleaseResourceLite(&IopSecurityResource
);
1683 KeLeaveCriticalRegion();
1690 else if (OperationCode
== SetSecurityDescriptor
)
1692 /* Get the Physical Device Object if any */
1693 PDEVICE_OBJECT PDO
= IopGetDevicePDO(DeviceObject
);
1697 /* Apply the new SD to any DO in the path from PDO to current DO */
1698 Status
= IopSetDeviceSecurityDescriptors(DeviceObject
, PDO
,
1699 SecurityInformation
,
1701 PoolType
, GenericMapping
);
1702 ObDereferenceObject(PDO
);
1706 /* Otherwise, just set for ourselves */
1707 Status
= IopSetDeviceSecurityDescriptor(DeviceObject
,
1708 SecurityInformation
,
1710 PoolType
, GenericMapping
);
1713 return STATUS_SUCCESS
;
1716 /* Shouldn't happen */
1717 return STATUS_SUCCESS
;
1719 else if (OperationCode
== DeleteSecurityDescriptor
)
1721 /* Same as for devices, do nothing */
1722 return STATUS_SUCCESS
;
1725 /* At this point, we know we're a file. Reference it */
1726 ObReferenceObject(FileObject
);
1728 /* Check if we should use Sync IO or not */
1729 if (FileObject
->Flags
& FO_SYNCHRONOUS_IO
)
1731 /* Lock the file object */
1732 Status
= IopLockFileObject(FileObject
, ExGetPreviousMode());
1733 if (Status
!= STATUS_SUCCESS
)
1735 ObDereferenceObject(FileObject
);
1741 /* Use local event */
1742 KeInitializeEvent(&Event
, SynchronizationEvent
, FALSE
);
1746 /* Clear the File Object event */
1747 KeClearEvent(&FileObject
->Event
);
1749 /* Get the device object */
1750 DeviceObject
= IoGetRelatedDeviceObject(FileObject
);
1752 /* Allocate the IRP */
1753 Irp
= IoAllocateIrp(DeviceObject
->StackSize
, FALSE
);
1754 if (!Irp
) return IopCleanupFailedIrp(FileObject
, NULL
, NULL
);
1757 Irp
->Tail
.Overlay
.OriginalFileObject
= FileObject
;
1758 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
1759 Irp
->RequestorMode
= ExGetPreviousMode();
1760 Irp
->UserIosb
= &IoStatusBlock
;
1761 Irp
->UserEvent
= (LocalEvent
) ? &Event
: NULL
;
1762 Irp
->Flags
= (LocalEvent
) ? IRP_SYNCHRONOUS_API
: 0;
1763 Irp
->Overlay
.AsynchronousParameters
.UserApcRoutine
= NULL
;
1765 /* Set Stack Parameters */
1766 StackPtr
= IoGetNextIrpStackLocation(Irp
);
1767 StackPtr
->FileObject
= FileObject
;
1769 /* Check if this is a query or set */
1770 if (OperationCode
== QuerySecurityDescriptor
)
1772 /* Set the major function and parameters */
1773 StackPtr
->MajorFunction
= IRP_MJ_QUERY_SECURITY
;
1774 StackPtr
->Parameters
.QuerySecurity
.SecurityInformation
=
1775 *SecurityInformation
;
1776 StackPtr
->Parameters
.QuerySecurity
.Length
= *BufferLength
;
1777 Irp
->UserBuffer
= SecurityDescriptor
;
1781 /* Set the major function and parameters for a set */
1782 StackPtr
->MajorFunction
= IRP_MJ_SET_SECURITY
;
1783 StackPtr
->Parameters
.SetSecurity
.SecurityInformation
=
1784 *SecurityInformation
;
1785 StackPtr
->Parameters
.SetSecurity
.SecurityDescriptor
=
1790 IopQueueIrpToThread(Irp
);
1792 /* Update operation counts */
1793 IopUpdateOperationCount(IopOtherTransfer
);
1795 /* Call the Driver */
1796 Status
= IoCallDriver(DeviceObject
, Irp
);
1798 /* Check if this was async I/O */
1801 /* Check if the IRP is pending completion */
1802 if (Status
== STATUS_PENDING
)
1804 /* Wait on the local event */
1805 KeWaitForSingleObject(&Event
,
1810 Status
= IoStatusBlock
.Status
;
1815 /* Check if the IRP is pending completion */
1816 if (Status
== STATUS_PENDING
)
1818 /* Wait on the file object */
1819 KeWaitForSingleObject(&FileObject
->Event
,
1824 Status
= FileObject
->FinalStatus
;
1827 /* Release the lock */
1828 IopUnlockFileObject(FileObject
);
1831 /* This Driver doesn't implement Security, so try to give it a default */
1832 if (Status
== STATUS_INVALID_DEVICE_REQUEST
)
1834 /* Was this a query? */
1835 if (OperationCode
== QuerySecurityDescriptor
)
1837 /* Set a World Security Descriptor */
1838 Status
= SeSetWorldSecurityDescriptor(*SecurityInformation
,
1844 /* It wasn't a query, so just fake success */
1845 Status
= STATUS_SUCCESS
;
1848 else if (OperationCode
== QuerySecurityDescriptor
)
1850 /* Callers usually expect the normalized form */
1851 if (Status
== STATUS_BUFFER_OVERFLOW
) Status
= STATUS_BUFFER_TOO_SMALL
;
1856 *BufferLength
= (ULONG
)IoStatusBlock
.Information
;
1858 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1860 /* Get the exception code */
1861 Status
= _SEH2_GetExceptionCode();
1872 IopQueryNameInternal(IN PVOID ObjectBody
,
1874 OUT POBJECT_NAME_INFORMATION ObjectNameInfo
,
1876 OUT PULONG ReturnLength
,
1877 IN KPROCESSOR_MODE PreviousMode
)
1879 POBJECT_NAME_INFORMATION LocalInfo
;
1880 PFILE_NAME_INFORMATION LocalFileInfo
;
1881 PFILE_OBJECT FileObject
= (PFILE_OBJECT
)ObjectBody
;
1882 ULONG LocalReturnLength
, FileLength
;
1883 BOOLEAN LengthMismatch
= FALSE
;
1886 IOTRACE(IO_FILE_DEBUG
, "ObjectBody: %p\n", ObjectBody
);
1888 /* Validate length */
1889 if (Length
< sizeof(OBJECT_NAME_INFORMATION
))
1891 /* Wrong length, fail */
1892 *ReturnLength
= sizeof(OBJECT_NAME_INFORMATION
);
1893 return STATUS_INFO_LENGTH_MISMATCH
;
1896 /* Allocate Buffer */
1897 LocalInfo
= ExAllocatePoolWithTag(PagedPool
, Length
, TAG_IO
);
1898 if (!LocalInfo
) return STATUS_INSUFFICIENT_RESOURCES
;
1900 /* Query the name */
1901 Status
= ObQueryNameString(FileObject
->DeviceObject
,
1904 &LocalReturnLength
);
1905 if (!NT_SUCCESS(Status
) && (Status
!= STATUS_INFO_LENGTH_MISMATCH
))
1907 /* Free the buffer and fail */
1908 ExFreePoolWithTag(LocalInfo
, TAG_IO
);
1912 /* Copy the information */
1913 RtlCopyMemory(ObjectNameInfo
,
1915 (LocalReturnLength
> Length
) ?
1916 Length
: LocalReturnLength
);
1918 /* Set buffer pointer */
1919 p
= (PWCHAR
)(ObjectNameInfo
+ 1);
1920 ObjectNameInfo
->Name
.Buffer
= p
;
1922 /* Advance in buffer */
1923 p
+= (LocalInfo
->Name
.Length
/ sizeof(WCHAR
));
1925 /* Check if this already filled our buffer */
1926 if (LocalReturnLength
> Length
)
1928 /* Set the length mismatch to true, so that we can return
1929 * the proper buffer size to the caller later
1931 LengthMismatch
= TRUE
;
1933 /* Save the initial buffer length value */
1934 *ReturnLength
= LocalReturnLength
;
1937 /* Now get the file name buffer and check the length needed */
1938 LocalFileInfo
= (PFILE_NAME_INFORMATION
)LocalInfo
;
1939 FileLength
= Length
-
1941 FIELD_OFFSET(FILE_NAME_INFORMATION
, FileName
);
1943 /* Query the File name */
1944 Status
= IoQueryFileInformation(FileObject
,
1945 FileNameInformation
,
1946 LengthMismatch
? Length
: FileLength
,
1948 &LocalReturnLength
);
1949 if (NT_ERROR(Status
))
1951 /* Fail on errors only, allow warnings */
1952 ExFreePoolWithTag(LocalInfo
, TAG_IO
);
1956 /* If the provided buffer is too small, return the required size */
1959 /* Add the required length */
1960 *ReturnLength
+= LocalFileInfo
->FileNameLength
;
1962 /* Free the allocated buffer and return failure */
1963 ExFreePoolWithTag(LocalInfo
, TAG_IO
);
1964 return STATUS_BUFFER_OVERFLOW
;
1967 /* Now calculate the new lengths left */
1968 FileLength
= LocalReturnLength
-
1969 FIELD_OFFSET(FILE_NAME_INFORMATION
, FileName
);
1970 LocalReturnLength
= (ULONG
)((ULONG_PTR
)p
-
1971 (ULONG_PTR
)ObjectNameInfo
+
1972 LocalFileInfo
->FileNameLength
);
1974 /* Write the Name and null-terminate it */
1975 RtlCopyMemory(p
, LocalFileInfo
->FileName
, FileLength
);
1976 p
+= (FileLength
/ sizeof(WCHAR
));
1978 LocalReturnLength
+= sizeof(UNICODE_NULL
);
1980 /* Return the length needed */
1981 *ReturnLength
= LocalReturnLength
;
1983 /* Setup the length and maximum length */
1984 FileLength
= (ULONG
)((ULONG_PTR
)p
- (ULONG_PTR
)ObjectNameInfo
);
1985 ObjectNameInfo
->Name
.Length
= (USHORT
)FileLength
-
1986 sizeof(OBJECT_NAME_INFORMATION
);
1987 ObjectNameInfo
->Name
.MaximumLength
= (USHORT
)ObjectNameInfo
->Name
.Length
+
1988 sizeof(UNICODE_NULL
);
1990 /* Free buffer and return */
1991 ExFreePoolWithTag(LocalInfo
, TAG_IO
);
1997 IopCloseFile(IN PEPROCESS Process OPTIONAL
,
1998 IN PVOID ObjectBody
,
1999 IN ACCESS_MASK GrantedAccess
,
2000 IN ULONG HandleCount
,
2001 IN ULONG SystemHandleCount
)
2003 PFILE_OBJECT FileObject
= (PFILE_OBJECT
)ObjectBody
;
2006 PIO_STACK_LOCATION StackPtr
;
2008 PDEVICE_OBJECT DeviceObject
;
2010 IO_STATUS_BLOCK IoStatusBlock
;
2011 IOTRACE(IO_FILE_DEBUG
, "ObjectBody: %p\n", ObjectBody
);
2013 /* If this isn't the last handle for the current process, quit */
2014 if (HandleCount
!= 1) return;
2016 /* Check if the file is locked and has more then one handle opened */
2017 if ((FileObject
->LockOperation
) && (SystemHandleCount
!= 1))
2019 /* Check if this is a direct open or not */
2020 if (BooleanFlagOn(FileObject
->Flags
, FO_DIRECT_DEVICE_OPEN
))
2022 /* Get the attached device */
2023 DeviceObject
= IoGetAttachedDevice(FileObject
->DeviceObject
);
2027 /* Get the FO's device */
2028 DeviceObject
= IoGetRelatedDeviceObject(FileObject
);
2031 /* Check if this is a sync FO and lock it */
2032 if (BooleanFlagOn(FileObject
->Flags
, FO_SYNCHRONOUS_IO
))
2034 (VOID
)IopLockFileObject(FileObject
, KernelMode
);
2037 /* Go the FastIO path if possible, otherwise fall back to IRP */
2038 if (DeviceObject
->DriverObject
->FastIoDispatch
== NULL
||
2039 DeviceObject
->DriverObject
->FastIoDispatch
->FastIoUnlockAll
== NULL
||
2040 !DeviceObject
->DriverObject
->FastIoDispatch
->FastIoUnlockAll(FileObject
, PsGetCurrentProcess(), &IoStatusBlock
, DeviceObject
))
2042 /* Clear and set up Events */
2043 KeClearEvent(&FileObject
->Event
);
2044 KeInitializeEvent(&Event
, SynchronizationEvent
, FALSE
);
2046 /* Allocate an IRP */
2047 Irp
= IopAllocateIrpMustSucceed(DeviceObject
->StackSize
);
2050 Irp
->UserEvent
= &Event
;
2051 Irp
->UserIosb
= &Irp
->IoStatus
;
2052 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
2053 Irp
->Tail
.Overlay
.OriginalFileObject
= FileObject
;
2054 Irp
->RequestorMode
= KernelMode
;
2055 Irp
->Flags
= IRP_SYNCHRONOUS_API
;
2056 Irp
->Overlay
.AsynchronousParameters
.UserApcRoutine
= NULL
;
2057 ObReferenceObject(FileObject
);
2059 /* Set up Stack Pointer Data */
2060 StackPtr
= IoGetNextIrpStackLocation(Irp
);
2061 StackPtr
->MajorFunction
= IRP_MJ_LOCK_CONTROL
;
2062 StackPtr
->MinorFunction
= IRP_MN_UNLOCK_ALL
;
2063 StackPtr
->FileObject
= FileObject
;
2066 IopQueueIrpToThread(Irp
);
2068 /* Call the FS Driver */
2069 Status
= IoCallDriver(DeviceObject
, Irp
);
2070 if (Status
== STATUS_PENDING
)
2072 /* Wait for completion */
2073 KeWaitForSingleObject(&Event
, UserRequest
, KernelMode
, FALSE
, NULL
);
2076 /* IO will unqueue & free for us */
2079 /* Release the lock if we were holding it */
2080 if (BooleanFlagOn(FileObject
->Flags
, FO_SYNCHRONOUS_IO
))
2082 IopUnlockFileObject(FileObject
);
2086 /* Make sure this is the last handle */
2087 if (SystemHandleCount
!= 1) return;
2089 /* Check if this is a direct open or not */
2090 if (FileObject
->Flags
& FO_DIRECT_DEVICE_OPEN
)
2092 /* Get the attached device */
2093 DeviceObject
= IoGetAttachedDevice(FileObject
->DeviceObject
);
2097 /* Get the FO's device */
2098 DeviceObject
= IoGetRelatedDeviceObject(FileObject
);
2101 /* Set the handle created flag */
2102 FileObject
->Flags
|= FO_HANDLE_CREATED
;
2104 /* Check if this is a sync FO and lock it */
2105 if (Process
!= NULL
&&
2106 BooleanFlagOn(FileObject
->Flags
, FO_SYNCHRONOUS_IO
))
2108 (VOID
)IopLockFileObject(FileObject
, KernelMode
);
2111 /* Clear and set up Events */
2112 KeClearEvent(&FileObject
->Event
);
2113 KeInitializeEvent(&Event
, SynchronizationEvent
, FALSE
);
2115 /* Allocate an IRP */
2116 Irp
= IopAllocateIrpMustSucceed(DeviceObject
->StackSize
);
2119 Irp
->UserEvent
= &Event
;
2120 Irp
->UserIosb
= &Irp
->IoStatus
;
2121 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
2122 Irp
->Tail
.Overlay
.OriginalFileObject
= FileObject
;
2123 Irp
->Overlay
.AsynchronousParameters
.UserApcRoutine
= NULL
;
2124 Irp
->Flags
= IRP_CLOSE_OPERATION
| IRP_SYNCHRONOUS_API
;
2126 /* Set up Stack Pointer Data */
2127 StackPtr
= IoGetNextIrpStackLocation(Irp
);
2128 StackPtr
->MajorFunction
= IRP_MJ_CLEANUP
;
2129 StackPtr
->FileObject
= FileObject
;
2132 IopQueueIrpToThread(Irp
);
2134 /* Update operation counts */
2135 IopUpdateOperationCount(IopOtherTransfer
);
2137 /* Call the FS Driver */
2138 Status
= IoCallDriver(DeviceObject
, Irp
);
2139 if (Status
== STATUS_PENDING
)
2141 /* Wait for completion */
2142 KeWaitForSingleObject(&Event
, UserRequest
, KernelMode
, FALSE
, NULL
);
2145 /* Unqueue the IRP */
2146 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
2147 IopUnQueueIrpFromThread(Irp
);
2148 KeLowerIrql(OldIrql
);
2153 /* Release the lock if we were holding it */
2154 if (Process
!= NULL
&&
2155 BooleanFlagOn(FileObject
->Flags
, FO_SYNCHRONOUS_IO
))
2157 IopUnlockFileObject(FileObject
);
2163 IopQueryAttributesFile(IN POBJECT_ATTRIBUTES ObjectAttributes
,
2164 IN FILE_INFORMATION_CLASS FileInformationClass
,
2165 IN ULONG FileInformationSize
,
2166 OUT PVOID FileInformation
)
2169 KPROCESSOR_MODE AccessMode
= ExGetPreviousMode();
2170 DUMMY_FILE_OBJECT LocalFileObject
;
2171 FILE_NETWORK_OPEN_INFORMATION NetworkOpenInfo
;
2173 OPEN_PACKET OpenPacket
;
2176 IOTRACE(IO_FILE_DEBUG
, "Class: %lx\n", FileInformationClass
);
2178 /* Check if the caller was user mode */
2179 if (AccessMode
!= KernelMode
)
2181 /* Protect probe in SEH */
2184 /* Probe the buffer */
2185 ProbeForWrite(FileInformation
, FileInformationSize
, sizeof(ULONG
));
2187 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2189 /* Return the exception code */
2190 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2195 /* Check if this is a basic or full request */
2196 IsBasic
= (FileInformationSize
== sizeof(FILE_BASIC_INFORMATION
));
2198 /* Setup the Open Packet */
2199 RtlZeroMemory(&OpenPacket
, sizeof(OPEN_PACKET
));
2200 OpenPacket
.Type
= IO_TYPE_OPEN_PACKET
;
2201 OpenPacket
.Size
= sizeof(OPEN_PACKET
);
2202 OpenPacket
.CreateOptions
= FILE_OPEN_REPARSE_POINT
;
2203 OpenPacket
.ShareAccess
= FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
;
2204 OpenPacket
.Disposition
= FILE_OPEN
;
2205 OpenPacket
.BasicInformation
= IsBasic
? FileInformation
: NULL
;
2206 OpenPacket
.NetworkInformation
= IsBasic
? &NetworkOpenInfo
:
2207 (AccessMode
!= KernelMode
) ?
2208 &NetworkOpenInfo
: FileInformation
;
2209 OpenPacket
.QueryOnly
= TRUE
;
2210 OpenPacket
.FullAttributes
= IsBasic
? FALSE
: TRUE
;
2211 OpenPacket
.LocalFileObject
= &LocalFileObject
;
2213 /* Update the operation count */
2214 IopUpdateOperationCount(IopOtherTransfer
);
2217 * Attempt opening the file. This will call the I/O Parse Routine for
2218 * the File Object (IopParseDevice) which will use the dummy file obejct
2219 * send the IRP to its device object. Note that we have two statuses
2220 * to worry about: the Object Manager's status (in Status) and the I/O
2221 * status, which is in the Open Packet's Final Status, and determined
2222 * by the Parse Check member.
2224 Status
= ObOpenObjectByName(ObjectAttributes
,
2228 FILE_READ_ATTRIBUTES
,
2231 if (OpenPacket
.ParseCheck
== FALSE
)
2234 DPRINT("IopQueryAttributesFile failed for '%wZ' with 0x%lx\n",
2235 ObjectAttributes
->ObjectName
, Status
);
2240 /* Use the Io status */
2241 Status
= OpenPacket
.FinalStatus
;
2244 /* Check if we were succesful and this was user mode and a full query */
2245 if ((NT_SUCCESS(Status
)) && (AccessMode
!= KernelMode
) && !(IsBasic
))
2247 /* Enter SEH for copy */
2250 /* Copy the buffer back */
2251 RtlCopyMemory(FileInformation
,
2253 FileInformationSize
);
2255 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2257 /* Get exception code */
2258 Status
= _SEH2_GetExceptionCode();
2269 IopAcquireFileObjectLock(
2270 _In_ PFILE_OBJECT FileObject
,
2271 _In_ KPROCESSOR_MODE WaitMode
,
2272 _In_ BOOLEAN Alertable
,
2273 _Out_ PBOOLEAN LockFailed
)
2279 InterlockedIncrement((PLONG
)&FileObject
->Waiters
);
2281 Status
= STATUS_SUCCESS
;
2284 if (!InterlockedExchange((PLONG
)&FileObject
->Busy
, TRUE
))
2288 Status
= KeWaitForSingleObject(&FileObject
->Lock
,
2293 } while (Status
== STATUS_SUCCESS
);
2295 InterlockedDecrement((PLONG
)&FileObject
->Waiters
);
2296 if (Status
== STATUS_SUCCESS
)
2298 ObReferenceObject(FileObject
);
2299 *LockFailed
= FALSE
;
2303 if (!FileObject
->Busy
&& FileObject
->Waiters
)
2305 KeSetEvent(&FileObject
->Lock
, IO_NO_INCREMENT
, FALSE
);
2315 IoGetFileObjectFilterContext(IN PFILE_OBJECT FileObject
)
2317 if (FileObject
->Flags
& FO_FILE_OBJECT_HAS_EXTENSION
)
2320 /* FIXME: return NULL for the moment ~ */
2329 IoChangeFileObjectFilterContext(IN PFILE_OBJECT FileObject
,
2330 IN PVOID FilterContext
,
2333 if (!(FileObject
->Flags
& FO_FILE_OBJECT_HAS_EXTENSION
))
2335 return STATUS_INVALID_PARAMETER
;
2340 return STATUS_NOT_IMPLEMENTED
;
2345 IopCreateFile(OUT PHANDLE FileHandle
,
2346 IN ACCESS_MASK DesiredAccess
,
2347 IN POBJECT_ATTRIBUTES ObjectAttributes
,
2348 OUT PIO_STATUS_BLOCK IoStatusBlock
,
2349 IN PLARGE_INTEGER AllocationSize OPTIONAL
,
2350 IN ULONG FileAttributes
,
2351 IN ULONG ShareAccess
,
2352 IN ULONG Disposition
,
2353 IN ULONG CreateOptions
,
2354 IN PVOID EaBuffer OPTIONAL
,
2356 IN CREATE_FILE_TYPE CreateFileType
,
2357 IN PVOID ExtraCreateParameters OPTIONAL
,
2360 IN PDEVICE_OBJECT DeviceObject OPTIONAL
)
2362 KPROCESSOR_MODE AccessMode
;
2363 HANDLE LocalHandle
= 0;
2364 LARGE_INTEGER SafeAllocationSize
;
2365 NTSTATUS Status
= STATUS_SUCCESS
;
2366 PNAMED_PIPE_CREATE_PARAMETERS NamedPipeCreateParameters
;
2367 POPEN_PACKET OpenPacket
;
2368 ULONG EaErrorOffset
;
2371 IOTRACE(IO_FILE_DEBUG
, "FileName: %wZ\n", ObjectAttributes
->ObjectName
);
2374 /* Check if we have no parameter checking to do */
2375 if (Options
& IO_NO_PARAMETER_CHECKING
)
2377 /* Then force kernel-mode access to avoid checks */
2378 AccessMode
= KernelMode
;
2382 /* Otherwise, use the actual mode */
2383 AccessMode
= ExGetPreviousMode();
2386 /* Check if we need to do parameter checking */
2387 if ((AccessMode
!= KernelMode
) || (Options
& IO_CHECK_CREATE_PARAMETERS
))
2389 /* Validate parameters */
2390 if (FileAttributes
& ~FILE_ATTRIBUTE_VALID_FLAGS
)
2392 DPRINT1("File Create 'FileAttributes' Parameter contains invalid flags!\n");
2393 return STATUS_INVALID_PARAMETER
;
2396 if (ShareAccess
& ~FILE_SHARE_VALID_FLAGS
)
2398 DPRINT1("File Create 'ShareAccess' Parameter contains invalid flags!\n");
2399 return STATUS_INVALID_PARAMETER
;
2402 if (Disposition
> FILE_MAXIMUM_DISPOSITION
)
2404 DPRINT1("File Create 'Disposition' Parameter is out of range!\n");
2405 return STATUS_INVALID_PARAMETER
;
2408 if (CreateOptions
& ~FILE_VALID_OPTION_FLAGS
)
2410 DPRINT1("File Create 'CreateOptions' parameter contains invalid flags!\n");
2411 return STATUS_INVALID_PARAMETER
;
2414 if ((CreateOptions
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)) &&
2415 (!(DesiredAccess
& SYNCHRONIZE
)))
2417 DPRINT1("File Create 'CreateOptions' parameter FILE_SYNCHRONOUS_IO_* requested, but 'DesiredAccess' does not have SYNCHRONIZE!\n");
2418 return STATUS_INVALID_PARAMETER
;
2421 if ((CreateOptions
& FILE_DELETE_ON_CLOSE
) && (!(DesiredAccess
& DELETE
)))
2423 DPRINT1("File Create 'CreateOptions' parameter FILE_DELETE_ON_CLOSE requested, but 'DesiredAccess' does not have DELETE!\n");
2424 return STATUS_INVALID_PARAMETER
;
2427 if ((CreateOptions
& (FILE_SYNCHRONOUS_IO_NONALERT
| FILE_SYNCHRONOUS_IO_ALERT
)) ==
2428 (FILE_SYNCHRONOUS_IO_NONALERT
| FILE_SYNCHRONOUS_IO_ALERT
))
2430 DPRINT1("File Create 'FileAttributes' parameter both FILE_SYNCHRONOUS_IO_NONALERT and FILE_SYNCHRONOUS_IO_ALERT specified!\n");
2431 return STATUS_INVALID_PARAMETER
;
2434 if ((CreateOptions
& FILE_DIRECTORY_FILE
) && !(CreateOptions
& FILE_NON_DIRECTORY_FILE
) &&
2435 (CreateOptions
& ~(FILE_DIRECTORY_FILE
|
2436 FILE_SYNCHRONOUS_IO_ALERT
|
2437 FILE_SYNCHRONOUS_IO_NONALERT
|
2438 FILE_WRITE_THROUGH
|
2439 FILE_COMPLETE_IF_OPLOCKED
|
2440 FILE_OPEN_FOR_BACKUP_INTENT
|
2441 FILE_DELETE_ON_CLOSE
|
2442 FILE_OPEN_FOR_FREE_SPACE_QUERY
|
2443 FILE_OPEN_BY_FILE_ID
|
2444 FILE_NO_COMPRESSION
|
2445 FILE_OPEN_REPARSE_POINT
)))
2447 DPRINT1("File Create 'CreateOptions' Parameter has flags incompatible with FILE_DIRECTORY_FILE!\n");
2448 return STATUS_INVALID_PARAMETER
;
2451 if ((CreateOptions
& FILE_DIRECTORY_FILE
) && !(CreateOptions
& FILE_NON_DIRECTORY_FILE
) &&
2452 (Disposition
!= FILE_CREATE
) && (Disposition
!= FILE_OPEN
) && (Disposition
!= FILE_OPEN_IF
))
2454 DPRINT1("File Create 'CreateOptions' Parameter FILE_DIRECTORY_FILE requested, but 'Disposition' is not FILE_CREATE/FILE_OPEN/FILE_OPEN_IF!\n");
2455 return STATUS_INVALID_PARAMETER
;
2458 if ((CreateOptions
& FILE_COMPLETE_IF_OPLOCKED
) && (CreateOptions
& FILE_RESERVE_OPFILTER
))
2460 DPRINT1("File Create 'CreateOptions' Parameter both FILE_COMPLETE_IF_OPLOCKED and FILE_RESERVE_OPFILTER specified!\n");
2461 return STATUS_INVALID_PARAMETER
;
2464 if ((CreateOptions
& FILE_NO_INTERMEDIATE_BUFFERING
) && (DesiredAccess
& FILE_APPEND_DATA
))
2466 DPRINT1("File Create 'CreateOptions' parameter FILE_NO_INTERMEDIATE_BUFFERING requested, but 'DesiredAccess' FILE_APPEND_DATA requires it!\n");
2467 return STATUS_INVALID_PARAMETER
;
2470 /* Now check if this is a named pipe */
2471 if (CreateFileType
== CreateFileTypeNamedPipe
)
2473 /* Make sure we have extra parameters */
2474 if (!ExtraCreateParameters
)
2476 DPRINT1("Invalid parameter: ExtraCreateParameters == 0!\n");
2477 return STATUS_INVALID_PARAMETER
;
2480 /* Get the parameters and validate them */
2481 NamedPipeCreateParameters
= ExtraCreateParameters
;
2482 if ((NamedPipeCreateParameters
->NamedPipeType
> FILE_PIPE_MESSAGE_TYPE
) ||
2483 (NamedPipeCreateParameters
->ReadMode
> FILE_PIPE_MESSAGE_MODE
) ||
2484 (NamedPipeCreateParameters
->CompletionMode
> FILE_PIPE_COMPLETE_OPERATION
) ||
2485 (ShareAccess
& FILE_SHARE_DELETE
) ||
2486 ((Disposition
< FILE_OPEN
) || (Disposition
> FILE_OPEN_IF
)) ||
2487 (CreateOptions
& ~FILE_VALID_PIPE_OPTION_FLAGS
))
2489 /* Invalid named pipe create */
2490 DPRINT1("Invalid named pipe create\n");
2491 return STATUS_INVALID_PARAMETER
;
2494 else if (CreateFileType
== CreateFileTypeMailslot
)
2496 /* Make sure we have extra parameters */
2497 if (!ExtraCreateParameters
)
2499 DPRINT1("Invalid parameter: ExtraCreateParameters == 0!\n");
2500 return STATUS_INVALID_PARAMETER
;
2503 /* Get the parameters and validate them */
2504 if ((ShareAccess
& FILE_SHARE_DELETE
) ||
2505 !(ShareAccess
& ~FILE_SHARE_WRITE
) ||
2506 (Disposition
!= FILE_CREATE
) ||
2507 (CreateOptions
& ~FILE_VALID_MAILSLOT_OPTION_FLAGS
))
2509 /* Invalid mailslot create */
2510 DPRINT1("Invalid mailslot create\n");
2511 return STATUS_INVALID_PARAMETER
;
2516 /* Allocate the open packet */
2517 OpenPacket
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(*OpenPacket
), 'pOoI');
2518 if (!OpenPacket
) return STATUS_INSUFFICIENT_RESOURCES
;
2519 RtlZeroMemory(OpenPacket
, sizeof(*OpenPacket
));
2521 /* Check if the call came from user mode */
2522 if (AccessMode
!= KernelMode
)
2526 /* Probe the output parameters */
2527 ProbeForWriteHandle(FileHandle
);
2528 ProbeForWriteIoStatusBlock(IoStatusBlock
);
2530 /* Probe the allocation size if one was passed in */
2533 SafeAllocationSize
= ProbeForReadLargeInteger(AllocationSize
);
2537 SafeAllocationSize
.QuadPart
= 0;
2540 /* Make sure it's valid */
2541 if (SafeAllocationSize
.QuadPart
< 0)
2543 RtlRaiseStatus(STATUS_INVALID_PARAMETER
);
2546 /* Check if EA was passed in */
2547 if ((EaBuffer
) && (EaLength
))
2550 ProbeForRead(EaBuffer
, EaLength
, sizeof(ULONG
));
2552 /* And marshall it */
2553 OpenPacket
->EaBuffer
= ExAllocatePoolWithTag(NonPagedPool
,
2556 OpenPacket
->EaLength
= EaLength
;
2557 RtlCopyMemory(OpenPacket
->EaBuffer
, EaBuffer
, EaLength
);
2559 /* Validate the buffer */
2560 Status
= IoCheckEaBufferValidity(OpenPacket
->EaBuffer
,
2563 if (!NT_SUCCESS(Status
))
2565 /* Undo everything if it's invalid */
2566 DPRINT1("Invalid EA buffer\n");
2567 IoStatusBlock
->Status
= Status
;
2568 IoStatusBlock
->Information
= EaErrorOffset
;
2569 RtlRaiseStatus(Status
);
2573 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2575 /* Return the exception code */
2576 if (OpenPacket
->EaBuffer
!= NULL
) ExFreePool(OpenPacket
->EaBuffer
);
2577 ExFreePool(OpenPacket
);
2578 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2584 /* Check if this is a device attach */
2585 if (CreateOptions
& IO_ATTACH_DEVICE_API
)
2587 /* Set the flag properly */
2588 Options
|= IO_ATTACH_DEVICE
;
2589 CreateOptions
&= ~IO_ATTACH_DEVICE_API
;
2592 /* Check if we have allocation size */
2596 SafeAllocationSize
= *AllocationSize
;
2600 /* Otherwise, no size */
2601 SafeAllocationSize
.QuadPart
= 0;
2604 /* Check if we have an EA packet */
2605 if ((EaBuffer
) && (EaLength
))
2607 /* Allocate the kernel copy */
2608 OpenPacket
->EaBuffer
= ExAllocatePoolWithTag(NonPagedPool
,
2611 if (!OpenPacket
->EaBuffer
)
2613 ExFreePool(OpenPacket
);
2614 DPRINT1("Failed to allocate open packet EA buffer\n");
2615 return STATUS_INSUFFICIENT_RESOURCES
;
2619 OpenPacket
->EaLength
= EaLength
;
2620 RtlCopyMemory(OpenPacket
->EaBuffer
, EaBuffer
, EaLength
);
2622 /* Validate the buffer */
2623 Status
= IoCheckEaBufferValidity(OpenPacket
->EaBuffer
,
2626 if (!NT_SUCCESS(Status
))
2628 /* Undo everything if it's invalid */
2629 DPRINT1("Invalid EA buffer\n");
2630 ExFreePool(OpenPacket
->EaBuffer
);
2631 IoStatusBlock
->Status
= Status
;
2632 IoStatusBlock
->Information
= EaErrorOffset
;
2633 ExFreePool(OpenPacket
);
2639 /* Setup the Open Packet */
2640 OpenPacket
->Type
= IO_TYPE_OPEN_PACKET
;
2641 OpenPacket
->Size
= sizeof(*OpenPacket
);
2642 OpenPacket
->AllocationSize
= SafeAllocationSize
;
2643 OpenPacket
->CreateOptions
= CreateOptions
;
2644 OpenPacket
->FileAttributes
= (USHORT
)FileAttributes
;
2645 OpenPacket
->ShareAccess
= (USHORT
)ShareAccess
;
2646 OpenPacket
->Options
= Options
;
2647 OpenPacket
->Disposition
= Disposition
;
2648 OpenPacket
->CreateFileType
= CreateFileType
;
2649 OpenPacket
->ExtraCreateParameters
= ExtraCreateParameters
;
2650 OpenPacket
->InternalFlags
= Flags
;
2651 OpenPacket
->TopDeviceObjectHint
= DeviceObject
;
2653 /* Update the operation count */
2654 IopUpdateOperationCount(IopOtherTransfer
);
2657 * Attempt opening the file. This will call the I/O Parse Routine for
2658 * the File Object (IopParseDevice) which will create the object and
2659 * send the IRP to its device object. Note that we have two statuses
2660 * to worry about: the Object Manager's status (in Status) and the I/O
2661 * status, which is in the Open Packet's Final Status, and determined
2662 * by the Parse Check member.
2664 Status
= ObOpenObjectByName(ObjectAttributes
,
2672 /* Free the EA Buffer */
2673 if (OpenPacket
->EaBuffer
) ExFreePool(OpenPacket
->EaBuffer
);
2675 /* Now check for Ob or Io failure */
2676 if (!(NT_SUCCESS(Status
)) || (OpenPacket
->ParseCheck
== FALSE
))
2678 /* Check if Ob thinks well went well */
2679 if (NT_SUCCESS(Status
))
2682 * Tell it otherwise. Because we didn't use an ObjectType,
2683 * it incorrectly returned us a handle to God knows what.
2685 ZwClose(LocalHandle
);
2686 Status
= STATUS_OBJECT_TYPE_MISMATCH
;
2689 /* Now check the Io status */
2690 if (!NT_SUCCESS(OpenPacket
->FinalStatus
))
2692 /* Use this status instead of Ob's */
2693 Status
= OpenPacket
->FinalStatus
;
2695 /* Check if it was only a warning */
2696 if (NT_WARNING(Status
))
2698 /* Protect write with SEH */
2701 /* In this case, we copy the I/O Status back */
2702 IoStatusBlock
->Information
= OpenPacket
->Information
;
2703 IoStatusBlock
->Status
= OpenPacket
->FinalStatus
;
2705 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2707 /* Get exception code */
2708 Status
= _SEH2_GetExceptionCode();
2713 else if ((OpenPacket
->FileObject
) && (OpenPacket
->ParseCheck
== FALSE
))
2716 * This can happen in the very bizarre case where the parse routine
2717 * actually executed more then once (due to a reparse) and ended
2718 * up failing after already having created the File Object.
2720 if (OpenPacket
->FileObject
->FileName
.Length
)
2722 /* It had a name, free it */
2723 ExFreePoolWithTag(OpenPacket
->FileObject
->FileName
.Buffer
, TAG_IO_NAME
);
2726 /* Clear the device object to invalidate the FO, and dereference */
2727 OpenPacket
->FileObject
->DeviceObject
= NULL
;
2728 ObDereferenceObject(OpenPacket
->FileObject
);
2733 /* We reached success and have a valid file handle */
2734 OpenPacket
->FileObject
->Flags
|= FO_HANDLE_CREATED
;
2735 ASSERT(OpenPacket
->FileObject
->Type
== IO_TYPE_FILE
);
2737 /* Enter SEH for write back */
2740 /* Write back the handle and I/O Status */
2741 *FileHandle
= LocalHandle
;
2742 IoStatusBlock
->Information
= OpenPacket
->Information
;
2743 IoStatusBlock
->Status
= OpenPacket
->FinalStatus
;
2745 /* Get the Io status */
2746 Status
= OpenPacket
->FinalStatus
;
2748 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2750 /* Get the exception status */
2751 Status
= _SEH2_GetExceptionCode();
2756 /* Check if we were 100% successful */
2757 if ((OpenPacket
->ParseCheck
!= FALSE
) && (OpenPacket
->FileObject
))
2759 /* Dereference the File Object */
2760 ObDereferenceObject(OpenPacket
->FileObject
);
2764 ExFreePool(OpenPacket
);
2768 /* FUNCTIONS *****************************************************************/
2775 IoCheckQuerySetFileInformation(IN FILE_INFORMATION_CLASS FileInformationClass
,
2777 IN BOOLEAN SetOperation
)
2780 return STATUS_NOT_IMPLEMENTED
;
2788 IoCheckQuotaBufferValidity(IN PFILE_QUOTA_INFORMATION QuotaBuffer
,
2789 IN ULONG QuotaLength
,
2790 OUT PULONG ErrorOffset
)
2793 return STATUS_NOT_IMPLEMENTED
;
2801 IoCreateFile(OUT PHANDLE FileHandle
,
2802 IN ACCESS_MASK DesiredAccess
,
2803 IN POBJECT_ATTRIBUTES ObjectAttributes
,
2804 OUT PIO_STATUS_BLOCK IoStatusBlock
,
2805 IN PLARGE_INTEGER AllocationSize OPTIONAL
,
2806 IN ULONG FileAttributes
,
2807 IN ULONG ShareAccess
,
2808 IN ULONG Disposition
,
2809 IN ULONG CreateOptions
,
2810 IN PVOID EaBuffer OPTIONAL
,
2812 IN CREATE_FILE_TYPE CreateFileType
,
2813 IN PVOID ExtraCreateParameters OPTIONAL
,
2818 return IopCreateFile(FileHandle
,
2830 ExtraCreateParameters
,
2841 IoCreateFileSpecifyDeviceObjectHint(OUT PHANDLE FileHandle
,
2842 IN ACCESS_MASK DesiredAccess
,
2843 IN POBJECT_ATTRIBUTES ObjectAttributes
,
2844 OUT PIO_STATUS_BLOCK IoStatusBlock
,
2845 IN PLARGE_INTEGER AllocationSize OPTIONAL
,
2846 IN ULONG FileAttributes
,
2847 IN ULONG ShareAccess
,
2848 IN ULONG Disposition
,
2849 IN ULONG CreateOptions
,
2850 IN PVOID EaBuffer OPTIONAL
,
2852 IN CREATE_FILE_TYPE CreateFileType
,
2853 IN PVOID ExtraCreateParameters OPTIONAL
,
2855 IN PVOID DeviceObject
)
2861 /* Check if we were passed a device to send the create request to*/
2864 /* We'll tag this request into a file object extension */
2865 Flags
= (IOP_CREATE_FILE_OBJECT_EXTENSION
| IOP_USE_TOP_LEVEL_DEVICE_HINT
);
2868 return IopCreateFile(FileHandle
,
2880 ExtraCreateParameters
,
2881 Options
| IO_NO_PARAMETER_CHECKING
,
2891 IoCreateStreamFileObjectEx(IN PFILE_OBJECT FileObject OPTIONAL
,
2892 IN PDEVICE_OBJECT DeviceObject OPTIONAL
,
2893 OUT PHANDLE FileObjectHandle OPTIONAL
)
2895 PFILE_OBJECT CreatedFileObject
;
2898 OBJECT_ATTRIBUTES ObjectAttributes
;
2900 IOTRACE(IO_FILE_DEBUG
, "FileObject: %p\n", FileObject
);
2902 /* Choose Device Object */
2903 if (FileObject
) DeviceObject
= FileObject
->DeviceObject
;
2905 /* Reference the device object and initialize attributes */
2906 InterlockedIncrement(&DeviceObject
->ReferenceCount
);
2907 InitializeObjectAttributes(&ObjectAttributes
, NULL
, 0, NULL
, NULL
);
2909 /* Create the File Object */
2910 Status
= ObCreateObject(KernelMode
,
2915 sizeof(FILE_OBJECT
),
2916 sizeof(FILE_OBJECT
),
2918 (PVOID
*)&CreatedFileObject
);
2919 if (!NT_SUCCESS(Status
))
2922 IopDereferenceDeviceObject(DeviceObject
, FALSE
);
2923 ExRaiseStatus(Status
);
2926 /* Set File Object Data */
2927 RtlZeroMemory(CreatedFileObject
, sizeof(FILE_OBJECT
));
2928 CreatedFileObject
->DeviceObject
= DeviceObject
;
2929 CreatedFileObject
->Type
= IO_TYPE_FILE
;
2930 CreatedFileObject
->Size
= sizeof(FILE_OBJECT
);
2931 CreatedFileObject
->Flags
= FO_STREAM_FILE
;
2933 /* Initialize the wait event */
2934 KeInitializeEvent(&CreatedFileObject
->Event
, SynchronizationEvent
, FALSE
);
2936 /* Insert it to create a handle for it */
2937 Status
= ObInsertObject(CreatedFileObject
,
2941 (PVOID
*)&CreatedFileObject
,
2943 if (!NT_SUCCESS(Status
)) ExRaiseStatus(Status
);
2945 /* Set the handle created flag */
2946 CreatedFileObject
->Flags
|= FO_HANDLE_CREATED
;
2947 ASSERT(CreatedFileObject
->Type
== IO_TYPE_FILE
);
2949 /* Check if we have a VPB */
2950 if (DeviceObject
->Vpb
)
2953 InterlockedIncrement((PLONG
)&DeviceObject
->Vpb
->ReferenceCount
);
2956 /* Check if the caller wants the handle */
2957 if (FileObjectHandle
)
2960 *FileObjectHandle
= FileHandle
;
2961 ObDereferenceObject(CreatedFileObject
);
2965 /* Otherwise, close it */
2966 ObCloseHandle(FileHandle
, KernelMode
);
2969 /* Return the file object */
2970 return CreatedFileObject
;
2978 IoCreateStreamFileObject(IN PFILE_OBJECT FileObject
,
2979 IN PDEVICE_OBJECT DeviceObject
)
2981 /* Call the newer function */
2982 return IoCreateStreamFileObjectEx(FileObject
, DeviceObject
, NULL
);
2990 IoCreateStreamFileObjectLite(IN PFILE_OBJECT FileObject OPTIONAL
,
2991 IN PDEVICE_OBJECT DeviceObject OPTIONAL
)
2993 PFILE_OBJECT CreatedFileObject
;
2995 OBJECT_ATTRIBUTES ObjectAttributes
;
2997 IOTRACE(IO_FILE_DEBUG
, "FileObject: %p\n", FileObject
);
2999 /* Choose Device Object */
3000 if (FileObject
) DeviceObject
= FileObject
->DeviceObject
;
3002 /* Reference the device object and initialize attributes */
3003 InterlockedIncrement(&DeviceObject
->ReferenceCount
);
3004 InitializeObjectAttributes(&ObjectAttributes
, NULL
, 0, NULL
, NULL
);
3006 /* Create the File Object */
3007 Status
= ObCreateObject(KernelMode
,
3012 sizeof(FILE_OBJECT
),
3013 sizeof(FILE_OBJECT
),
3015 (PVOID
*)&CreatedFileObject
);
3016 if (!NT_SUCCESS(Status
))
3019 IopDereferenceDeviceObject(DeviceObject
, FALSE
);
3020 ExRaiseStatus(Status
);
3023 /* Set File Object Data */
3024 RtlZeroMemory(CreatedFileObject
, sizeof(FILE_OBJECT
));
3025 CreatedFileObject
->DeviceObject
= DeviceObject
;
3026 CreatedFileObject
->Type
= IO_TYPE_FILE
;
3027 CreatedFileObject
->Size
= sizeof(FILE_OBJECT
);
3028 CreatedFileObject
->Flags
= FO_STREAM_FILE
;
3030 /* Initialize the wait event */
3031 KeInitializeEvent(&CreatedFileObject
->Event
, SynchronizationEvent
, FALSE
);
3033 /* Destroy create information */
3034 ObFreeObjectCreateInfoBuffer(OBJECT_TO_OBJECT_HEADER(CreatedFileObject
)->
3036 OBJECT_TO_OBJECT_HEADER(CreatedFileObject
)->ObjectCreateInfo
= NULL
;
3038 /* Set the handle created flag */
3039 CreatedFileObject
->Flags
|= FO_HANDLE_CREATED
;
3040 ASSERT(CreatedFileObject
->Type
== IO_TYPE_FILE
);
3042 /* Check if we have a VPB */
3043 if (DeviceObject
->Vpb
)
3046 InterlockedIncrement((PLONG
)&DeviceObject
->Vpb
->ReferenceCount
);
3049 /* Return the file object */
3050 return CreatedFileObject
;
3058 IoGetFileObjectGenericMapping(VOID
)
3060 /* Return the mapping */
3061 return &IopFileMapping
;
3069 IoIsFileOriginRemote(IN PFILE_OBJECT FileObject
)
3071 /* Return the flag status */
3072 return FileObject
->Flags
& FO_REMOTE_ORIGIN
? TRUE
: FALSE
;
3080 IoFastQueryNetworkAttributes(IN POBJECT_ATTRIBUTES ObjectAttributes
,
3081 IN ACCESS_MASK DesiredAccess
,
3082 IN ULONG OpenOptions
,
3083 OUT PIO_STATUS_BLOCK IoStatus
,
3084 OUT PFILE_NETWORK_OPEN_INFORMATION Buffer
)
3087 DUMMY_FILE_OBJECT LocalFileObject
;
3089 OPEN_PACKET OpenPacket
;
3091 IOTRACE(IO_FILE_DEBUG
, "FileName: %wZ\n", ObjectAttributes
->ObjectName
);
3093 /* Setup the Open Packet */
3094 RtlZeroMemory(&OpenPacket
, sizeof(OPEN_PACKET
));
3095 OpenPacket
.Type
= IO_TYPE_OPEN_PACKET
;
3096 OpenPacket
.Size
= sizeof(OPEN_PACKET
);
3097 OpenPacket
.CreateOptions
= OpenOptions
| FILE_OPEN_REPARSE_POINT
;
3098 OpenPacket
.ShareAccess
= FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
;
3099 OpenPacket
.Options
= IO_FORCE_ACCESS_CHECK
;
3100 OpenPacket
.Disposition
= FILE_OPEN
;
3101 OpenPacket
.NetworkInformation
= Buffer
;
3102 OpenPacket
.QueryOnly
= TRUE
;
3103 OpenPacket
.FullAttributes
= TRUE
;
3104 OpenPacket
.LocalFileObject
= &LocalFileObject
;
3107 * Attempt opening the file. This will call the I/O Parse Routine for
3108 * the File Object (IopParseDevice) which will use the dummy file obejct
3109 * send the IRP to its device object. Note that we have two statuses
3110 * to worry about: the Object Manager's status (in Status) and the I/O
3111 * status, which is in the Open Packet's Final Status, and determined
3112 * by the Parse Check member.
3114 Status
= ObOpenObjectByName(ObjectAttributes
,
3121 if (OpenPacket
.ParseCheck
== FALSE
)
3124 IoStatus
->Status
= Status
;
3128 /* Use the Io status */
3129 IoStatus
->Status
= OpenPacket
.FinalStatus
;
3130 IoStatus
->Information
= OpenPacket
.Information
;
3133 /* Return success */
3142 IoUpdateShareAccess(IN PFILE_OBJECT FileObject
,
3143 OUT PSHARE_ACCESS ShareAccess
)
3147 /* Check if the file has an extension */
3148 if (FileObject
->Flags
& FO_FILE_OBJECT_HAS_EXTENSION
)
3150 /* Check if caller specified to ignore access checks */
3151 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3153 /* Don't update share access */
3158 /* Otherwise, check if there's any access present */
3159 if ((FileObject
->ReadAccess
) ||
3160 (FileObject
->WriteAccess
) ||
3161 (FileObject
->DeleteAccess
))
3163 /* Increase the open count */
3164 ShareAccess
->OpenCount
++;
3166 /* Add new share access */
3167 ShareAccess
->Readers
+= FileObject
->ReadAccess
;
3168 ShareAccess
->Writers
+= FileObject
->WriteAccess
;
3169 ShareAccess
->Deleters
+= FileObject
->DeleteAccess
;
3170 ShareAccess
->SharedRead
+= FileObject
->SharedRead
;
3171 ShareAccess
->SharedWrite
+= FileObject
->SharedWrite
;
3172 ShareAccess
->SharedDelete
+= FileObject
->SharedDelete
;
3181 IoCheckShareAccess(IN ACCESS_MASK DesiredAccess
,
3182 IN ULONG DesiredShareAccess
,
3183 IN PFILE_OBJECT FileObject
,
3184 IN PSHARE_ACCESS ShareAccess
,
3188 BOOLEAN WriteAccess
;
3189 BOOLEAN DeleteAccess
;
3191 BOOLEAN SharedWrite
;
3192 BOOLEAN SharedDelete
;
3195 /* Get access masks */
3196 ReadAccess
= (DesiredAccess
& (FILE_READ_DATA
| FILE_EXECUTE
)) != 0;
3197 WriteAccess
= (DesiredAccess
& (FILE_WRITE_DATA
| FILE_APPEND_DATA
)) != 0;
3198 DeleteAccess
= (DesiredAccess
& DELETE
) != 0;
3200 /* Set them in the file object */
3201 FileObject
->ReadAccess
= ReadAccess
;
3202 FileObject
->WriteAccess
= WriteAccess
;
3203 FileObject
->DeleteAccess
= DeleteAccess
;
3205 /* Check if the file has an extension */
3206 if (FileObject
->Flags
& FO_FILE_OBJECT_HAS_EXTENSION
)
3208 /* Check if caller specified to ignore access checks */
3209 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3211 /* Don't check share access */
3212 return STATUS_SUCCESS
;
3216 /* Check if we have any access */
3217 if ((ReadAccess
) || (WriteAccess
) || (DeleteAccess
))
3219 /* Get shared access masks */
3220 SharedRead
= (DesiredShareAccess
& FILE_SHARE_READ
) != 0;
3221 SharedWrite
= (DesiredShareAccess
& FILE_SHARE_WRITE
) != 0;
3222 SharedDelete
= (DesiredShareAccess
& FILE_SHARE_DELETE
) != 0;
3225 FileObject
->SharedRead
= SharedRead
;
3226 FileObject
->SharedWrite
= SharedWrite
;
3227 FileObject
->SharedDelete
= SharedDelete
;
3229 /* Check if the shared access is violated */
3231 (ShareAccess
->SharedRead
< ShareAccess
->OpenCount
)) ||
3233 (ShareAccess
->SharedWrite
< ShareAccess
->OpenCount
)) ||
3235 (ShareAccess
->SharedDelete
< ShareAccess
->OpenCount
)) ||
3236 ((ShareAccess
->Readers
!= 0) && !SharedRead
) ||
3237 ((ShareAccess
->Writers
!= 0) && !SharedWrite
) ||
3238 ((ShareAccess
->Deleters
!= 0) && !SharedDelete
))
3240 /* Sharing violation, fail */
3241 return STATUS_SHARING_VIOLATION
;
3244 /* It's not, check if caller wants us to update it */
3247 /* Increase open count */
3248 ShareAccess
->OpenCount
++;
3250 /* Update shared access */
3251 ShareAccess
->Readers
+= ReadAccess
;
3252 ShareAccess
->Writers
+= WriteAccess
;
3253 ShareAccess
->Deleters
+= DeleteAccess
;
3254 ShareAccess
->SharedRead
+= SharedRead
;
3255 ShareAccess
->SharedWrite
+= SharedWrite
;
3256 ShareAccess
->SharedDelete
+= SharedDelete
;
3260 /* Validation successful */
3261 return STATUS_SUCCESS
;
3269 IoRemoveShareAccess(IN PFILE_OBJECT FileObject
,
3270 IN PSHARE_ACCESS ShareAccess
)
3274 /* Check if the file has an extension */
3275 if (FileObject
->Flags
& FO_FILE_OBJECT_HAS_EXTENSION
)
3277 /* Check if caller specified to ignore access checks */
3278 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3280 /* Don't update share access */
3285 /* Otherwise, check if there's any access present */
3286 if ((FileObject
->ReadAccess
) ||
3287 (FileObject
->WriteAccess
) ||
3288 (FileObject
->DeleteAccess
))
3290 /* Decrement the open count */
3291 ShareAccess
->OpenCount
--;
3293 /* Remove share access */
3294 ShareAccess
->Readers
-= FileObject
->ReadAccess
;
3295 ShareAccess
->Writers
-= FileObject
->WriteAccess
;
3296 ShareAccess
->Deleters
-= FileObject
->DeleteAccess
;
3297 ShareAccess
->SharedRead
-= FileObject
->SharedRead
;
3298 ShareAccess
->SharedWrite
-= FileObject
->SharedWrite
;
3299 ShareAccess
->SharedDelete
-= FileObject
->SharedDelete
;
3308 IoSetShareAccess(IN ACCESS_MASK DesiredAccess
,
3309 IN ULONG DesiredShareAccess
,
3310 IN PFILE_OBJECT FileObject
,
3311 OUT PSHARE_ACCESS ShareAccess
)
3314 BOOLEAN WriteAccess
;
3315 BOOLEAN DeleteAccess
;
3317 BOOLEAN SharedWrite
;
3318 BOOLEAN SharedDelete
;
3319 BOOLEAN Update
= TRUE
;
3322 ReadAccess
= (DesiredAccess
& (FILE_READ_DATA
| FILE_EXECUTE
)) != 0;
3323 WriteAccess
= (DesiredAccess
& (FILE_WRITE_DATA
| FILE_APPEND_DATA
)) != 0;
3324 DeleteAccess
= (DesiredAccess
& DELETE
) != 0;
3326 /* Check if the file has an extension */
3327 if (FileObject
->Flags
& FO_FILE_OBJECT_HAS_EXTENSION
)
3329 /* Check if caller specified to ignore access checks */
3330 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3332 /* Don't update share access */
3337 /* Update basic access */
3338 FileObject
->ReadAccess
= ReadAccess
;
3339 FileObject
->WriteAccess
= WriteAccess
;
3340 FileObject
->DeleteAccess
= DeleteAccess
;
3342 /* Check if we have no access as all */
3343 if (!(ReadAccess
) && !(WriteAccess
) && !(DeleteAccess
))
3345 /* Check if we need to update the structure */
3346 if (!Update
) return;
3348 /* Otherwise, clear data */
3349 ShareAccess
->OpenCount
= 0;
3350 ShareAccess
->Readers
= 0;
3351 ShareAccess
->Writers
= 0;
3352 ShareAccess
->Deleters
= 0;
3353 ShareAccess
->SharedRead
= 0;
3354 ShareAccess
->SharedWrite
= 0;
3355 ShareAccess
->SharedDelete
= 0;
3359 /* Calculate shared access */
3360 SharedRead
= (DesiredShareAccess
& FILE_SHARE_READ
) != 0;
3361 SharedWrite
= (DesiredShareAccess
& FILE_SHARE_WRITE
) != 0;
3362 SharedDelete
= (DesiredShareAccess
& FILE_SHARE_DELETE
) != 0;
3364 /* Set it in the FO */
3365 FileObject
->SharedRead
= SharedRead
;
3366 FileObject
->SharedWrite
= SharedWrite
;
3367 FileObject
->SharedDelete
= SharedDelete
;
3369 /* Check if we need to update the structure */
3370 if (!Update
) return;
3372 /* Otherwise, set data */
3373 ShareAccess
->OpenCount
= 1;
3374 ShareAccess
->Readers
= ReadAccess
;
3375 ShareAccess
->Writers
= WriteAccess
;
3376 ShareAccess
->Deleters
= DeleteAccess
;
3377 ShareAccess
->SharedRead
= SharedRead
;
3378 ShareAccess
->SharedWrite
= SharedWrite
;
3379 ShareAccess
->SharedDelete
= SharedDelete
;
3388 IoCancelFileOpen(IN PDEVICE_OBJECT DeviceObject
,
3389 IN PFILE_OBJECT FileObject
)
3395 PIO_STACK_LOCATION Stack
;
3397 /* Check if handles were already created for the
3398 * open file. If so, that's over.
3400 if (FileObject
->Flags
& FO_HANDLE_CREATED
)
3401 KeBugCheckEx(INVALID_CANCEL_OF_FILE_OPEN
,
3402 (ULONG_PTR
)FileObject
,
3403 (ULONG_PTR
)DeviceObject
, 0, 0);
3405 /* Reset the events */
3406 KeInitializeEvent(&Event
, SynchronizationEvent
, FALSE
);
3407 KeClearEvent(&FileObject
->Event
);
3409 /* Allocate the IRP we'll use */
3410 Irp
= IopAllocateIrpMustSucceed(DeviceObject
->StackSize
);
3411 /* Properly set it */
3412 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
3413 Irp
->UserEvent
= &Event
;
3414 Irp
->UserIosb
= &Irp
->IoStatus
;
3415 Irp
->Overlay
.AsynchronousParameters
.UserApcRoutine
= NULL
;
3416 Irp
->Tail
.Overlay
.OriginalFileObject
= FileObject
;
3417 Irp
->RequestorMode
= KernelMode
;
3418 Irp
->Flags
= IRP_CLOSE_OPERATION
| IRP_SYNCHRONOUS_API
;
3420 Stack
= IoGetNextIrpStackLocation(Irp
);
3421 Stack
->MajorFunction
= IRP_MJ_CLEANUP
;
3422 Stack
->FileObject
= FileObject
;
3424 /* Put on top of IRPs list of the thread */
3425 IopQueueIrpToThread(Irp
);
3427 /* Call the driver */
3428 Status
= IoCallDriver(DeviceObject
, Irp
);
3429 if (Status
== STATUS_PENDING
)
3431 KeWaitForSingleObject(&Event
, UserRequest
,
3432 KernelMode
, FALSE
, NULL
);
3435 /* Remove from IRPs list */
3436 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
3437 IopUnQueueIrpFromThread(Irp
);
3438 KeLowerIrql(OldIrql
);
3443 /* Clear the event */
3444 KeClearEvent(&FileObject
->Event
);
3445 /* And finally, mark the open operation as canceled */
3446 FileObject
->Flags
|= FO_FILE_OPEN_CANCELLED
;
3454 IoQueryFileDosDeviceName(IN PFILE_OBJECT FileObject
,
3455 OUT POBJECT_NAME_INFORMATION
*ObjectNameInformation
)
3458 return STATUS_NOT_IMPLEMENTED
;
3466 IoSetFileOrigin(IN PFILE_OBJECT FileObject
,
3469 NTSTATUS Status
= STATUS_SUCCESS
;
3472 /* Get the flag status */
3473 FlagSet
= FileObject
->Flags
& FO_REMOTE_ORIGIN
? TRUE
: FALSE
;
3475 /* Don't set the flag if it was set already, and don't remove it if it wasn't set */
3476 if (Remote
&& !FlagSet
)
3479 FileObject
->Flags
|= FO_REMOTE_ORIGIN
;
3481 else if (!Remote
&& FlagSet
)
3483 /* Remove the flag */
3484 FileObject
->Flags
&= ~FO_REMOTE_ORIGIN
;
3489 Status
= STATUS_INVALID_PARAMETER_MIX
;
3501 NtCreateFile(PHANDLE FileHandle
,
3502 ACCESS_MASK DesiredAccess
,
3503 POBJECT_ATTRIBUTES ObjectAttributes
,
3504 PIO_STATUS_BLOCK IoStatusBlock
,
3505 PLARGE_INTEGER AllocateSize
,
3506 ULONG FileAttributes
,
3508 ULONG CreateDisposition
,
3509 ULONG CreateOptions
,
3513 /* Call the I/O Function */
3514 return IoCreateFile(FileHandle
,
3532 NtCreateMailslotFile(OUT PHANDLE FileHandle
,
3533 IN ACCESS_MASK DesiredAccess
,
3534 IN POBJECT_ATTRIBUTES ObjectAttributes
,
3535 OUT PIO_STATUS_BLOCK IoStatusBlock
,
3536 IN ULONG CreateOptions
,
3537 IN ULONG MailslotQuota
,
3538 IN ULONG MaxMessageSize
,
3539 IN PLARGE_INTEGER TimeOut
)
3541 MAILSLOT_CREATE_PARAMETERS Buffer
;
3544 /* Check for Timeout */
3547 /* check if the call came from user mode */
3548 if (KeGetPreviousMode() != KernelMode
)
3550 /* Enter SEH for Probe */
3553 /* Probe the timeout */
3554 Buffer
.ReadTimeout
= ProbeForReadLargeInteger(TimeOut
);
3556 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3558 /* Return the exception code */
3559 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3565 /* Otherwise, capture directly */
3566 Buffer
.ReadTimeout
= *TimeOut
;
3569 /* Set the correct setting */
3570 Buffer
.TimeoutSpecified
= TRUE
;
3574 /* Tell the FSD we don't have a timeout */
3575 Buffer
.TimeoutSpecified
= FALSE
;
3579 Buffer
.MailslotQuota
= MailslotQuota
;
3580 Buffer
.MaximumMessageSize
= MaxMessageSize
;
3583 return IoCreateFile(FileHandle
,
3589 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
3594 CreateFileTypeMailslot
,
3601 NtCreateNamedPipeFile(OUT PHANDLE FileHandle
,
3602 IN ACCESS_MASK DesiredAccess
,
3603 IN POBJECT_ATTRIBUTES ObjectAttributes
,
3604 OUT PIO_STATUS_BLOCK IoStatusBlock
,
3605 IN ULONG ShareAccess
,
3606 IN ULONG CreateDisposition
,
3607 IN ULONG CreateOptions
,
3608 IN ULONG NamedPipeType
,
3610 IN ULONG CompletionMode
,
3611 IN ULONG MaximumInstances
,
3612 IN ULONG InboundQuota
,
3613 IN ULONG OutboundQuota
,
3614 IN PLARGE_INTEGER DefaultTimeout
)
3616 NAMED_PIPE_CREATE_PARAMETERS Buffer
;
3619 /* Check for Timeout */
3622 /* check if the call came from user mode */
3623 if (KeGetPreviousMode() != KernelMode
)
3625 /* Enter SEH for Probe */
3628 /* Probe the timeout */
3629 Buffer
.DefaultTimeout
=
3630 ProbeForReadLargeInteger(DefaultTimeout
);
3632 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3634 /* Return the exception code */
3635 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3641 /* Otherwise, capture directly */
3642 Buffer
.DefaultTimeout
= *DefaultTimeout
;
3645 /* Set the correct setting */
3646 Buffer
.TimeoutSpecified
= TRUE
;
3650 /* Tell the FSD we don't have a timeout */
3651 Buffer
.TimeoutSpecified
= FALSE
;
3655 Buffer
.NamedPipeType
= NamedPipeType
;
3656 Buffer
.ReadMode
= ReadMode
;
3657 Buffer
.CompletionMode
= CompletionMode
;
3658 Buffer
.MaximumInstances
= MaximumInstances
;
3659 Buffer
.InboundQuota
= InboundQuota
;
3660 Buffer
.OutboundQuota
= OutboundQuota
;
3663 return IoCreateFile(FileHandle
,
3674 CreateFileTypeNamedPipe
,
3681 NtFlushWriteBuffer(VOID
)
3685 /* Call the kernel */
3686 KeFlushWriteBuffer();
3687 return STATUS_SUCCESS
;
3695 NtOpenFile(OUT PHANDLE FileHandle
,
3696 IN ACCESS_MASK DesiredAccess
,
3697 IN POBJECT_ATTRIBUTES ObjectAttributes
,
3698 OUT PIO_STATUS_BLOCK IoStatusBlock
,
3699 IN ULONG ShareAccess
,
3700 IN ULONG OpenOptions
)
3702 /* Call the I/O Function */
3703 return IoCreateFile(FileHandle
,
3721 NtQueryAttributesFile(IN POBJECT_ATTRIBUTES ObjectAttributes
,
3722 OUT PFILE_BASIC_INFORMATION FileInformation
)
3724 /* Call the internal helper API */
3725 return IopQueryAttributesFile(ObjectAttributes
,
3726 FileBasicInformation
,
3727 sizeof(FILE_BASIC_INFORMATION
),
3733 NtQueryFullAttributesFile(IN POBJECT_ATTRIBUTES ObjectAttributes
,
3734 OUT PFILE_NETWORK_OPEN_INFORMATION FileInformation
)
3736 /* Call the internal helper API */
3737 return IopQueryAttributesFile(ObjectAttributes
,
3738 FileNetworkOpenInformation
,
3739 sizeof(FILE_NETWORK_OPEN_INFORMATION
),
3744 * @name NtCancelIoFile
3746 * Cancel all pending I/O operations in the current thread for specified
3750 * Handle to file object to cancel requests for. No specific
3751 * access rights are needed.
3752 * @param IoStatusBlock
3753 * Pointer to status block which is filled with final completition
3754 * status on successful return.
3762 NtCancelIoFile(IN HANDLE FileHandle
,
3763 OUT PIO_STATUS_BLOCK IoStatusBlock
)
3765 PFILE_OBJECT FileObject
;
3769 BOOLEAN OurIrpsInList
= FALSE
;
3770 LARGE_INTEGER Interval
;
3771 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
3773 PLIST_ENTRY ListHead
, NextEntry
;
3775 IOTRACE(IO_API_DEBUG
, "FileHandle: %p\n", FileHandle
);
3777 /* Check the previous mode */
3778 if (PreviousMode
!= KernelMode
)
3780 /* Enter SEH for probing */
3783 /* Probe the I/O Status Block */
3784 ProbeForWriteIoStatusBlock(IoStatusBlock
);
3786 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3788 /* Return the exception code */
3789 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3794 /* Reference the file object */
3795 Status
= ObReferenceObjectByHandle(FileHandle
,
3799 (PVOID
*)&FileObject
,
3801 if (!NT_SUCCESS(Status
)) return Status
;
3803 /* IRP cancellations are synchronized at APC_LEVEL. */
3804 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
3806 /* Get the current thread */
3807 Thread
= PsGetCurrentThread();
3809 /* Update the operation counts */
3810 IopUpdateOperationCount(IopOtherTransfer
);
3813 ListHead
= &Thread
->IrpList
;
3814 NextEntry
= ListHead
->Flink
;
3815 while (ListHead
!= NextEntry
)
3817 /* Get the IRP and check if the File Object matches */
3818 Irp
= CONTAINING_RECORD(NextEntry
, IRP
, ThreadListEntry
);
3819 if (Irp
->Tail
.Overlay
.OriginalFileObject
== FileObject
)
3821 /* Cancel this IRP and keep looping */
3823 OurIrpsInList
= TRUE
;
3826 /* Go to the next entry */
3827 NextEntry
= NextEntry
->Flink
;
3830 /* Lower the IRQL */
3831 KeLowerIrql(OldIrql
);
3833 /* Check if we had found an IRP */
3836 /* Setup a 10ms wait */
3837 Interval
.QuadPart
= -100000;
3840 while (OurIrpsInList
)
3843 KeDelayExecutionThread(KernelMode
, FALSE
, &Interval
);
3844 OurIrpsInList
= FALSE
;
3847 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
3849 /* Now loop the list again */
3850 NextEntry
= ListHead
->Flink
;
3851 while (NextEntry
!= ListHead
)
3853 /* Get the IRP and check if the File Object matches */
3854 Irp
= CONTAINING_RECORD(NextEntry
, IRP
, ThreadListEntry
);
3855 if (Irp
->Tail
.Overlay
.OriginalFileObject
== FileObject
)
3858 OurIrpsInList
= TRUE
;
3862 /* Go to the next entry */
3863 NextEntry
= NextEntry
->Flink
;
3866 /* Lower the IRQL */
3867 KeLowerIrql(OldIrql
);
3871 /* Enter SEH for writing back the I/O Status */
3875 IoStatusBlock
->Status
= STATUS_SUCCESS
;
3876 IoStatusBlock
->Information
= 0;
3878 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3880 /* Ignore exception */
3884 /* Dereference the file object and return success */
3885 ObDereferenceObject(FileObject
);
3886 return STATUS_SUCCESS
;
3894 NtDeleteFile(IN POBJECT_ATTRIBUTES ObjectAttributes
)
3897 DUMMY_FILE_OBJECT LocalFileObject
;
3899 KPROCESSOR_MODE AccessMode
= KeGetPreviousMode();
3900 OPEN_PACKET OpenPacket
;
3902 IOTRACE(IO_API_DEBUG
, "FileMame: %wZ\n", ObjectAttributes
->ObjectName
);
3904 /* Setup the Open Packet */
3905 RtlZeroMemory(&OpenPacket
, sizeof(OPEN_PACKET
));
3906 OpenPacket
.Type
= IO_TYPE_OPEN_PACKET
;
3907 OpenPacket
.Size
= sizeof(OPEN_PACKET
);
3908 OpenPacket
.CreateOptions
= FILE_DELETE_ON_CLOSE
;
3909 OpenPacket
.ShareAccess
= FILE_SHARE_READ
|
3912 OpenPacket
.Disposition
= FILE_OPEN
;
3913 OpenPacket
.DeleteOnly
= TRUE
;
3914 OpenPacket
.LocalFileObject
= &LocalFileObject
;
3916 /* Update the operation counts */
3917 IopUpdateOperationCount(IopOtherTransfer
);
3920 * Attempt opening the file. This will call the I/O Parse Routine for
3921 * the File Object (IopParseDevice) which will use the dummy file obejct
3922 * send the IRP to its device object. Note that we have two statuses
3923 * to worry about: the Object Manager's status (in Status) and the I/O
3924 * status, which is in the Open Packet's Final Status, and determined
3925 * by the Parse Check member.
3927 Status
= ObOpenObjectByName(ObjectAttributes
,
3934 if (OpenPacket
.ParseCheck
== FALSE
) return Status
;
3936 /* Retrn the Io status */
3937 return OpenPacket
.FinalStatus
;