NTSTATUS DriverEntry(PDRIVER_OBJECT driver, PUNICODE_STRING str) { UNREFERENCED_PARAMETER(driver); UNREFERENCED_PARAMETER(str); dri = driver; driver->DriverUnload = unload; for (int i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) { driver->MajorFunction[i] = dispatch; } PFILE_OBJECT file; UNICODE_STRING tcpname; UNICODE_STRING udpname; UNICODE_STRING ipname; RtlInitUnicodeString(&tcpname, TCP); RtlInitUnicodeString(&udpname, UDP); RtlInitUnicodeString(&ipname, IP); IoGetDeviceObjectPointer(&udpname, FILE_ALL_ACCESS, &file, &udpreal); ObfDereferenceObject(file); IoGetDeviceObjectPointer(&tcpname, FILE_ALL_ACCESS, &file, &tcpreal); ObfDereferenceObject(file); IoGetDeviceObjectPointer(&ipname, FILE_ALL_ACCESS, &file, &ipreal); ObfDereferenceObject(file); attach(&tcpname, DEVTYPE_TCP); attach(&udpname, DEVTYPE_UDP); attach(&ipname, DEVTYPE_IP); return STATUS_SUCCESS; }
static void setfilter(PacketFilterExtensionPtr fn) { UNICODE_STRING name; PDEVICE_OBJECT device=NULL; PFILE_OBJECT file=NULL; NTSTATUS status; RtlInitUnicodeString(&name, DD_IPFLTRDRVR_DEVICE_NAME); status=IoGetDeviceObjectPointer(&name, STANDARD_RIGHTS_ALL, &file, &device); if(NT_SUCCESS(status)) { KEVENT event; IO_STATUS_BLOCK iostatus; PF_SET_EXTENSION_HOOK_INFO hookinfo; PIRP irp; hookinfo.ExtensionPointer=fn; KeInitializeEvent(&event, NotificationEvent, FALSE); irp=IoBuildDeviceIoControlRequest( IOCTL_PF_SET_EXTENSION_POINTER, device, &hookinfo, sizeof(PF_SET_EXTENSION_HOOK_INFO), NULL, 0, FALSE, &event, &iostatus); if(irp && IoCallDriver(device, irp)==STATUS_PENDING) KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL); if(file) ObDereferenceObject(file); } }
/* * @implemented */ VOID RegisterForTargetDeviceNotification(IN PDEVICE_EXTENSION DeviceExtension, IN PDEVICE_INFORMATION DeviceInformation) { NTSTATUS Status; PFILE_OBJECT FileObject; PDEVICE_OBJECT DeviceObject; /* Get device object */ Status = IoGetDeviceObjectPointer(&(DeviceInformation->DeviceName), FILE_READ_ATTRIBUTES, &FileObject, &DeviceObject); if (!NT_SUCCESS(Status)) { return; } /* And simply register for notifications */ Status = IoRegisterPlugPlayNotification(EventCategoryTargetDeviceChange, 0, FileObject, DeviceExtension->DriverObject, MountMgrTargetDeviceNotification, DeviceInformation, &(DeviceInformation->TargetDeviceNotificationEntry)); if (!NT_SUCCESS(Status)) { DeviceInformation->TargetDeviceNotificationEntry = NULL; } ObDereferenceObject(FileObject); return; }
NTSTATUS vol_close(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { volume_device_extension* vde = DeviceObject->DeviceExtension; pdo_device_extension* pdode = vde->pdode; TRACE("(%p, %p)\n", DeviceObject, Irp); Irp->IoStatus.Information = 0; ExAcquireResourceExclusiveLite(&pdo_list_lock, TRUE); ExAcquireResourceSharedLite(&pdode->child_lock, TRUE); if (InterlockedDecrement(&vde->open_count) == 0 && vde->removing) { NTSTATUS Status; UNICODE_STRING mmdevpath; PDEVICE_OBJECT mountmgr; PFILE_OBJECT mountmgrfo; PDEVICE_OBJECT pdo; RtlInitUnicodeString(&mmdevpath, MOUNTMGR_DEVICE_NAME); Status = IoGetDeviceObjectPointer(&mmdevpath, FILE_READ_ATTRIBUTES, &mountmgrfo, &mountmgr); if (!NT_SUCCESS(Status)) ERR("IoGetDeviceObjectPointer returned %08x\n", Status); else { remove_drive_letter(mountmgr, &vde->name); ObDereferenceObject(mountmgrfo); } if (vde->mounted_device) { device_extension* Vcb = vde->mounted_device->DeviceExtension; Vcb->vde = NULL; } if (vde->name.Buffer) ExFreePool(vde->name.Buffer); ExReleaseResourceLite(&pdode->child_lock); ExDeleteResourceLite(&pdode->child_lock); if (vde->pdo->AttachedDevice) IoDetachDevice(vde->pdo); pdo = vde->pdo; IoDeleteDevice(vde->device); if (!no_pnp) IoDeleteDevice(pdo); } else ExReleaseResourceLite(&pdode->child_lock); ExReleaseResourceLite(&pdo_list_lock); return STATUS_SUCCESS; }
////////////////////////////////////////////////////////////////////////// // // // added by hootch 01172004 NTSTATUS NDCtrlOpenLanScsiBus( OUT PDEVICE_OBJECT *LanScsiDev, OUT PFILE_OBJECT *FileObject ) { NTSTATUS ntStatus; PWSTR symbolicLinkList; UNICODE_STRING objectName; PFILE_OBJECT fileObject; PDEVICE_OBJECT deviceObject; SPY_LOG_PRINT( LFS_DEBUG_LFS_INFO, ( "[LFS] NDCtrlOpenLanScsiBus: entered.\n")); ASSERT(LanScsiDev); ASSERT(KeGetCurrentIrql() <= PASSIVE_LEVEL); ntStatus = IoGetDeviceInterfaces( &GUID_LANSCSI_BUS_ENUMERATOR_INTERFACE_CLASS, NULL, 0, &symbolicLinkList ); if(!NT_SUCCESS(ntStatus)) { SPY_LOG_PRINT( LFS_DEBUG_LFS_INFO, ( "[LFS] NDCtrlOpenLanScsiBus: IoGetDeviceInterfaces ntStatus = 0x%x\n", ntStatus)); return ntStatus; } ASSERT(symbolicLinkList != NULL); SPY_LOG_PRINT( LFS_DEBUG_LFS_INFO, ( "[LFS] NDCtrlOpenLanScsiBus: symbolicLinkList = %ws\n", symbolicLinkList)); RtlInitUnicodeString(&objectName, symbolicLinkList); ntStatus = IoGetDeviceObjectPointer( &objectName, FILE_ALL_ACCESS, &fileObject, &deviceObject ); if(!NT_SUCCESS(ntStatus)) { SPY_LOG_PRINT( LFS_DEBUG_LFS_INFO, ( "[LFS] NDCtrlOpenLanScsiBus: ntStatus = 0x%x\n", ntStatus)); ExFreePool(symbolicLinkList); return ntStatus; } ExFreePool(symbolicLinkList); *LanScsiDev = deviceObject; *FileObject = fileObject; SPY_LOG_PRINT( LFS_DEBUG_LFS_INFO, ( "NDCtrlOpenLanScsiBus: Done.\n")); return ntStatus; }
NTSTATUS DokanSendIoContlToMountManager(__in ULONG IoControlCode, __in PVOID InputBuffer, __in ULONG Length, __out PVOID OutputBuffer, __in ULONG OutputLength) { NTSTATUS status; UNICODE_STRING mountManagerName; PFILE_OBJECT mountFileObject; PDEVICE_OBJECT mountDeviceObject; PIRP irp; KEVENT driverEvent; IO_STATUS_BLOCK iosb; DDbgPrint("=> DokanSendIoContlToMountManager\n"); RtlInitUnicodeString(&mountManagerName, MOUNTMGR_DEVICE_NAME); status = IoGetDeviceObjectPointer(&mountManagerName, FILE_READ_ATTRIBUTES, &mountFileObject, &mountDeviceObject); if (!NT_SUCCESS(status)) { DDbgPrint(" IoGetDeviceObjectPointer failed: 0x%x\n", status); return status; } KeInitializeEvent(&driverEvent, NotificationEvent, FALSE); irp = IoBuildDeviceIoControlRequest(IoControlCode, mountDeviceObject, InputBuffer, Length, OutputBuffer, OutputLength, FALSE, &driverEvent, &iosb); if (irp == NULL) { DDbgPrint(" IoBuildDeviceIoControlRequest failed\n"); return STATUS_INSUFFICIENT_RESOURCES; } status = IoCallDriver(mountDeviceObject, irp); if (status == STATUS_PENDING) { KeWaitForSingleObject(&driverEvent, Executive, KernelMode, FALSE, NULL); } status = iosb.Status; ObDereferenceObject(mountFileObject); // Don't dereference mountDeviceObject, mountFileObject is enough if (NT_SUCCESS(status)) { DDbgPrint(" IoCallDriver success\n"); } else { DDbgPrint(" IoCallDriver failed: 0x%x\n", status); } DDbgPrint("<= DokanSendIoContlToMountManager\n"); return status; }
NTSTATUS ImScsiGetAdapterDeviceObject() { NTSTATUS status = STATUS_OBJECT_NAME_NOT_FOUND; int i; UNICODE_STRING objname = { 0 }; PFILE_OBJECT file_object = NULL; PDEVICE_OBJECT device_object = NULL; WCHAR objstr[] = L"\\Device\\Scsi\\PhDskMnt00"; if (pMPDrvInfoGlobal->DeviceObject != NULL) return STATUS_SUCCESS; for (i = 0; i < 100; i++) { LARGE_INTEGER wait_time; if ((i & 7) == 7) { wait_time.QuadPart = -1; KeDelayExecutionThread(KernelMode, FALSE, &wait_time); } _snwprintf(objstr, sizeof(objstr)/sizeof(*objstr), L"\\Device\\Scsi\\PhDskMnt%i", i); RtlInitUnicodeString(&objname, objstr); KdPrint2(("PhDskMnt::ImScsiGetAdapterDeviceObject: Attempt to open %ws...\n", objstr)); status = IoGetDeviceObjectPointer(&objname, GENERIC_ALL, &file_object, &device_object); if (!NT_SUCCESS(status)) { KdPrint2(("PhDskMnt::ImScsiGetAdapterDeviceObject: Attempt to open %ws failed: status=0x%x\n", objstr, status)); continue; } if (device_object->DriverObject != pMPDrvInfoGlobal->pDriverObj) { KdPrint2(("PhDskMnt::ImScsiGetAdapterDeviceObject: %ws was not our device.\n", objstr, status)); continue; } pMPDrvInfoGlobal->DeviceObject = device_object; return STATUS_SUCCESS; } if (NT_SUCCESS(status)) KdPrint(("PhDskMnt::ImScsiGetAdapterDeviceObject: Successfully opened %ws.\n", objstr)); else DbgPrint(("PhDskMnt::ImScsiGetAdapterDeviceObject: Could not locate SCSI adapter device object by name.\n")); return status; }
static void setfilter(PacketFilterExtensionPtr fn) { UNICODE_STRING name; PDEVICE_OBJECT device=NULL; PFILE_OBJECT file=NULL; NTSTATUS status; DbgPrint("pbfilter: > Entering setfilter()\n"); RtlInitUnicodeString(&name, DD_IPFLTRDRVR_DEVICE_NAME); status=IoGetDeviceObjectPointer(&name, STANDARD_RIGHTS_ALL, &file, &device); if(NT_SUCCESS(status)) { KEVENT event; IO_STATUS_BLOCK iostatus; PF_SET_EXTENSION_HOOK_INFO hookinfo; PIRP irp; DbgPrint("pbfilter: got devobj\n"); hookinfo.ExtensionPointer=fn; KeInitializeEvent(&event, NotificationEvent, FALSE); irp=IoBuildDeviceIoControlRequest( IOCTL_PF_SET_EXTENSION_POINTER, device, &hookinfo, sizeof(PF_SET_EXTENSION_HOOK_INFO), NULL, 0, FALSE, &event, &iostatus); DbgPrint("pbfilter: calling into driver\n"); if(irp && IoCallDriver(device, irp)==STATUS_PENDING) { DbgPrint("pbfilter: waiting for IRP to complete\n"); KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL); } else { DbgPrint("pbfilter: IRP not pending (or no IRP?)\n"); } if(file) { DbgPrint("pbfilter: Dereferencing file\n"); ObDereferenceObject(file); } else { DbgPrint("pbfilter: no file to dereference\n"); } } else { DbgPrint("pbfilter: * ERROR: unable to get IpFltDrv DevObj, status:[0x%lX]\n", status); } DbgPrint("pbfilter: < Leaving setfilter()\n"); }
NTSTATUS DriverEntry( __in PDRIVER_OBJECT DriverObject, __in PUNICODE_STRING RegistryPath ) { UNICODE_STRING CfixkrName = RTL_CONSTANT_STRING( CFIXKR_DEVICE_NT_NAME ); PFILE_OBJECT File; PDEVICE_OBJECT CfixkrObject; NTSTATUS Status; UNREFERENCED_PARAMETER( RegistryPath ); KdPrint( ( "CFIXDRV: DriverEntry of test driver\n" ) ); // // Install dispatch routines. // DriverObject->MajorFunction[ IRP_MJ_CREATE ] = CfixkDrvNotImplemented; DriverObject->MajorFunction[ IRP_MJ_CLOSE ] = CfixkDrvNotImplemented; DriverObject->DriverUnload = CfixkDrvUnload; // // Lookup cfixkr and obtain interface. // Status = IoGetDeviceObjectPointer( &CfixkrName, FILE_WRITE_DATA, &File, &CfixkrObject ); if ( ! NT_SUCCESS( Status ) ) { KdPrint( ( "CFIX: Failed to obtain pointer to cfixkr device\n" ) ); return Status; } Status = CfixkDrvQueryReporter( CfixkrObject ); if ( NT_SUCCESS( Status ) ) { // // Keep a reference to the device to lock the driver in // memory until we have released the interface. // ObReferenceObject( CfixkrObject ); CfixkDrvCfixkrDevice = CfixkrObject; } // // We have obtained the interface, which is referenced. We can thus // release File while having locked the DO through the interface. // ObDereferenceObject( File ); return Status; }
/* * @implemented */ VOID SendOnlineNotification(IN PUNICODE_STRING SymbolicName) { PIRP Irp; KEVENT Event; NTSTATUS Status; PFILE_OBJECT FileObject; PIO_STACK_LOCATION Stack; PDEVICE_OBJECT DeviceObject; IO_STATUS_BLOCK IoStatusBlock; /* Get device object */ Status = IoGetDeviceObjectPointer(SymbolicName, FILE_READ_ATTRIBUTES, &FileObject, &DeviceObject); if (!NT_SUCCESS(Status)) { return; } /* And attached device object */ DeviceObject = IoGetAttachedDeviceReference(FileObject->DeviceObject); /* And send VOLUME_ONLINE */ KeInitializeEvent(&Event, NotificationEvent, FALSE); Irp = IoBuildDeviceIoControlRequest(IOCTL_VOLUME_ONLINE, DeviceObject, NULL, 0, NULL, 0, FALSE, &Event, &IoStatusBlock); if (!Irp) { goto Cleanup; } Stack = IoGetNextIrpStackLocation(Irp); Stack->FileObject = FileObject; Status = IoCallDriver(DeviceObject, Irp); if (Status == STATUS_PENDING) { KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL); } Cleanup: ObDereferenceObject(DeviceObject); ObDereferenceObject(FileObject); return; }
/* Guest Device Communication API */ NTSTATUS VBoxGdcInit() { UNICODE_STRING UniName; RtlInitUnicodeString(&UniName, VBOXGUEST_DEVICE_NAME_NT); NTSTATUS Status = IoGetDeviceObjectPointer(&UniName, FILE_ALL_ACCESS, &g_ctx.Gdc.pFo, &g_ctx.Gdc.pDo); if (!NT_SUCCESS(Status)) { WARN(("IoGetDeviceObjectPointer failed Status(0x%x)", Status)); memset(&g_ctx.Gdc, 0, sizeof (g_ctx.Gdc)); } return Status; }
/* ssh_virtual_adapter_device_add_ref() * * Increments the reference count of underlying virtual NIC's device object * thus ensuring that the virtual NIC can't be unloaded from memory. * * This function must be run on IRQL PASSIVE_LEVEL. * */ static Boolean ssh_virtual_adapter_device_add_ref(SshVirtualAdapter va) { Boolean status = TRUE; #ifndef _WIN32_WCE PDEVICE_OBJECT device_object = NULL; UNICODE_STRING device_name; #endif /* _WIN32_WCE */ SSH_DEBUG(SSH_D_MIDSTART, ("ssh_virtual_adapter_device_add_ref()")); SSH_ASSERT(va != NULL); SSH_ASSERT(va->adapter != NULL); SSH_ASSERT(va->file_object == NULL); #ifndef _WIN32_WCE SSH_ASSERT(SSH_GET_IRQL() == SSH_PASSIVE_LEVEL); NdisInitUnicodeString(&device_name, NULL); if (ssh_adapter_device_object_name_get(va->adapter, &device_name)) { SSH_ASSERT(device_name.Buffer != NULL); SSH_ASSERT(device_name.Length > 0); if (!NT_SUCCESS(IoGetDeviceObjectPointer( &device_name, FILE_ALL_ACCESS, (PFILE_OBJECT *)&va->file_object, &device_object))) { SSH_DEBUG(SSH_D_FAIL, ("IoGetDeviceObjectPointer() FAILED!")); status = FALSE; } ssh_free(device_name.Buffer); } else { SSH_DEBUG(SSH_D_FAIL, ("ssh_device_object_name_get() FAILED!")); status = FALSE; } #else /* not _WIN32_WCE */ /* Just initialize with a bogus value... */ va->file_object = (void *)0x00BEEF00; #endif /* not _WIN32_WCE */ return (status); }
RT_C_DECLS_END # endif int vbglDriverOpen (VBGLDRIVER *pDriver) { # ifdef RT_OS_WINDOWS UNICODE_STRING uszDeviceName; RtlInitUnicodeString (&uszDeviceName, L"\\Device\\VBoxGuest"); PDEVICE_OBJECT pDeviceObject = NULL; PFILE_OBJECT pFileObject = NULL; NTSTATUS rc = IoGetDeviceObjectPointer (&uszDeviceName, FILE_ALL_ACCESS, &pFileObject, &pDeviceObject); if (NT_SUCCESS (rc)) { Log(("vbglDriverOpen VBoxGuest successful pDeviceObject=%x\n", pDeviceObject)); pDriver->pDeviceObject = pDeviceObject; pDriver->pFileObject = pFileObject; return VINF_SUCCESS; } /** @todo return RTErrConvertFromNtStatus(rc)! */ Log(("vbglDriverOpen VBoxGuest failed with ntstatus=%x\n", rc)); return rc; # elif defined (RT_OS_OS2) /* * Just check whether the connection was made or not. */ if ( g_VBoxGuestIDC.u32Version == VMMDEV_VERSION && VALID_PTR(g_VBoxGuestIDC.u32Session) && VALID_PTR(g_VBoxGuestIDC.pfnServiceEP)) { pDriver->u32Session = g_VBoxGuestIDC.u32Session; return VINF_SUCCESS; } pDriver->u32Session = UINT32_MAX; Log(("vbglDriverOpen: failed\n")); return VERR_FILE_NOT_FOUND; # else uint32_t u32VMMDevVersion; pDriver->pvOpaque = VBoxGuestIDCOpen (&u32VMMDevVersion); if ( pDriver->pvOpaque && u32VMMDevVersion == VMMDEV_VERSION) return VINF_SUCCESS; Log(("vbglDriverOpen: failed\n")); return VERR_FILE_NOT_FOUND; # endif }
/* get device object by its name */ NTSTATUS get_device_object(wchar_t *name, PDEVICE_OBJECT *devobj) { UNICODE_STRING str; NTSTATUS status; PFILE_OBJECT fileobj; RtlInitUnicodeString(&str, name); status = IoGetDeviceObjectPointer(&str, FILE_ALL_ACCESS, &fileobj, devobj); if (status == STATUS_SUCCESS) ObDereferenceObject(fileobj); return status; }
NTSTATUS FspGetDeviceObjectPointer(PUNICODE_STRING ObjectName, ACCESS_MASK DesiredAccess, PULONG PFileNameIndex, PFILE_OBJECT *PFileObject, PDEVICE_OBJECT *PDeviceObject) { PAGED_CODE(); UNICODE_STRING PartialName; OBJECT_ATTRIBUTES ObjectAttributes; HANDLE Handle; NTSTATUS Result; PartialName.Length = 0; PartialName.MaximumLength = ObjectName->Length; PartialName.Buffer = ObjectName->Buffer; Result = STATUS_NO_SUCH_DEVICE; while (PartialName.MaximumLength > PartialName.Length) { while (PartialName.MaximumLength > PartialName.Length && L'\\' == PartialName.Buffer[PartialName.Length / sizeof(WCHAR)]) PartialName.Length += sizeof(WCHAR); while (PartialName.MaximumLength > PartialName.Length && L'\\' != PartialName.Buffer[PartialName.Length / sizeof(WCHAR)]) PartialName.Length += sizeof(WCHAR); Result = IoGetDeviceObjectPointer(&PartialName, DesiredAccess, PFileObject, PDeviceObject); if (NT_SUCCESS(Result)) { *PFileNameIndex = PartialName.Length; break; } InitializeObjectAttributes(&ObjectAttributes, &PartialName, OBJ_KERNEL_HANDLE, 0, 0); Result = ZwOpenDirectoryObject(&Handle, 0, &ObjectAttributes); if (!NT_SUCCESS(Result)) { Result = ZwOpenSymbolicLinkObject(&Handle, 0, &ObjectAttributes); if (!NT_SUCCESS(Result)) { Result = STATUS_NO_SUCH_DEVICE; break; } } ZwClose(Handle); } return Result; }
// 打开一个端口设备 PDEVICE_OBJECT CFTOpenCom(ULONG aId, NTSTATUS *aStatus) { UNICODE_STRING nameString; static WCHAR name[32] = {0}; PFILE_OBJECT fileObject = NULL; PDEVICE_OBJECT deviceObject = NULL; // 输入字符串 RtlZeroMemory(name, sizeof(WCHAR)*32); RtlStringCchPrintfW(name, 32, L"\\Device\\Serial%d", aId); RtlInitUnicodeString(&nameString, name); // 打开设备对象 *aStatus = IoGetDeviceObjectPointer(&nameString, FILE_ALL_ACCESS, &fileObject, &deviceObject); if (*aStatus == STATUS_SUCCESS) ObDereferenceObject(fileObject); return deviceObject; }
PDEVICE_OBJECT OpenCom(ULONG id, NTSTATUS* status) { UNICODE_STRING name_str; static WCHAR name[32] = { 0 }; PFILE_OBJECT fileobj = NULL; PDEVICE_OBJECT devobj = NULL; memset(name, 0, sizeof(WCHAR)* 32); RtlStringCchPrintfW( name, 32, L"\\Device\\Serial%d", id); RtlInitUnicodeString(&name_str, name); *status = IoGetDeviceObjectPointer( &name_str, FILE_ALL_ACCESS, &fileobj, &devobj); if (*status == STATUS_SUCCESS) ObDereferenceObject(fileobj); return devobj; }
void testRoutine(_In_ PDEVICE_OBJECT pDeviceObject, _In_opt_ PVOID pContext){ UNREFERENCED_PARAMETER(pDeviceObject); UNREFERENCED_PARAMETER(pContext); PFILE_OBJECT pFileObj; PDEVICE_OBJECT pDevObj; NTSTATUS status = STATUS_UNSUCCESSFUL; if (!pContext){ DbgPrint("pcontext null"); return; } PMY_WORK_CONTEXT pWorkContext = (PMY_WORK_CONTEXT)pContext; status = IoGetDeviceObjectPointer(pWorkContext->pSymlink, 0, &pFileObj, &pDevObj); if (status){ DbgPrint("failed to access devobj!%lX", status); return; } DbgPrint("not failed to access devobj!%lX", status); ObfDereferenceObject(pFileObj); ObfDereferenceObject(pDevObj); //return; }
int VBOXCALL supR0IdcNativeOpen(PSUPDRVIDCHANDLE pHandle, PSUPDRVIDCREQCONNECT pReq) { PDEVICE_OBJECT pDeviceObject = NULL; PFILE_OBJECT pFileObject = NULL; UNICODE_STRING wszDeviceName; NTSTATUS rcNt; int rc; /* * Get the device object pointer. */ RtlInitUnicodeString(&wszDeviceName, DEVICE_NAME_NT); rcNt = IoGetDeviceObjectPointer(&wszDeviceName, FILE_ALL_ACCESS, &pFileObject, &pDeviceObject); if (NT_SUCCESS(rcNt)) { /* * Make the connection call. */ rc = supR0IdcNtCallInternal(pDeviceObject, pFileObject, SUPDRV_IDC_REQ_CONNECT, &pReq->Hdr); if (RT_SUCCESS(rc)) { pHandle->s.pDeviceObject = pDeviceObject; pHandle->s.pFileObject = pFileObject; return rc; } /* only the file object. */ ObDereferenceObject(pFileObject); } else rc = RTErrConvertFromNtStatus(rcNt); pHandle->s.pDeviceObject = NULL; pHandle->s.pFileObject = NULL; return rc; }
/* * @implemented */ NTSTATUS QuerySuggestedLinkName(IN PUNICODE_STRING SymbolicName, OUT PUNICODE_STRING SuggestedLinkName, OUT PBOOLEAN UseOnlyIfThereAreNoOtherLinks) { PIRP Irp; KEVENT Event; NTSTATUS Status; USHORT NameLength; PFILE_OBJECT FileObject; PDEVICE_OBJECT DeviceObject; IO_STATUS_BLOCK IoStatusBlock; PIO_STACK_LOCATION IoStackLocation; PMOUNTDEV_SUGGESTED_LINK_NAME IoCtlSuggested; /* First, get device */ Status = IoGetDeviceObjectPointer(SymbolicName, FILE_READ_ATTRIBUTES, &FileObject, &DeviceObject); if (!NT_SUCCESS(Status)) { return Status; } /* Then, get attached device */ DeviceObject = IoGetAttachedDeviceReference(FileObject->DeviceObject); /* Then, prepare buffer to query suggested name */ IoCtlSuggested = AllocatePool(sizeof(MOUNTDEV_SUGGESTED_LINK_NAME)); if (!IoCtlSuggested) { Status = STATUS_INSUFFICIENT_RESOURCES; goto Dereference; } /* Prepare request */ KeInitializeEvent(&Event, NotificationEvent, FALSE); Irp = IoBuildDeviceIoControlRequest(IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME, DeviceObject, NULL, 0, IoCtlSuggested, sizeof(MOUNTDEV_SUGGESTED_LINK_NAME), FALSE, &Event, &IoStatusBlock); if (!Irp) { Status = STATUS_INSUFFICIENT_RESOURCES; goto Release; } IoStackLocation = IoGetNextIrpStackLocation(Irp); IoStackLocation->FileObject = FileObject; /* And ask */ Status = IoCallDriver(DeviceObject, Irp); if (Status == STATUS_PENDING) { KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL); Status = IoStatusBlock.Status; } /* Overflow? Normal */ if (Status == STATUS_BUFFER_OVERFLOW) { /* Reallocate big enough buffer */ NameLength = IoCtlSuggested->NameLength + sizeof(MOUNTDEV_SUGGESTED_LINK_NAME); FreePool(IoCtlSuggested); IoCtlSuggested = AllocatePool(NameLength); if (!IoCtlSuggested) { Status = STATUS_INSUFFICIENT_RESOURCES; goto Dereference; } /* And reask */ KeInitializeEvent(&Event, NotificationEvent, FALSE); Irp = IoBuildDeviceIoControlRequest(IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME, DeviceObject, NULL, 0, IoCtlSuggested, NameLength, FALSE, &Event, &IoStatusBlock); if (!Irp) { Status = STATUS_INSUFFICIENT_RESOURCES; goto Release; } IoStackLocation = IoGetNextIrpStackLocation(Irp); IoStackLocation->FileObject = FileObject; Status = IoCallDriver(DeviceObject, Irp); if (Status == STATUS_PENDING) { KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL); Status = IoStatusBlock.Status; } } if (!NT_SUCCESS(Status)) { goto Release; } /* Now we have suggested name, copy it */ SuggestedLinkName->Length = IoCtlSuggested->NameLength; SuggestedLinkName->MaximumLength = IoCtlSuggested->NameLength + sizeof(UNICODE_NULL); SuggestedLinkName->Buffer = AllocatePool(IoCtlSuggested->NameLength + sizeof(UNICODE_NULL)); if (!SuggestedLinkName->Buffer) { Status = STATUS_INSUFFICIENT_RESOURCES; } else { RtlCopyMemory(SuggestedLinkName->Buffer, IoCtlSuggested->Name, IoCtlSuggested->NameLength); SuggestedLinkName->Buffer[SuggestedLinkName->Length / sizeof(WCHAR)] = UNICODE_NULL; } /* Also return its priority */ *UseOnlyIfThereAreNoOtherLinks = IoCtlSuggested->UseOnlyIfThereAreNoOtherLinks; Release: FreePool(IoCtlSuggested); Dereference: ObDereferenceObject(DeviceObject); ObDereferenceObject(FileObject); return Status; }
/* * @implemented */ VOID SendLinkDeleted(IN PUNICODE_STRING DeviceName, IN PUNICODE_STRING SymbolicName) { PIRP Irp; KEVENT Event; ULONG NameSize; NTSTATUS Status; PFILE_OBJECT FileObject; PIO_STACK_LOCATION Stack; PMOUNTDEV_NAME Name = NULL; PDEVICE_OBJECT DeviceObject; IO_STATUS_BLOCK IoStatusBlock; /* Get the device associated with the name */ Status = IoGetDeviceObjectPointer(DeviceName, FILE_READ_ATTRIBUTES, &FileObject, &DeviceObject); if (!NT_SUCCESS(Status)) { return; } /* Get attached device (will notify it) */ DeviceObject = IoGetAttachedDeviceReference(FileObject->DeviceObject); /* NameSize is the size of the whole MOUNTDEV_NAME struct */ NameSize = sizeof(USHORT) + SymbolicName->Length; Name = AllocatePool(NameSize); if (!Name) { goto Cleanup; } /* Initialize struct */ Name->NameLength = SymbolicName->Length; RtlCopyMemory(Name->Name, SymbolicName->Buffer, SymbolicName->Length); KeInitializeEvent(&Event, NotificationEvent, FALSE); /* Cf: SendLinkCreated comment */ Irp = IoBuildDeviceIoControlRequest(CTL_CODE(MOUNTDEVCONTROLTYPE, 5, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS), DeviceObject, Name, NameSize, NULL, 0, FALSE, &Event, &IoStatusBlock); /* This one can fail, no one matters */ if (Irp) { Stack = IoGetNextIrpStackLocation(Irp); Stack->FileObject = FileObject; Status = IoCallDriver(DeviceObject, Irp); if (Status == STATUS_PENDING) { KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL); } } /* Then, second one */ KeInitializeEvent(&Event, NotificationEvent, FALSE); Irp = IoBuildDeviceIoControlRequest(IOCTL_MOUNTDEV_LINK_DELETED, DeviceObject, Name, NameSize, NULL, 0, FALSE, &Event, &IoStatusBlock); if (!Irp) { goto Cleanup; } Stack = IoGetNextIrpStackLocation(Irp); Stack->FileObject = FileObject; /* Really notify */ Status = IoCallDriver(DeviceObject, Irp); if (Status == STATUS_PENDING) { KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL); } Cleanup: if (Name) { FreePool(Name); } ObDereferenceObject(DeviceObject); ObDereferenceObject(FileObject); return; }
NTSTATUS KBFAttachDevicesEx(IN PDRIVER_OBJECT aDriverObject, IN PUNICODE_STRING aRegistryPath) { UNREFERENCED_PARAMETER(aDriverObject); UNREFERENCED_PARAMETER(aRegistryPath); NTSTATUS status = STATUS_SUCCESS; // 遍历所有键盘设备 UNICODE_STRING nameString; static WCHAR name[32] = {0}; ULONG index = 0; PDEVICE_OBJECT deviceObject = NULL; PFILE_OBJECT fileObject = NULL; // 第一个设备 RtlZeroMemory(name, sizeof(WCHAR)*32); RtlStringCchPrintfW(name, 32, L"\\Device\\KeyboardClass%d", index); RtlInitUnicodeString(&nameString, name); // 打开设备对象 status = IoGetDeviceObjectPointer(&nameString, FILE_ALL_ACCESS, &fileObject, &deviceObject); if (NT_SUCCESS(status)) ObDereferenceObject(fileObject); while (deviceObject != NULL) { PDEVICE_OBJECT pFilterDeviceObject = NULL; PDEVICE_OBJECT pLowerDeviceObject = NULL; // 创建一个过滤设备 status = IoCreateDevice(aDriverObject, sizeof(DEVICE_EXTENSION), NULL, deviceObject->DeviceType, deviceObject->Characteristics, FALSE, &pFilterDeviceObject); if (!NT_SUCCESS(status)) { KdPrint(("wykbflt.sys : KBFAttachDevices Couldn't create the Filter Device Object %d\n", index)); break; } pLowerDeviceObject = IoAttachDeviceToDeviceStack(pFilterDeviceObject, deviceObject); if (!pLowerDeviceObject) { KdPrint(("wykbflt.sys : Couldn't attach to Device Object\n")); IoDeleteDevice(pFilterDeviceObject); pFilterDeviceObject = NULL; break; } // 设备扩展 PDEVICE_EXTENSION deviceExtension = (PDEVICE_EXTENSION)pFilterDeviceObject->DeviceExtension; KBFInitDeviceExtension(deviceExtension, pFilterDeviceObject, deviceObject, pLowerDeviceObject); // 设置过滤操作 pFilterDeviceObject->DeviceType = pLowerDeviceObject->DeviceType; // 要过滤的设备类型跟物理设备类型一致 pFilterDeviceObject->Characteristics = pLowerDeviceObject->Characteristics; pFilterDeviceObject->StackSize = pLowerDeviceObject->StackSize + 1; pFilterDeviceObject->Flags |= pLowerDeviceObject->Flags & (DO_BUFFERED_IO | DO_DIRECT_IO | DO_POWER_PAGABLE) ; ++index; RtlZeroMemory(name, sizeof(WCHAR)*32); RtlStringCchPrintfW(name, 32, L"\\Device\\KeyboardClass%d", index); RtlInitUnicodeString(&nameString, name); // 打开设备对象 status = IoGetDeviceObjectPointer(&nameString, FILE_ALL_ACCESS, &fileObject, &deviceObject); if (NT_SUCCESS(status)) ObDereferenceObject(fileObject); else break; } return STATUS_SUCCESS; }
NTSTATUS UDPFilter_Attach( IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath ) { NTSTATUS status = 0; UNICODE_STRING uniNtNameString; PTDIH_DeviceExtension pTDIH_DeviceExtension; PDEVICE_OBJECT pFilterDeviceObject = NULL; PDEVICE_OBJECT pTargetDeviceObject = NULL; PFILE_OBJECT pTargetFileObject = NULL; PDEVICE_OBJECT pLowerDeviceObject = NULL; DBGPRINT("UDPFilter_Attach.\n"); RtlInitUnicodeString( &uniNtNameString, DD_UDP_DEVICE_NAME ); status = IoGetDeviceObjectPointer( IN &uniNtNameString, IN FILE_READ_ATTRIBUTES, OUT &pTargetFileObject, OUT &pTargetDeviceObject ); if( !NT_SUCCESS(status) ) { DBGPRINT(("UDPFilter_Attach: Couldn't get the UDP Device Object\n")); pTargetFileObject = NULL; pTargetDeviceObject = NULL; return( status ); } RtlInitUnicodeString( &uniNtNameString, TDIH_UDP_DEVICE_NAME ); status = IoCreateDevice( IN DriverObject, IN sizeof( TDIH_DeviceExtension ), IN &uniNtNameString, IN pTargetDeviceObject->DeviceType, IN pTargetDeviceObject->Characteristics, IN FALSE, OUT &pFilterDeviceObject ); if( !NT_SUCCESS(status) ) { DBGPRINT(("UDPFilter_Attach: Couldn't create the UDP Filter Device Object\n")); ObDereferenceObject( pTargetFileObject ); pTargetFileObject = NULL; pTargetDeviceObject = NULL; return( status ); } pLowerDeviceObject = IoAttachDeviceToDeviceStack(pFilterDeviceObject,pTargetDeviceObject); if( !pLowerDeviceObject ) { DBGPRINT(("UDPFilter_Attach: Couldn't attach to UDP Device Object\n")); IoDeleteDevice( pFilterDeviceObject ); pFilterDeviceObject = NULL; ObDereferenceObject( pTargetFileObject ); pTargetFileObject = NULL; pTargetDeviceObject = NULL; return( status ); } pTDIH_DeviceExtension = (PTDIH_DeviceExtension )( pFilterDeviceObject->DeviceExtension ); UDPFilter_InitDeviceExtension( IN pTDIH_DeviceExtension, IN pFilterDeviceObject, IN pTargetDeviceObject, IN pTargetFileObject, IN pLowerDeviceObject ); pFilterDeviceObject->Flags |= pTargetDeviceObject->Flags & (DO_BUFFERED_IO | DO_DIRECT_IO); return status; }
// // General ioctl to NDASBUS // NTSTATUS IoctlToLanscsiBus( IN ULONG IoControlCode, IN PVOID InputBuffer OPTIONAL, IN ULONG InputBufferLength, OUT PVOID OutputBuffer OPTIONAL, IN ULONG OutputBufferLength, OUT PULONG BufferNeeded ) { NTSTATUS ntStatus; PWSTR symbolicLinkList; UNICODE_STRING objectName; PFILE_OBJECT fileObject; PDEVICE_OBJECT deviceObject; PIRP irp; KEVENT event; IO_STATUS_BLOCK ioStatus; KDPrint(3,("IoControlCode = %x\n", IoControlCode)); ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL); ntStatus = IoGetDeviceInterfaces( &GUID_NDAS_BUS_ENUMERATOR_INTERFACE_CLASS, NULL, 0, &symbolicLinkList ); if(!NT_SUCCESS(ntStatus)) { KDPrint(2,("IoGetDeviceInterfaces ntStatus = 0x%x\n", ntStatus)); return ntStatus; } ASSERT(symbolicLinkList != NULL); KDPrint(2,("symbolicLinkList = %ws\n", symbolicLinkList)); RtlInitUnicodeString(&objectName, symbolicLinkList); ntStatus = IoGetDeviceObjectPointer( &objectName, FILE_ALL_ACCESS, &fileObject, &deviceObject ); if(!NT_SUCCESS(ntStatus)) { KDPrint(2,("ntStatus = 0x%x\n", ntStatus)); ExFreePool(symbolicLinkList); return ntStatus; } KeInitializeEvent(&event, NotificationEvent, FALSE); irp = IoBuildDeviceIoControlRequest( IoControlCode, deviceObject, InputBuffer, InputBufferLength, OutputBuffer, OutputBufferLength, FALSE, &event, &ioStatus ); if (irp == NULL) { KDPrint(2,("irp NULL\n")); ExFreePool(symbolicLinkList); ObDereferenceObject(fileObject); return ntStatus; } KDPrint(3,("Before Done...ioStatus.Status = 0x%08x Information = %d\n", ioStatus.Status, ioStatus.Information)); ntStatus = IoCallDriver(deviceObject, irp); if (ntStatus == STATUS_PENDING) { KDPrint(2,("IoCallDriver STATUS_PENDING\n")); KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL); ntStatus = ioStatus.Status; } else if(NT_SUCCESS(ntStatus)) { ntStatus = ioStatus.Status; } if(BufferNeeded) *BufferNeeded = (ULONG)ioStatus.Information; ExFreePool(symbolicLinkList); ObDereferenceObject(fileObject); KDPrint(2,("Done...ioStatus.Status = 0x%08x Information = %d\n", ioStatus.Status, ioStatus.Information)); return ntStatus; }
PGRAPHICS_DEVICE NTAPI EngpRegisterGraphicsDevice( _In_ PUNICODE_STRING pustrDeviceName, _In_ PUNICODE_STRING pustrDiplayDrivers, _In_ PUNICODE_STRING pustrDescription, _In_ PDEVMODEW pdmDefault) { PGRAPHICS_DEVICE pGraphicsDevice; PDEVICE_OBJECT pDeviceObject; PFILE_OBJECT pFileObject; NTSTATUS Status; PWSTR pwsz; ULONG cj; SIZE_T cjWritten; BOOL bEnable = TRUE; TRACE("EngpRegisterGraphicsDevice(%wZ)\n", pustrDeviceName); /* Allocate a GRAPHICS_DEVICE structure */ pGraphicsDevice = ExAllocatePoolWithTag(PagedPool, sizeof(GRAPHICS_DEVICE), GDITAG_GDEVICE); if (!pGraphicsDevice) { ERR("ExAllocatePoolWithTag failed\n"); return NULL; } /* Try to open the driver */ Status = IoGetDeviceObjectPointer(pustrDeviceName, FILE_READ_DATA | FILE_WRITE_DATA, &pFileObject, &pDeviceObject); if (!NT_SUCCESS(Status)) { ERR("Could not open driver %wZ, 0x%lx\n", pustrDeviceName, Status); ExFreePoolWithTag(pGraphicsDevice, GDITAG_GDEVICE); return NULL; } /* Enable the device */ EngFileWrite(pFileObject, &bEnable, sizeof(BOOL), &cjWritten); /* Copy the device and file object pointers */ pGraphicsDevice->DeviceObject = pDeviceObject; pGraphicsDevice->FileObject = pFileObject; /* Copy device name */ RtlStringCbCopyNW(pGraphicsDevice->szNtDeviceName, sizeof(pGraphicsDevice->szNtDeviceName), pustrDeviceName->Buffer, pustrDeviceName->Length); /* Create a win device name (FIXME: virtual devices!) */ swprintf(pGraphicsDevice->szWinDeviceName, L"\\\\.\\DISPLAY%d", (int)giDevNum); /* Allocate a buffer for the strings */ cj = pustrDiplayDrivers->Length + pustrDescription->Length + sizeof(WCHAR); pwsz = ExAllocatePoolWithTag(PagedPool, cj, GDITAG_DRVSUP); if (!pwsz) { ERR("Could not allocate string buffer\n"); ASSERT(FALSE); // FIXME ExFreePoolWithTag(pGraphicsDevice, GDITAG_GDEVICE); return NULL; } /* Copy display driver names */ pGraphicsDevice->pDiplayDrivers = pwsz; RtlCopyMemory(pGraphicsDevice->pDiplayDrivers, pustrDiplayDrivers->Buffer, pustrDiplayDrivers->Length); /* Copy description */ pGraphicsDevice->pwszDescription = pwsz + pustrDiplayDrivers->Length / sizeof(WCHAR); RtlCopyMemory(pGraphicsDevice->pwszDescription, pustrDescription->Buffer, pustrDescription->Length); pGraphicsDevice->pwszDescription[pustrDescription->Length/sizeof(WCHAR)] = 0; /* Initialize the pdevmodeInfo list and default index */ pGraphicsDevice->pdevmodeInfo = NULL; pGraphicsDevice->iDefaultMode = 0; pGraphicsDevice->iCurrentMode = 0; // FIXME: initialize state flags pGraphicsDevice->StateFlags = 0; /* Create the mode list */ pGraphicsDevice->pDevModeList = NULL; if (!EngpPopulateDeviceModeList(pGraphicsDevice, pdmDefault)) { ExFreePoolWithTag(pGraphicsDevice, GDITAG_GDEVICE); return NULL; } /* Lock loader */ EngAcquireSemaphore(ghsemGraphicsDeviceList); /* Insert the device into the global list */ pGraphicsDevice->pNextGraphicsDevice = NULL; if (gpGraphicsDeviceLast) gpGraphicsDeviceLast->pNextGraphicsDevice = pGraphicsDevice; gpGraphicsDeviceLast = pGraphicsDevice; if (!gpGraphicsDeviceFirst) gpGraphicsDeviceFirst = pGraphicsDevice; /* Increment device number */ giDevNum++; /* Unlock loader */ EngReleaseSemaphore(ghsemGraphicsDeviceList); TRACE("Prepared %lu modes for %ls\n", pGraphicsDevice->cDevModes, pGraphicsDevice->pwszDescription); return pGraphicsDevice; }
/*++ * @name IoSetDeviceInterfaceState * @implemented * * Enables or disables an instance of a previously registered device * interface class. * Documented in WDK. * * @param SymbolicLinkName * Pointer to the string identifying instance to enable or disable * * @param Enable * TRUE = enable, FALSE = disable * * @return Usual NTSTATUS * * @remarks Must be called at IRQL = PASSIVE_LEVEL in the context of a * system thread * *--*/ NTSTATUS NTAPI IoSetDeviceInterfaceState(IN PUNICODE_STRING SymbolicLinkName, IN BOOLEAN Enable) { PDEVICE_OBJECT PhysicalDeviceObject; PFILE_OBJECT FileObject; UNICODE_STRING GuidString; UNICODE_STRING SymLink; PWCHAR StartPosition; PWCHAR EndPosition; NTSTATUS Status; LPCGUID EventGuid; HANDLE InstanceHandle, ControlHandle; UNICODE_STRING KeyName; OBJECT_ATTRIBUTES ObjectAttributes; ULONG LinkedValue; GUID DeviceGuid; if (SymbolicLinkName == NULL) return STATUS_INVALID_PARAMETER_1; DPRINT("IoSetDeviceInterfaceState('%wZ', %u)\n", SymbolicLinkName, Enable); /* Symbolic link name is \??\ACPI#PNP0501#1#{GUID}\ReferenceString */ /* Get GUID from SymbolicLinkName */ StartPosition = wcschr(SymbolicLinkName->Buffer, L'{'); EndPosition = wcschr(SymbolicLinkName->Buffer, L'}'); if (!StartPosition ||!EndPosition || StartPosition > EndPosition) { DPRINT1("IoSetDeviceInterfaceState() returning STATUS_INVALID_PARAMETER_1\n"); return STATUS_INVALID_PARAMETER_1; } GuidString.Buffer = StartPosition; GuidString.MaximumLength = GuidString.Length = (USHORT)((ULONG_PTR)(EndPosition + 1) - (ULONG_PTR)StartPosition); SymLink.Buffer = SymbolicLinkName->Buffer; SymLink.MaximumLength = SymLink.Length = (USHORT)((ULONG_PTR)(EndPosition + 1) - (ULONG_PTR)SymLink.Buffer); DPRINT("IoSetDeviceInterfaceState('%wZ', %u)\n", SymbolicLinkName, Enable); Status = OpenRegistryHandlesFromSymbolicLink(SymbolicLinkName, KEY_CREATE_SUB_KEY, NULL, NULL, &InstanceHandle); if (!NT_SUCCESS(Status)) return Status; RtlInitUnicodeString(&KeyName, L"Control"); InitializeObjectAttributes(&ObjectAttributes, &KeyName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, InstanceHandle, NULL); Status = ZwCreateKey(&ControlHandle, KEY_SET_VALUE, &ObjectAttributes, 0, NULL, REG_OPTION_VOLATILE, NULL); ZwClose(InstanceHandle); if (!NT_SUCCESS(Status)) { DPRINT1("Failed to create the Control subkey\n"); return Status; } LinkedValue = (Enable ? 1 : 0); RtlInitUnicodeString(&KeyName, L"Linked"); Status = ZwSetValueKey(ControlHandle, &KeyName, 0, REG_DWORD, &LinkedValue, sizeof(ULONG)); ZwClose(ControlHandle); if (!NT_SUCCESS(Status)) { DPRINT1("Failed to write the Linked value\n"); return Status; } /* Get pointer to the PDO */ Status = IoGetDeviceObjectPointer( &SymLink, 0, /* DesiredAccess */ &FileObject, &PhysicalDeviceObject); if (!NT_SUCCESS(Status)) { DPRINT1("IoGetDeviceObjectPointer() failed with status 0x%08lx\n", Status); return Status; } Status = RtlGUIDFromString(&GuidString, &DeviceGuid); if (!NT_SUCCESS(Status)) { DPRINT1("RtlGUIDFromString() failed with status 0x%08lx\n", Status); return Status; } EventGuid = Enable ? &GUID_DEVICE_INTERFACE_ARRIVAL : &GUID_DEVICE_INTERFACE_REMOVAL; IopNotifyPlugPlayNotification( PhysicalDeviceObject, EventCategoryDeviceInterfaceChange, EventGuid, &DeviceGuid, (PVOID)SymbolicLinkName); ObDereferenceObject(FileObject); DPRINT("Status %x\n", Status); return STATUS_SUCCESS; }
NTSTATUS OpenDeviceReparseIndex( IN PUNICODE_STRING DeviceName, OUT PHANDLE Handle ) /*++ Routine Description: This routine opens the reparse index on the given device. Arguments: DeviceName - Supplies the device name. Handle - Returns the handle. Return Value: NTSTATUS --*/ { NTSTATUS status; PFILE_OBJECT fileObject; PDEVICE_OBJECT deviceObject; UNICODE_STRING reparseSuffix, reparseName; OBJECT_ATTRIBUTES oa; IO_STATUS_BLOCK ioStatus; status = IoGetDeviceObjectPointer(DeviceName, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject); if (!NT_SUCCESS(status)) { return status; } deviceObject = fileObject->DeviceObject; if (!deviceObject->Vpb || !(deviceObject->Vpb->Flags&VPB_MOUNTED)) { ObDereferenceObject(fileObject); return STATUS_UNSUCCESSFUL; } ObDereferenceObject(fileObject); RtlInitUnicodeString(&reparseSuffix, L"\\$Extend\\$Reparse:$R:$INDEX_ALLOCATION"); reparseName.Length = DeviceName->Length + reparseSuffix.Length; reparseName.MaximumLength = reparseName.Length + sizeof(WCHAR); reparseName.Buffer = ExAllocatePool(PagedPool, reparseName.MaximumLength); if (!reparseName.Buffer) { return STATUS_INSUFFICIENT_RESOURCES; } RtlCopyMemory(reparseName.Buffer, DeviceName->Buffer, DeviceName->Length); RtlCopyMemory((PCHAR) reparseName.Buffer + DeviceName->Length, reparseSuffix.Buffer, reparseSuffix.Length); reparseName.Buffer[reparseName.Length/sizeof(WCHAR)] = 0; InitializeObjectAttributes(&oa, &reparseName, OBJ_CASE_INSENSITIVE, 0, 0); status = ZwOpenFile(Handle, SYNCHRONIZE | FILE_LIST_DIRECTORY, &oa, &ioStatus, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_ALERT | FILE_OPEN_FOR_BACKUP_INTENT); ExFreePool(reparseName.Buffer); return status; }
NTSTATUS KbdWinQueryLeds( ) /** Query windows current state of LEDs */ { UNICODE_STRING DeviceName; PDEVICE_OBJECT DeviceObject; PFILE_OBJECT FileObject; NTSTATUS Status; RtlInitUnicodeString (&DeviceName, L"\\Device\\KeyboardClass0"); Status = IoGetDeviceObjectPointer (&DeviceName, FILE_READ_ATTRIBUTES, &FileObject, &DeviceObject); if (!NT_SUCCESS(Status)) { KdPrint(("IoGetDeviceObjectPointer failed st %X\n", Status)); return Status; } PIRP Irp; IO_STATUS_BLOCK IoStatus; KEVENT Event; KeInitializeEvent (&Event, SynchronizationEvent, FALSE); KEYBOARD_UNIT_ID_PARAMETER unitID = {0}; KEYBOARD_INDICATOR_PARAMETERS leds = {0}; Irp = IoBuildDeviceIoControlRequest ( IOCTL_KEYBOARD_QUERY_INDICATORS, DeviceObject, &unitID, sizeof(unitID), &leds, sizeof(leds), FALSE, &Event, &IoStatus ); Status = IoCallDriver (DeviceObject, Irp); if (Status == STATUS_PENDING) { KeWaitForSingleObject (&Event, Executive, KernelMode, FALSE, NULL); } if (NT_SUCCESS(Status)) Status = IoStatus.Status; ObDereferenceObject (FileObject); if (!NT_SUCCESS(Status)) { KdPrint(("IOCTL_KEYBOARD_QUERY_INDICATORS failed with status %X\n", Status)); return Status; } WindowsNum = !!(leds.LedFlags & KEYBOARD_NUM_LOCK_ON); WindowsCaps = !!(leds.LedFlags & KEYBOARD_CAPS_LOCK_ON); WindowsScroll = !!(leds.LedFlags & KEYBOARD_SCROLL_LOCK_ON); KdPrint(("IOCTL_KEYBOARD_QUERY_INDICATORS ok\n")); return STATUS_SUCCESS; }
/** * Install/Uninstall the filter function */ NTSTATUS SetFilterFunction( IPPacketFirewallPtr pfnFilterFunction, BOOLEAN bLoad ) { // // pfnFilterFunction - [in] Pointer to the filter function. // loa - [in] If TRUE, the function is added. Else, the function will be removed. // RETURN - STATUS_SUCCESS If success, // NTSTATUS ntStatus = STATUS_SUCCESS; NTSTATUS ntWaitStatus = STATUS_SUCCESS; UNICODE_STRING usFilterName; PDEVICE_OBJECT pstIpDeviceObject = NULL; PFILE_OBJECT pstIpFileObject = NULL; IP_SET_FIREWALL_HOOK_INFO stFilterData; KEVENT oEvent; IO_STATUS_BLOCK stIoStatus; PIRP pstIrp; __try { // Get pointer to Ip device RtlInitUnicodeString( &usFilterName, DD_IP_DEVICE_NAME ); ntStatus = IoGetDeviceObjectPointer( &usFilterName, STANDARD_RIGHTS_ALL, &pstIpFileObject, &pstIpDeviceObject ); if ( NT_SUCCESS( ntStatus ) ) { // Init firewall hook structure memset( &stFilterData, 0, sizeof(stFilterData) ); stFilterData.FirewallPtr = pfnFilterFunction; stFilterData.Priority = 1; stFilterData.Add = bLoad; KeInitializeEvent( &oEvent, NotificationEvent, FALSE ); // Build pstIrp to establish filter function pstIrp = IoBuildDeviceIoControlRequest ( IOCTL_IP_SET_FIREWALL_HOOK, pstIpDeviceObject, (PVOID)&stFilterData, sizeof(IP_SET_FIREWALL_HOOK_INFO), NULL, 0, FALSE, &oEvent, &stIoStatus ); if ( pstIrp ) { // Send the pstIrp and wait for its completion ntStatus = IoCallDriver( pstIpDeviceObject, pstIrp ); if ( STATUS_PENDING == ntStatus ) { ntWaitStatus = KeWaitForSingleObject( &oEvent, Executive, KernelMode, FALSE, NULL); if ( STATUS_SUCCESS != ntWaitStatus ) { dprintf( "VwFirewallDrv.sys: Error waiting for Ip Driver." ); } } ntStatus = stIoStatus.Status; if ( ! NT_SUCCESS( ntStatus ) ) { dprintf( "VwFirewallDrv.sys: E/S error with Ip Driver\n" ); } } else { ntStatus = STATUS_INSUFFICIENT_RESOURCES; dprintf( "VwFirewallDrv.sys: Error creating the IRP\n" ); } // Free resources if ( pstIpFileObject ) { ObDereferenceObject( pstIpFileObject ); } pstIpFileObject = NULL; pstIpDeviceObject = NULL; } else { dprintf( "VwFirewallDrv.sys: Error getting pointer to Ip driver.\n" ); } } __except( EXCEPTION_EXECUTE_HANDLER ) { KdPrint(( "EXCEPTION EXECUTE IN: SetFilterFunction\n" )); } return ntStatus; }
/** * Find and hot-swap to a backing file. Internal. * * We search all filesystems for a particular filename, then swap * to using it as the backing store. This is currently useful for * sector-mapped disks which should really have a file-in-use lock * for the file they represent. Once the backing file is established, * the work item is freed. Otherwise, it is re-enqueued and the * thread will keep trying. */ static BOOLEAN STDCALL WvFilediskHotSwap_( IN WV_SP_FILEDISK_T filedisk, IN PUNICODE_STRING filename ) { NTSTATUS status; GUID vol_guid = GUID_DEVINTERFACE_VOLUME; PWSTR sym_links; PWCHAR pos; KIRQL irql; /* Do we currently have a backing disk? If not, re-enqueue for later. */ if (filedisk->file == NULL) return FALSE; /* * Find the backing volume and use it. We walk a list * of unicode volume device names and check each one for the file. */ status = IoGetDeviceInterfaces(&vol_guid, NULL, 0, &sym_links); if (!NT_SUCCESS(status)) return FALSE; pos = sym_links; status = STATUS_UNSUCCESSFUL; while (*pos != UNICODE_NULL) { UNICODE_STRING path; PFILE_OBJECT vol_file_obj; PDEVICE_OBJECT vol_dev_obj; UNICODE_STRING vol_dos_name; UNICODE_STRING filepath; static const WCHAR obj_path_prefix[] = L"\\??\\"; static const WCHAR path_sep = L'\\'; OBJECT_ATTRIBUTES obj_attrs; HANDLE file = 0; IO_STATUS_BLOCK io_status; RtlInitUnicodeString(&path, pos); /* Get some object pointers for the volume. */ status = IoGetDeviceObjectPointer( &path, FILE_READ_DATA, &vol_file_obj, &vol_dev_obj ); if (!NT_SUCCESS(status)) goto err_obj_ptrs; /* Get the DOS name. */ vol_dos_name.Buffer = NULL; vol_dos_name.Length = vol_dos_name.MaximumLength = 0; status = RtlVolumeDeviceToDosName( vol_file_obj->DeviceObject, &vol_dos_name ); if (!NT_SUCCESS(status)) goto err_dos_name; /* Build the file path. Ugh, what a mess. */ filepath.Length = filepath.MaximumLength = sizeof obj_path_prefix - sizeof UNICODE_NULL + vol_dos_name.Length + sizeof path_sep + filename->Length; filepath.Buffer = wv_malloc(filepath.Length); if (filepath.Buffer == NULL) { status = STATUS_UNSUCCESSFUL; goto err_alloc_buf; } { PCHAR buf = (PCHAR) filepath.Buffer; RtlCopyMemory( buf, obj_path_prefix, sizeof obj_path_prefix - sizeof UNICODE_NULL ); buf += sizeof obj_path_prefix - sizeof UNICODE_NULL; RtlCopyMemory(buf, vol_dos_name.Buffer, vol_dos_name.Length); buf += vol_dos_name.Length; RtlCopyMemory(buf, &path_sep, sizeof path_sep); buf += sizeof path_sep; RtlCopyMemory(buf, filename->Buffer, filename->Length); } /* buf scope */ InitializeObjectAttributes( &obj_attrs, &filepath, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL ); /* Look for the file on this volume. */ status = ZwCreateFile( &file, GENERIC_READ | GENERIC_WRITE, &obj_attrs, &io_status, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, FILE_OPEN, FILE_NON_DIRECTORY_FILE | FILE_RANDOM_ACCESS | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 ); if (!NT_SUCCESS(status)) goto err_open; /* We could open it. Do the hot-swap. */ { HANDLE old = filedisk->file; filedisk->file = 0; filedisk->offset.QuadPart = 0; filedisk->file = file; ZwClose(old); } /* old scope */ err_open: wv_free(filepath.Buffer); err_alloc_buf: wv_free(vol_dos_name.Buffer); err_dos_name: ObDereferenceObject(vol_file_obj); err_obj_ptrs: /* Walk to the next terminator. */ while (*pos != UNICODE_NULL) pos++; /* If everything succeeded, stop. Otherwise try the next volume. */ if (!NT_SUCCESS(status)) pos++; } /* while */ wv_free(sym_links); /* Success? */ if (NT_SUCCESS(status)) { DBG("Finished hot-swapping.\n"); return TRUE; } return FALSE; }