NTSTATUS uStartFdo(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { NTSTATUS Status = STATUS_SUCCESS; PIO_STACK_LOCATION Stack; PFDO_EXT FdoExt; PDEVICE_RELATIONS Rels; Stack = IoGetCurrentIrpStackLocation( Irp ); FdoExt = DeviceObject->DeviceExtension; Status = SendIrpSynchronously(FdoExt->LowerDev,Irp); if (NT_ERROR(Status)) goto ErrorOut; Status = IoSetDeviceInterfaceState (&FdoExt->InterfaceName , TRUE ); if (NT_ERROR(Status)) goto ErrorOut; uSCSIInitialize(); return Status; ErrorOut: return Status; }
VOID NTAPI FatCompleteRequest(PFAT_IRP_CONTEXT IrpContext OPTIONAL, PIRP Irp OPTIONAL, NTSTATUS Status) { PAGED_CODE(); if (IrpContext) { /* TODO: Unpin repinned BCBs */ //ASSERT(IrpContext->Repinned.Bcb[0] == NULL); //FatUnpinRepinnedBcbs( IrpContext ); /* Destroy IRP context */ FatDestroyIrpContext(IrpContext); } /* Complete the IRP */ if (Irp) { /* Cleanup IoStatus.Information in case of error input operation */ if (NT_ERROR(Status) && (Irp->Flags & IRP_INPUT_OPERATION)) { Irp->IoStatus.Information = 0; } /* Save status and complete this IRP */ Irp->IoStatus.Status = Status; IoCompleteRequest( Irp, IO_DISK_INCREMENT ); } }
NTSTATUS Ext2CompleteIrpContext ( IN PEXT2_IRP_CONTEXT IrpContext, IN NTSTATUS Status ) { PIRP Irp = NULL; BOOLEAN bPrint; Irp = IrpContext->Irp; if (Irp != NULL) { if (NT_ERROR(Status)) { Irp->IoStatus.Information = 0; } Irp->IoStatus.Status = Status; bPrint = !IsFlagOn(IrpContext->Flags, IRP_CONTEXT_FLAG_REQUEUED); Ext2CompleteRequest( Irp, bPrint, (CCHAR)(NT_SUCCESS(Status)? IO_DISK_INCREMENT : IO_NO_INCREMENT) ); IrpContext->Irp = NULL; } Ext2FreeIrpContext(IrpContext); return Status; }
//Called after a read request to the MBR has been processed NTSTATUS MbrReadComplete(PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID Context) { PVOID SystemMdlAddress; PIO_STACK_LOCATION StackLocation; PCOMPLETION_CTX CompletionCtx; CHAR InvokeCompletion = FALSE; UCHAR Control; NTSTATUS IrpStatus, status = STATUS_SUCCESS; CompletionCtx = (PCOMPLETION_CTX)Context; StackLocation = IoGetCurrentIrpStackLocation(Irp); //If request was successful, we need to replace the real MBR inside buffer if(NT_SUCCESS(Irp->IoStatus.Status) && CompletionCtx->TransferLength > 0) { SystemMdlAddress = MmGetSystemAddressForMdlSafe(Irp->MdlAddress, NormalPagePriority); if(SystemMdlAddress) { memcpy(SystemMdlAddress, FakeMbr, 512); DbgPrint("{CompletionRoutine} Disk read request was successful, replaced MBR in buffer %X\n", CompletionCtx->TransferLength); } } //Restore original completion routine information StackLocation->Context = CompletionCtx->OriginalContext; StackLocation->CompletionRoutine = CompletionCtx->OriginalRoutine; StackLocation->Control = CompletionCtx->OriginalControl; Control = StackLocation->Control; IrpStatus = Irp->IoStatus.Status; //If there is an original completion routine, check if it should be called if(StackLocation->CompletionRoutine) { if(NT_SUCCESS(IrpStatus) && (Control & SL_INVOKE_ON_SUCCESS) == SL_INVOKE_ON_SUCCESS) InvokeCompletion = TRUE; if(IrpStatus == STATUS_CANCELLED && (Control & SL_INVOKE_ON_CANCEL) == SL_INVOKE_ON_CANCEL) InvokeCompletion = TRUE; if(NT_ERROR(IrpStatus) && IrpStatus != STATUS_CANCELLED && (Control & SL_INVOKE_ON_ERROR) == SL_INVOKE_ON_ERROR) InvokeCompletion = TRUE; } //Call original completion routine if(InvokeCompletion == TRUE) status = (StackLocation->CompletionRoutine)(DeviceObject, Irp, StackLocation->Context); ExFreePool(Context); return status; }
int CollectorWin::getRawHostCpuLoad(uint64_t *user, uint64_t *kernel, uint64_t *idle) { LogFlowThisFuncEnter(); FILETIME ftIdle, ftKernel, ftUser; if (mpfnGetSystemTimes) { if (!mpfnGetSystemTimes(&ftIdle, &ftKernel, &ftUser)) { DWORD dwError = GetLastError(); Log (("GetSystemTimes() -> 0x%x\n", dwError)); return RTErrConvertFromWin32(dwError); } *user = FILETTIME_TO_100NS(ftUser); *idle = FILETTIME_TO_100NS(ftIdle); *kernel = FILETTIME_TO_100NS(ftKernel) - *idle; } else { /* GetSystemTimes is not available, fall back to NtQuerySystemInformation */ if (!mpfnNtQuerySystemInformation) return VERR_NOT_IMPLEMENTED; SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION sppi[MAXIMUM_PROCESSORS]; ULONG ulReturned; NTSTATUS status = mpfnNtQuerySystemInformation( SystemProcessorPerformanceInformation, &sppi, sizeof(sppi), &ulReturned); if (NT_ERROR(status)) { Log(("NtQuerySystemInformation() -> 0x%x\n", status)); return RTErrConvertFromNtStatus(status); } /* Sum up values across all processors */ *user = *kernel = *idle = 0; for (unsigned i = 0; i < ulReturned / sizeof(sppi[0]); ++i) { *idle += sppi[i].IdleTime.QuadPart; *kernel += sppi[i].KernelTime.QuadPart - sppi[i].IdleTime.QuadPart; *user += sppi[i].UserTime.QuadPart; } } LogFlowThisFunc(("user=%lu kernel=%lu idle=%lu\n", *user, *kernel, *idle)); LogFlowThisFuncLeave(); return VINF_SUCCESS; }
/* prints the data in Cse451Info class in the following format: API TOTAL SUCCESS INFO WARN ERROR BYTES ------------------------------------- --------- --------- --------- --------- --------- --------- API_NAME ### ### ### ### ### ### ... ... ... ... ... ... ... */ VOID printAbbrevStatus(SYSTEM_CSE451_INFORMATION Cse451Info) { ULONG total , success, info, warn, error; USHORT i; USHORT j; ULONG count; NTSTATUS status; printf("%30s %10s %10s %10s %10s %10s %15s\n", "API", "TOTAL", "SUCCESS", "INFO", "WARN", "ERROR", "BYTES"); printf("%.30s %.10s %.10s %.10s %.10s %.10s %.15s\n", BIG_UNDERLINE, BIG_UNDERLINE, BIG_UNDERLINE, BIG_UNDERLINE, BIG_UNDERLINE, BIG_UNDERLINE, BIG_UNDERLINE); for(j = 0; j < NUM_CSE451_APIS; j++) { total = 0; success = 0; info = 0; warn = 0; error = 0; count = 0; status = 0; for(i = 0; i < Cse451Info.ApiStatus[j].NumStatuses; i++) { count = Cse451Info.ApiStatus[j].StatusCounts[i].Count; status = Cse451Info.ApiStatus[j].StatusCounts[i].Status; total += count; if(NT_SUCCESS(status)) { success += count; } else if(NT_INFORMATION(status)) { info += count; } else if(NT_WARNING(status)) { warn += count; } else if(NT_ERROR(status)) { error += count; } } printf("%30s %10d %10d %10d %10d %10d ", CSE451_APIS_STRINGS[j], total, success, info, warn, error); if(j == ReadFile || j == WriteFile) { printf("%15d", Cse451Info.ApiStatus[j].BytesUsed); } printf("\n"); } }
NTSTATUS AlertDrvDispatch(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { PIO_STACK_LOCATION irpStack; PVOID ioBuffer; ULONG inputBufferLength; ULONG outputBufferLength; ULONG ioControlCode; NTSTATUS ntStatus; PHANDLE ph = NULL; PETHREAD uThread = NULL; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; irpStack = IoGetCurrentIrpStackLocation(Irp); ioBuffer = Irp->AssociatedIrp.SystemBuffer; inputBufferLength = irpStack->Parameters.DeviceIoControl.InputBufferLength; outputBufferLength = irpStack->Parameters.DeviceIoControl.OutputBufferLength; switch (irpStack->MajorFunction) { case IRP_MJ_CREATE: AlertDrvKdPrint (("IRP_MJ_CREATE\n")); break; case IRP_MJ_CLOSE: AlertDrvKdPrint (("IRP_MJ_CLOSE\n")); break; case IRP_MJ_DEVICE_CONTROL: ioControlCode = irpStack->Parameters.DeviceIoControl.IoControlCode; switch (ioControlCode) { case IOCTL_ALERTDRV_SET_ALERTABLE2: if (inputBufferLength >= sizeof(PVOID)) { ph = (PHANDLE) ioBuffer; Irp->IoStatus.Status = ObReferenceObjectByHandle(*((PHANDLE)ph),THREAD_ALL_ACCESS,NULL,UserMode,&uThread,NULL); if (NT_ERROR(Irp->IoStatus.Status)) { AlertDrvKdPrint (("ObReferenceObjectByHandle Failed (%ld)\n", Irp->IoStatus.Status)); } else { AlertDrvKdPrint (("uThread = 0x%lx\n", uThread)); Irp->IoStatus.Status = AlertDrvSendTheSignal(uThread); ObDereferenceObject((PVOID) uThread); } } else { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; AlertDrvKdPrint (("Invalid parameter passed!\n")); } break; default: AlertDrvKdPrint (("Unknown IRP_MJ_DEVICE_CONTROL\n")); Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; break; } break; } ntStatus = Irp->IoStatus.Status; IoCompleteRequest(Irp, IO_NO_INCREMENT); return ntStatus; }
_Use_decl_annotations_ NTSTATUS PrepareHardware( WDFDEVICE Device, WDFCMRESLIST ResourceList, WDFCMRESLIST ResourceListTranslated ) /*++ Routine Description: PrepareHardware parses the device resource description and assigns default values in device context. Arguments: Device - Pointer to the device object ResourceList - Pointer to the devices resource list ResourceListTranslated - Ponter to the translated resource list of the device Return Value: Status --*/ { PAGED_CODE(); UNREFERENCED_PARAMETER(ResourceList); PDEVICE_CONTEXT deviceContext; NTSTATUS status = STATUS_SUCCESS; ULONG resourceCount; ULONG memoryResources = 0; ULONG interruptResources = 0; ULONG dmaResources = 0; deviceContext = GetContext(Device); resourceCount = WdfCmResourceListGetCount(ResourceListTranslated); for (ULONG i = 0; i < resourceCount && NT_SUCCESS(status); ++i) { PCM_PARTIAL_RESOURCE_DESCRIPTOR res; res = WdfCmResourceListGetDescriptor(ResourceListTranslated, i); switch (res->Type) { case CmResourceTypeMemory: if (memoryResources == 0) { // // DMA channel registers // if (res->u.Memory.Length < sizeof(DMA_CHANNEL_REGS)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "DMA channel memory region too small (start:0x%llX, length:0x%X)", res->u.Memory.Start.QuadPart, res->u.Memory.Length ); status = STATUS_DEVICE_CONFIGURATION_ERROR; break; } deviceContext->dmaChannelRegs = (PDMA_CHANNEL_REGS)MmMapIoSpaceEx( res->u.Memory.Start, res->u.Memory.Length, PAGE_READWRITE | PAGE_NOCACHE ); if (deviceContext->dmaChannelRegs == NULL) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "Unable to map DMA channel registers."); status = STATUS_INSUFFICIENT_RESOURCES; break; } deviceContext->dmaChannelRegsPa = res->u.Memory.Start; } else if (memoryResources == 1) { // // PWM registers // if (res->u.Memory.Length < sizeof(PWM_REGS)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "PWM control register memory region too small (start:0x%llX, length:0x%X)", res->u.Memory.Start.QuadPart, res->u.Memory.Length ); status = STATUS_DEVICE_CONFIGURATION_ERROR; break; } deviceContext->pwmRegs = (PPWM_REGS)MmMapIoSpaceEx( res->u.Memory.Start, res->u.Memory.Length, PAGE_READWRITE | PAGE_NOCACHE ); if (deviceContext->pwmRegs == NULL) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "Unable to map PWM control registers."); status = STATUS_INSUFFICIENT_RESOURCES; break; } deviceContext->pwmRegsPa = res->u.Memory.Start; } else if (memoryResources == 2) { // // PWM control registers bus address // deviceContext->pwmRegsBusPa = res->u.Memory.Start; } else if (memoryResources == 3) { // // PWM control registers uncached address // PHYSICAL_ADDRESS pa = res->u.Memory.Start; deviceContext->memUncachedOffset = pa.LowPart - deviceContext->pwmRegsPa.LowPart; } else if (memoryResources == 4) { // // PWM clock registers // if (res->u.Memory.Length < sizeof(CM_PWM_REGS)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "PWM clock register memory region too small (start:0x%llX, length:0x%X)", res->u.Memory.Start.QuadPart, res->u.Memory.Length ); status = STATUS_DEVICE_CONFIGURATION_ERROR; break; } deviceContext->cmPwmRegs = (PCM_PWM_REGS)MmMapIoSpaceEx( res->u.Memory.Start, res->u.Memory.Length, PAGE_READWRITE | PAGE_NOCACHE ); if (deviceContext->cmPwmRegs == NULL) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "Unable to map PWM clock registers."); status = STATUS_INSUFFICIENT_RESOURCES; break; } deviceContext->cmPwmRegsPa = res->u.Memory.Start; } else { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "Too many ACPI memory entries. Only 5 memory entries are allowed. Please verify ACPI configuration."); status = STATUS_DEVICE_CONFIGURATION_ERROR; break; } memoryResources++; break; case CmResourceTypeInterrupt: // // Interrupt for used DMA channel. No setup required. // interruptResources++; break; case CmResourceTypeDma: // // Get the used DMA channel. // deviceContext->dmaChannel = res->u.DmaV3.Channel; deviceContext->dmaDreq = res->u.DmaV3.RequestLine; deviceContext->dmaTransferWidth = (DMA_WIDTH)res->u.DmaV3.TransferWidth; // // Sanity check DREQ, transfer width. // if (deviceContext->dmaDreq != DMA_DREQ_PWM) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "PWM DREQ configuration invalid (DREQ:%d)", res->u.DmaV3.RequestLine); status = STATUS_DEVICE_CONFIGURATION_ERROR; break; } if (deviceContext->dmaTransferWidth != Width32Bits) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "PWM DMA transfer width setting (width setting:%d)", (ULONG)res->u.DmaV3.TransferWidth); status = STATUS_DEVICE_CONFIGURATION_ERROR; break; } // // Allocate and initialize contiguous DMA buffer logic. // status = AllocateDmaBuffer(deviceContext); if (NT_ERROR(status)) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "Error allocating DMA buffer (0x%08x)", status); } dmaResources++; break; default: TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "Resource type not allowed for PWM. Please verify ACPI configuration."); status = STATUS_DEVICE_CONFIGURATION_ERROR; break; } } // // Sanity check ACPI resources. // if (memoryResources != 5) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "Too less ACPI memory entries. 5 memory entries are required. Please verify ACPI configuration."); status = STATUS_DEVICE_CONFIGURATION_ERROR; } if (interruptResources != 1) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "Exactly 1 interrupt entry is required and allowed. Please verify ACPI configuration."); status = STATUS_DEVICE_CONFIGURATION_ERROR; } if (dmaResources != 1) { TraceEvents(TRACE_LEVEL_ERROR, TRACE_INIT, "Exactly 1 DMA entry is required and allowed. Please verify ACPI configuration."); status = STATUS_DEVICE_CONFIGURATION_ERROR; } if (NT_SUCCESS(status)) { // // Initialize device context and set default values. // deviceContext->pwmClockConfig.ClockSource = BCM_PWM_CLOCKSOURCE_PLLC; deviceContext->pwmClockConfig.Divisor = CM_PWMCTL_DIVI_PLLC_1MHZ; deviceContext->pwmChannel1Config.Channel = BCM_PWM_CHANNEL_CHANNEL1; deviceContext->pwmChannel1Config.Range = 0x20; deviceContext->pwmChannel1Config.DutyMode = BCM_PWM_DUTYMODE_PWM; deviceContext->pwmChannel1Config.Mode = BCM_PWM_MODE_PWM; deviceContext->pwmChannel1Config.Polarity = BCM_PWM_POLARITY_NORMAL; deviceContext->pwmChannel1Config.Repeat = BCM_PWM_REPEATMODE_OFF; deviceContext->pwmChannel1Config.Silence = BCM_PWM_SILENCELEVEL_LOW; deviceContext->pwmDuty1 = 0; deviceContext->pwmChannel2Config.Channel = BCM_PWM_CHANNEL_CHANNEL2; deviceContext->pwmChannel2Config.Range = 0x20; deviceContext->pwmChannel2Config.DutyMode = BCM_PWM_DUTYMODE_PWM; deviceContext->pwmChannel2Config.Mode = BCM_PWM_MODE_PWM; deviceContext->pwmChannel2Config.Polarity = BCM_PWM_POLARITY_NORMAL; deviceContext->pwmChannel2Config.Repeat = BCM_PWM_REPEATMODE_OFF; deviceContext->pwmChannel2Config.Silence = BCM_PWM_SILENCELEVEL_LOW; deviceContext->pwmDuty2 = 0; deviceContext->pwmMode = PWM_MODE_REGISTER; InitializeListHead(&deviceContext->notificationList); deviceContext->dmaDpcForIsrErrorCount = 0; deviceContext->dmaUnderflowErrorCount = 0; deviceContext->dmaLastKnownCompletedPacket = NO_LAST_COMPLETED_PACKET; deviceContext->dmaPacketsInUse = 0; deviceContext->dmaPacketsToPrime = 0; deviceContext->dmaPacketsToPrimePreset = 0; deviceContext->dmaPacketsProcessed = 0; deviceContext->dmaAudioNotifcationCount = 0; deviceContext->dmaRestartRequired = FALSE; } else { ReleaseHardware(Device, ResourceListTranslated); } return status; }
NTSTATUS DriverEntry(__in PDRIVER_OBJECT DriverObject, __in PUNICODE_STRING RegistryPath) /*++ Routine Description: This routine gets called by the system to initialize the driver. Arguments: DriverObject - the system supplied driver object. RegistryPath - the system supplied registry path for this driver. Return Value: NTSTATUS --*/ { NTSTATUS status; PFAST_IO_DISPATCH fastIoDispatch; FS_FILTER_CALLBACKS filterCallbacks; PDOKAN_GLOBAL dokanGlobal = NULL; UNREFERENCED_PARAMETER(RegistryPath); DDbgPrint("==> DriverEntry ver.%x, %s %s\n", DOKAN_DRIVER_VERSION, __DATE__, __TIME__); status = DokanCreateGlobalDiskDevice(DriverObject, &dokanGlobal); if (NT_ERROR(status)) { return status; } // // Set up dispatch entry points for the driver. // DriverObject->DriverUnload = DokanUnload; DriverObject->MajorFunction[IRP_MJ_CREATE] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_CLOSE] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_CLEANUP] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_DIRECTORY_CONTROL] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_SET_VOLUME_INFORMATION] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_READ] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_WRITE] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_SHUTDOWN] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_PNP] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_LOCK_CONTROL] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_QUERY_SECURITY] = DokanBuildRequest; DriverObject->MajorFunction[IRP_MJ_SET_SECURITY] = DokanBuildRequest; fastIoDispatch = ExAllocatePool(sizeof(FAST_IO_DISPATCH)); if (!fastIoDispatch) { CleanupGlobalDiskDevice(dokanGlobal); DDbgPrint(" ExAllocatePool failed"); return STATUS_INSUFFICIENT_RESOURCES; } RtlZeroMemory(fastIoDispatch, sizeof(FAST_IO_DISPATCH)); fastIoDispatch->SizeOfFastIoDispatch = sizeof(FAST_IO_DISPATCH); fastIoDispatch->FastIoCheckIfPossible = DokanFastIoCheckIfPossible; // fastIoDispatch->FastIoRead = DokanFastIoRead; fastIoDispatch->FastIoRead = FsRtlCopyRead; fastIoDispatch->FastIoWrite = FsRtlCopyWrite; fastIoDispatch->AcquireFileForNtCreateSection = DokanAcquireForCreateSection; fastIoDispatch->ReleaseFileForNtCreateSection = DokanReleaseForCreateSection; fastIoDispatch->MdlRead = FsRtlMdlReadDev; fastIoDispatch->MdlReadComplete = FsRtlMdlReadCompleteDev; fastIoDispatch->PrepareMdlWrite = FsRtlPrepareMdlWriteDev; fastIoDispatch->MdlWriteComplete = FsRtlMdlWriteCompleteDev; DriverObject->FastIoDispatch = fastIoDispatch; #if _WIN32_WINNT >= _WIN32_WINNT_WIN8 ExInitializeNPagedLookasideList(&DokanIrpEntryLookasideList, NULL, NULL, POOL_NX_ALLOCATION, sizeof(IRP_ENTRY), TAG, 0); #else ExInitializeNPagedLookasideList(&DokanIrpEntryLookasideList, NULL, NULL, 0, sizeof(IRP_ENTRY), TAG, 0); #endif #if _WIN32_WINNT < 0x0501 RtlInitUnicodeString(&functionName, L"FsRtlTeardownPerStreamContexts"); DokanFsRtlTeardownPerStreamContexts = MmGetSystemRoutineAddress(&functionName); #endif RtlZeroMemory(&filterCallbacks, sizeof(FS_FILTER_CALLBACKS)); // only be used by filter driver? filterCallbacks.SizeOfFsFilterCallbacks = sizeof(FS_FILTER_CALLBACKS); filterCallbacks.PreAcquireForSectionSynchronization = DokanFilterCallbackAcquireForCreateSection; status = FsRtlRegisterFileSystemFilterCallbacks(DriverObject, &filterCallbacks); if (!NT_SUCCESS(status)) { CleanupGlobalDiskDevice(dokanGlobal); ExFreePool(DriverObject->FastIoDispatch); DDbgPrint(" FsRtlRegisterFileSystemFilterCallbacks returned 0x%x\n", status); return status; } if (!DokanLookasideCreate(&g_DokanCCBLookasideList, sizeof(DokanCCB))) { DDbgPrint(" DokanLookasideCreate g_DokanCCBLookasideList failed"); CleanupGlobalDiskDevice(dokanGlobal); ExFreePool(DriverObject->FastIoDispatch); return STATUS_INSUFFICIENT_RESOURCES; } if (!DokanLookasideCreate(&g_DokanFCBLookasideList, sizeof(DokanFCB))) { DDbgPrint(" DokanLookasideCreate g_DokanFCBLookasideList failed"); CleanupGlobalDiskDevice(dokanGlobal); ExFreePool(DriverObject->FastIoDispatch); ExDeleteLookasideListEx(&g_DokanCCBLookasideList); return STATUS_INSUFFICIENT_RESOURCES; } if (!DokanLookasideCreate(&g_DokanEResourceLookasideList, sizeof(ERESOURCE))) { DDbgPrint(" DokanLookasideCreate g_DokanEResourceLookasideList failed"); CleanupGlobalDiskDevice(dokanGlobal); ExFreePool(DriverObject->FastIoDispatch); ExDeleteLookasideListEx(&g_DokanCCBLookasideList); ExDeleteLookasideListEx(&g_DokanFCBLookasideList); return STATUS_INSUFFICIENT_RESOURCES; } DDbgPrint("<== DriverEntry\n"); return (status); }
__drv_mustHoldCriticalRegion NTSTATUS CdQueryDirectory ( __inout PIRP_CONTEXT IrpContext, __inout PIRP Irp, __in PIO_STACK_LOCATION IrpSp, __in PFCB Fcb, __in PCCB Ccb ) /*++ Routine Description: This routine performs the query directory operation. It is responsible for either completing of enqueuing the input Irp. We store the state of the search in the Ccb. Arguments: Irp - Supplies the Irp to process IrpSp - Stack location for this Irp. Fcb - Fcb for this directory. Ccb - Ccb for this directory open. Return Value: NTSTATUS - The return status for the operation --*/ { NTSTATUS Status = STATUS_SUCCESS; ULONG Information = 0; ULONG LastEntry = 0; ULONG NextEntry = 0; ULONG FileNameBytes; ULONG SeparatorBytes; ULONG VersionStringBytes; FILE_ENUM_CONTEXT FileContext; PDIRENT ThisDirent = NULL; BOOLEAN InitialQuery; BOOLEAN ReturnNextEntry = FALSE; BOOLEAN ReturnSingleEntry; BOOLEAN Found; BOOLEAN DoCcbUpdate = FALSE; PCHAR UserBuffer; ULONG BytesRemainingInBuffer; ULONG BaseLength; PFILE_BOTH_DIR_INFORMATION DirInfo = NULL; PFILE_NAMES_INFORMATION NamesInfo; PFILE_ID_FULL_DIR_INFORMATION IdFullDirInfo; PFILE_ID_BOTH_DIR_INFORMATION IdBothDirInfo; PAGED_CODE(); // // Check if we support this search mode. Also remember the size of the base part of // each of these structures. // switch (IrpSp->Parameters.QueryDirectory.FileInformationClass) { case FileDirectoryInformation: BaseLength = FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[0] ); break; case FileFullDirectoryInformation: BaseLength = FIELD_OFFSET( FILE_FULL_DIR_INFORMATION, FileName[0] ); break; case FileIdFullDirectoryInformation: BaseLength = FIELD_OFFSET( FILE_ID_FULL_DIR_INFORMATION, FileName[0] ); break; case FileNamesInformation: BaseLength = FIELD_OFFSET( FILE_NAMES_INFORMATION, FileName[0] ); break; case FileBothDirectoryInformation: BaseLength = FIELD_OFFSET( FILE_BOTH_DIR_INFORMATION, FileName[0] ); break; case FileIdBothDirectoryInformation: BaseLength = FIELD_OFFSET( FILE_ID_BOTH_DIR_INFORMATION, FileName[0] ); break; default: CdCompleteRequest( IrpContext, Irp, STATUS_INVALID_INFO_CLASS ); return STATUS_INVALID_INFO_CLASS; } // // Get the user buffer. // CdMapUserBuffer( IrpContext, &UserBuffer); // // Initialize our search context. // CdInitializeFileContext( IrpContext, &FileContext ); // // Acquire the directory. // CdAcquireFileShared( IrpContext, Fcb ); // // Use a try-finally to facilitate cleanup. // try { // // Verify the Fcb is still good. // CdVerifyFcbOperation( IrpContext, Fcb ); // // Start by getting the initial state for the enumeration. This will set up the Ccb with // the initial search parameters and let us know the starting offset in the directory // to search. // CdInitializeEnumeration( IrpContext, IrpSp, Fcb, Ccb, &FileContext, &ReturnNextEntry, &ReturnSingleEntry, &InitialQuery ); // // The current dirent is stored in the InitialDirent field. We capture // this here so that we have a valid restart point even if we don't // find a single entry. // ThisDirent = &FileContext.InitialDirent->Dirent; // // At this point we are about to enter our query loop. We have // determined the index into the directory file to begin the // search. LastEntry and NextEntry are used to index into the user // buffer. LastEntry is the last entry we've added, NextEntry is // current one we're working on. If NextEntry is non-zero, then // at least one entry was added. // while (TRUE) { // // If the user had requested only a single match and we have // returned that, then we stop at this point. We update the Ccb with // the status based on the last entry returned. // if ((NextEntry != 0) && ReturnSingleEntry) { DoCcbUpdate = TRUE; try_leave( Status ); } // // We try to locate the next matching dirent. Our search if based on a starting // dirent offset, whether we should return the current or next entry, whether // we should be doing a short name search and finally whether we should be // checking for a version match. // Found = CdEnumerateIndex( IrpContext, Ccb, &FileContext, ReturnNextEntry ); // // Initialize the value for the next search. // ReturnNextEntry = TRUE; // // If we didn't receive a dirent, then we are at the end of the // directory. If we have returned any files, we exit with // success, otherwise we return STATUS_NO_MORE_FILES. // if (!Found) { if (NextEntry == 0) { Status = STATUS_NO_MORE_FILES; if (InitialQuery) { Status = STATUS_NO_SUCH_FILE; } } DoCcbUpdate = TRUE; try_leave( Status ); } // // Remember the dirent for the file we just found. // ThisDirent = &FileContext.InitialDirent->Dirent; // // Here are the rules concerning filling up the buffer: // // 1. The Io system garentees that there will always be // enough room for at least one base record. // // 2. If the full first record (including file name) cannot // fit, as much of the name as possible is copied and // STATUS_BUFFER_OVERFLOW is returned. // // 3. If a subsequent record cannot completely fit into the // buffer, none of it (as in 0 bytes) is copied, and // STATUS_SUCCESS is returned. A subsequent query will // pick up with this record. // // // Let's compute the number of bytes we need to transfer the current entry. // SeparatorBytes = VersionStringBytes = 0; // // We can look directly at the dirent that we found. // FileNameBytes = ThisDirent->CdFileName.FileName.Length; // // Compute the number of bytes for the version string if // we will return this. Allow directories with illegal ";". // if (((Ccb->SearchExpression.VersionString.Length != 0) || (FlagOn(ThisDirent->DirentFlags, CD_ATTRIBUTE_DIRECTORY))) && (ThisDirent->CdFileName.VersionString.Length != 0)) { SeparatorBytes = 2; VersionStringBytes = ThisDirent->CdFileName.VersionString.Length; } // // If the slot for the next entry would be beyond the length of the // user's buffer just exit (we know we've returned at least one entry // already). This will happen when we align the pointer past the end. // if (NextEntry > IrpSp->Parameters.QueryDirectory.Length) { ReturnNextEntry = FALSE; DoCcbUpdate = TRUE; try_leave( Status = STATUS_SUCCESS ); } // // Compute the number of bytes remaining in the buffer. Round this // down to a WCHAR boundary so we can copy full characters. // BytesRemainingInBuffer = IrpSp->Parameters.QueryDirectory.Length - NextEntry; ClearFlag( BytesRemainingInBuffer, 1 ); // // If this won't fit and we have returned a previous entry then just // return STATUS_SUCCESS. // if ((BaseLength + FileNameBytes + SeparatorBytes + VersionStringBytes) > BytesRemainingInBuffer) { // // If we already found an entry then just exit. // if (NextEntry != 0) { ReturnNextEntry = FALSE; DoCcbUpdate = TRUE; try_leave( Status = STATUS_SUCCESS ); } // // Don't even try to return the version string if it doesn't all fit. // Reduce the FileNameBytes to just fit in the buffer. // if ((BaseLength + FileNameBytes) > BytesRemainingInBuffer) { FileNameBytes = BytesRemainingInBuffer - BaseLength; } // // Don't return any version string bytes. // VersionStringBytes = SeparatorBytes = 0; // // Use a status code of STATUS_BUFFER_OVERFLOW. Also set // ReturnSingleEntry so that we will exit the loop at the top. // Status = STATUS_BUFFER_OVERFLOW; ReturnSingleEntry = TRUE; } // // Protect access to the user buffer with an exception handler. // Since (at our request) IO doesn't buffer these requests, we have // to guard against a user messing with the page protection and other // such trickery. // try { // // Zero and initialize the base part of the current entry. // RtlZeroMemory( Add2Ptr( UserBuffer, NextEntry, PVOID ), BaseLength ); // // Now we have an entry to return to our caller. // We'll case on the type of information requested and fill up // the user buffer if everything fits. // switch (IrpSp->Parameters.QueryDirectory.FileInformationClass) { case FileBothDirectoryInformation: case FileFullDirectoryInformation: case FileIdBothDirectoryInformation: case FileIdFullDirectoryInformation: case FileDirectoryInformation: DirInfo = Add2Ptr( UserBuffer, NextEntry, PFILE_BOTH_DIR_INFORMATION ); // // Use the create time for all the time stamps. // CdConvertCdTimeToNtTime( IrpContext, FileContext.InitialDirent->Dirent.CdTime, &DirInfo->CreationTime ); DirInfo->LastWriteTime = DirInfo->ChangeTime = DirInfo->CreationTime; // // Set the attributes and sizes separately for directories and // files. // if (FlagOn( ThisDirent->DirentFlags, CD_ATTRIBUTE_DIRECTORY )) { DirInfo->EndOfFile.QuadPart = DirInfo->AllocationSize.QuadPart = 0; SetFlag( DirInfo->FileAttributes, FILE_ATTRIBUTE_DIRECTORY); } else { DirInfo->EndOfFile.QuadPart = FileContext.FileSize; DirInfo->AllocationSize.QuadPart = LlSectorAlign( FileContext.FileSize ); SetFlag( DirInfo->FileAttributes, FILE_ATTRIBUTE_READONLY); } if (FlagOn( ThisDirent->DirentFlags, CD_ATTRIBUTE_HIDDEN )) { SetFlag( DirInfo->FileAttributes, FILE_ATTRIBUTE_HIDDEN ); } DirInfo->FileIndex = ThisDirent->DirentOffset; DirInfo->FileNameLength = FileNameBytes + SeparatorBytes + VersionStringBytes; break; case FileNamesInformation: NamesInfo = Add2Ptr( UserBuffer, NextEntry, PFILE_NAMES_INFORMATION ); NamesInfo->FileIndex = ThisDirent->DirentOffset; NamesInfo->FileNameLength = FileNameBytes + SeparatorBytes + VersionStringBytes; break; } // // Fill in the FileId // switch (IrpSp->Parameters.QueryDirectory.FileInformationClass) { case FileIdBothDirectoryInformation: IdBothDirInfo = Add2Ptr( UserBuffer, NextEntry, PFILE_ID_BOTH_DIR_INFORMATION ); CdSetFidFromParentAndDirent( IdBothDirInfo->FileId, Fcb, ThisDirent ); break; case FileIdFullDirectoryInformation: IdFullDirInfo = Add2Ptr( UserBuffer, NextEntry, PFILE_ID_FULL_DIR_INFORMATION ); CdSetFidFromParentAndDirent( IdFullDirInfo->FileId, Fcb, ThisDirent ); break; default: break; } // // Now copy as much of the name as possible. We also may have a version // string to copy. // if (FileNameBytes != 0) { // // This is a Unicode name, we can copy the bytes directly. // RtlCopyMemory( Add2Ptr( UserBuffer, NextEntry + BaseLength, PVOID ), ThisDirent->CdFileName.FileName.Buffer, FileNameBytes ); if (SeparatorBytes != 0) { *(Add2Ptr( UserBuffer, NextEntry + BaseLength + FileNameBytes, PWCHAR )) = L';'; if (VersionStringBytes != 0) { RtlCopyMemory( Add2Ptr( UserBuffer, NextEntry + BaseLength + FileNameBytes + sizeof( WCHAR ), PVOID ), ThisDirent->CdFileName.VersionString.Buffer, VersionStringBytes ); } } } // // Fill in the short name if we got STATUS_SUCCESS. The short name // may already be in the file context. Otherwise we will check // whether the long name is 8.3. Special case the self and parent // directory names. // if ((Status == STATUS_SUCCESS) && (IrpSp->Parameters.QueryDirectory.FileInformationClass == FileBothDirectoryInformation || IrpSp->Parameters.QueryDirectory.FileInformationClass == FileIdBothDirectoryInformation) && (Ccb->SearchExpression.VersionString.Length == 0) && !FlagOn( ThisDirent->Flags, DIRENT_FLAG_CONSTANT_ENTRY )) { // // If we already have the short name then copy into the user's buffer. // if (FileContext.ShortName.FileName.Length != 0) { RtlCopyMemory( DirInfo->ShortName, FileContext.ShortName.FileName.Buffer, FileContext.ShortName.FileName.Length ); DirInfo->ShortNameLength = (CCHAR) FileContext.ShortName.FileName.Length; // // If the short name length is currently zero then check if // the long name is not 8.3. We can copy the short name in // unicode form directly into the caller's buffer. // } else { if (!CdIs8dot3Name( IrpContext, ThisDirent->CdFileName.FileName )) { CdGenerate8dot3Name( IrpContext, &ThisDirent->CdCaseFileName.FileName, ThisDirent->DirentOffset, DirInfo->ShortName, &FileContext.ShortName.FileName.Length ); DirInfo->ShortNameLength = (CCHAR) FileContext.ShortName.FileName.Length; } } } // // Sum the total number of bytes for the information field. // FileNameBytes += SeparatorBytes + VersionStringBytes; // // Update the information with the number of bytes stored in the // buffer. We quad-align the existing buffer to add any necessary // pad bytes. // Information = NextEntry + BaseLength + FileNameBytes; // // Go back to the previous entry and fill in the update to this entry. // *(Add2Ptr( UserBuffer, LastEntry, PULONG )) = NextEntry - LastEntry; // // Set up our variables for the next dirent. // InitialQuery = FALSE; LastEntry = NextEntry; NextEntry = QuadAlign( Information ); } except (EXCEPTION_EXECUTE_HANDLER) { // // We had a problem filling in the user's buffer, so stop and // fail this request. This is the only reason any exception // would have occured at this level. // Information = 0; try_leave( Status = GetExceptionCode()); } } DoCcbUpdate = TRUE; } finally { // // Cleanup our search context - *before* aquiring the FCB mutex exclusive, // else can block on threads in cdcreateinternalstream/purge which // hold the FCB but are waiting for all maps in this stream to be released. // CdCleanupFileContext( IrpContext, &FileContext ); // // Now we can safely aqure the FCB mutex if we need to. // if (DoCcbUpdate && !NT_ERROR( Status )) { // // Update the Ccb to show the current state of the enumeration. // CdLockFcb( IrpContext, Fcb ); Ccb->CurrentDirentOffset = ThisDirent->DirentOffset; ClearFlag( Ccb->Flags, CCB_FLAG_ENUM_RETURN_NEXT ); if (ReturnNextEntry) { SetFlag( Ccb->Flags, CCB_FLAG_ENUM_RETURN_NEXT ); } CdUnlockFcb( IrpContext, Fcb ); } // // Release the Fcb. // CdReleaseFile( IrpContext, Fcb ); } // // Complete the request here. // Irp->IoStatus.Information = Information; CdCompleteRequest( IrpContext, Irp, Status ); return Status; }
RT_C_DECLS_END #ifdef ALLOC_PRAGMA # pragma alloc_text(INIT, vgdrvNt4CreateDevice) # pragma alloc_text(INIT, vgdrvNt4FindPciDevice) #endif /** * Legacy helper function to create the device object. * * @returns NT status code. * * @param pDrvObj The driver object. * @param pRegPath The driver registry path. */ NTSTATUS vgdrvNt4CreateDevice(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath) { Log(("vgdrvNt4CreateDevice: pDrvObj=%p, pRegPath=%p\n", pDrvObj, pRegPath)); /* * Find our virtual PCI device */ ULONG uBusNumber; PCI_SLOT_NUMBER SlotNumber; NTSTATUS rc = vgdrvNt4FindPciDevice(&uBusNumber, &SlotNumber); if (NT_ERROR(rc)) { Log(("vgdrvNt4CreateDevice: Device not found!\n")); return rc; } /* * Create device. */ UNICODE_STRING szDevName; RtlInitUnicodeString(&szDevName, VBOXGUEST_DEVICE_NAME_NT); PDEVICE_OBJECT pDeviceObject = NULL; rc = IoCreateDevice(pDrvObj, sizeof(VBOXGUESTDEVEXTWIN), &szDevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject); if (NT_SUCCESS(rc)) { Log(("vgdrvNt4CreateDevice: Device created\n")); UNICODE_STRING DosName; RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS); rc = IoCreateSymbolicLink(&DosName, &szDevName); if (NT_SUCCESS(rc)) { Log(("vgdrvNt4CreateDevice: Symlink created\n")); /* * Setup the device extension. */ Log(("vgdrvNt4CreateDevice: Setting up device extension ...\n")); PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDeviceObject->DeviceExtension; RT_ZERO(*pDevExt); Log(("vgdrvNt4CreateDevice: Device extension created\n")); /* Store a reference to ourself. */ pDevExt->pDeviceObject = pDeviceObject; /* Store bus and slot number we've queried before. */ pDevExt->busNumber = uBusNumber; pDevExt->slotNumber = SlotNumber.u.AsULONG; #ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION rc = hlpRegisterBugCheckCallback(pDevExt); #endif /* Do the actual VBox init ... */ if (NT_SUCCESS(rc)) { rc = vgdrvNtInit(pDrvObj, pDeviceObject, pRegPath); if (NT_SUCCESS(rc)) { Log(("vgdrvNt4CreateDevice: Returning rc = 0x%x (succcess)\n", rc)); return rc; } /* bail out */ } IoDeleteSymbolicLink(&DosName); } else Log(("vgdrvNt4CreateDevice: IoCreateSymbolicLink failed with rc = %#x\n", rc)); IoDeleteDevice(pDeviceObject); } else Log(("vgdrvNt4CreateDevice: IoCreateDevice failed with rc = %#x\n", rc)); Log(("vgdrvNt4CreateDevice: Returning rc = 0x%x\n", rc)); return rc; }
NTSTATUS vboxguestwinInit(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj, PUNICODE_STRING pRegPath) #endif { PVBOXGUESTDEVEXT pDevExt = (PVBOXGUESTDEVEXT)pDevObj->DeviceExtension; #ifndef TARGET_NT4 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); #endif Log(("VBoxGuest::vboxguestwinInit\n")); int rc = STATUS_SUCCESS; #ifdef TARGET_NT4 /* * Let's have a look at what our PCI adapter offers. */ Log(("VBoxGuest::vboxguestwinInit: Starting to scan PCI resources of VBoxGuest ...\n")); /* Assign the PCI resources. */ PCM_RESOURCE_LIST pResourceList = NULL; UNICODE_STRING classNameString; RtlInitUnicodeString(&classNameString, L"VBoxGuestAdapter"); rc = HalAssignSlotResources(pRegPath, &classNameString, pDrvObj, pDevObj, PCIBus, pDevExt->win.s.busNumber, pDevExt->win.s.slotNumber, &pResourceList); if (pResourceList && pResourceList->Count > 0) vboxguestwinShowDeviceResources(&pResourceList->List[0].PartialResourceList); if (NT_SUCCESS(rc)) rc = vboxguestwinScanPCIResourceList(pResourceList, pDevExt); #else if (pStack->Parameters.StartDevice.AllocatedResources->Count > 0) vboxguestwinShowDeviceResources(&pStack->Parameters.StartDevice.AllocatedResources->List[0].PartialResourceList); if (NT_SUCCESS(rc)) rc = vboxguestwinScanPCIResourceList(pStack->Parameters.StartDevice.AllocatedResourcesTranslated, pDevExt); #endif if (NT_SUCCESS(rc)) { /* * Map physical address of VMMDev memory into MMIO region * and init the common device extension bits. */ void *pvMMIOBase = NULL; uint32_t cbMMIO = 0; rc = vboxguestwinMapVMMDevMemory(pDevExt, pDevExt->win.s.vmmDevPhysMemoryAddress, pDevExt->win.s.vmmDevPhysMemoryLength, &pvMMIOBase, &cbMMIO); if (NT_SUCCESS(rc)) { pDevExt->pVMMDevMemory = (VMMDevMemory *)pvMMIOBase; Log(("VBoxGuest::vboxguestwinInit: pvMMIOBase = 0x%p, pDevExt = 0x%p, pDevExt->pVMMDevMemory = 0x%p\n", pvMMIOBase, pDevExt, pDevExt ? pDevExt->pVMMDevMemory : NULL)); int vrc = VBoxGuestInitDevExt(pDevExt, pDevExt->IOPortBase, pvMMIOBase, cbMMIO, vboxguestwinVersionToOSType(g_winVersion), VMMDEV_EVENT_MOUSE_POSITION_CHANGED); if (RT_FAILURE(vrc)) { Log(("VBoxGuest::vboxguestwinInit: Could not init device extension, rc = %Rrc!\n", vrc)); rc = STATUS_DEVICE_CONFIGURATION_ERROR; } } else Log(("VBoxGuest::vboxguestwinInit: Could not map physical address of VMMDev, rc = 0x%x!\n", rc)); } if (NT_SUCCESS(rc)) { int vrc = VbglGRAlloc((VMMDevRequestHeader **)&pDevExt->win.s.pPowerStateRequest, sizeof (VMMDevPowerStateRequest), VMMDevReq_SetPowerStatus); if (RT_FAILURE(vrc)) { Log(("VBoxGuest::vboxguestwinInit: Alloc for pPowerStateRequest failed, rc = %Rrc\n", vrc)); rc = STATUS_UNSUCCESSFUL; } } if (NT_SUCCESS(rc)) { /* * Register DPC and ISR. */ Log(("VBoxGuest::vboxguestwinInit: Initializing DPC/ISR ...\n")); IoInitializeDpcRequest(pDevExt->win.s.pDeviceObject, vboxguestwinDpcHandler); #ifdef TARGET_NT4 ULONG uInterruptVector; KIRQL irqLevel; /* Get an interrupt vector. */ /* Only proceed if the device provides an interrupt. */ if ( pDevExt->win.s.interruptLevel || pDevExt->win.s.interruptVector) { Log(("VBoxGuest::vboxguestwinInit: Getting interrupt vector (HAL): Bus: %u, IRQL: %u, Vector: %u\n", pDevExt->win.s.busNumber, pDevExt->win.s.interruptLevel, pDevExt->win.s.interruptVector)); uInterruptVector = HalGetInterruptVector(PCIBus, pDevExt->win.s.busNumber, pDevExt->win.s.interruptLevel, pDevExt->win.s.interruptVector, &irqLevel, &pDevExt->win.s.interruptAffinity); Log(("VBoxGuest::vboxguestwinInit: HalGetInterruptVector returns vector %u\n", uInterruptVector)); if (uInterruptVector == 0) Log(("VBoxGuest::vboxguestwinInit: No interrupt vector found!\n")); } else Log(("VBoxGuest::vboxguestwinInit: Device does not provide an interrupt!\n")); #endif if (pDevExt->win.s.interruptVector) { Log(("VBoxGuest::vboxguestwinInit: Connecting interrupt ...\n")); rc = IoConnectInterrupt(&pDevExt->win.s.pInterruptObject, /* Out: interrupt object. */ (PKSERVICE_ROUTINE)vboxguestwinIsrHandler, /* Our ISR handler. */ pDevExt, /* Device context. */ NULL, /* Optional spinlock. */ #ifdef TARGET_NT4 uInterruptVector, /* Interrupt vector. */ irqLevel, /* Interrupt level. */ irqLevel, /* Interrupt level. */ #else pDevExt->win.s.interruptVector, /* Interrupt vector. */ (KIRQL)pDevExt->win.s.interruptLevel, /* Interrupt level. */ (KIRQL)pDevExt->win.s.interruptLevel, /* Interrupt level. */ #endif pDevExt->win.s.interruptMode, /* LevelSensitive or Latched. */ TRUE, /* Shareable interrupt. */ pDevExt->win.s.interruptAffinity, /* CPU affinity. */ FALSE); /* Don't save FPU stack. */ if (NT_ERROR(rc)) Log(("VBoxGuest::vboxguestwinInit: Could not connect interrupt, rc = 0x%x\n", rc)); } else Log(("VBoxGuest::vboxguestwinInit: No interrupt vector found!\n")); } #ifdef VBOX_WITH_HGCM Log(("VBoxGuest::vboxguestwinInit: Allocating kernel session data ...\n")); int vrc = VBoxGuestCreateKernelSession(pDevExt, &pDevExt->win.s.pKernelSession); if (RT_FAILURE(vrc)) { Log(("VBoxGuest::vboxguestwinInit: Failed to allocated kernel session data! rc = %Rrc\n", rc)); rc = STATUS_UNSUCCESSFUL; } #endif if (RT_SUCCESS(rc)) { ULONG ulValue = 0; NTSTATUS s = vboxguestwinRegistryReadDWORD(RTL_REGISTRY_SERVICES, L"VBoxGuest", L"LoggingEnabled", &ulValue); if (NT_SUCCESS(s)) { pDevExt->fLoggingEnabled = ulValue >= 0xFF; if (pDevExt->fLoggingEnabled) Log(("Logging to release log enabled (0x%x)", ulValue)); } /* Ready to rumble! */ Log(("VBoxGuest::vboxguestwinInit: Device is ready!\n")); VBOXGUEST_UPDATE_DEVSTATE(pDevExt, WORKING); } else { pDevExt->win.s.pInterruptObject = NULL; } Log(("VBoxGuest::vboxguestwinInit: Returned with rc = 0x%x\n", rc)); return rc; }
/** * PnP Request handler. * * @param pDevObj Device object. * @param pIrp Request packet. */ NTSTATUS vbgdNtPnP(PDEVICE_OBJECT pDevObj, PIRP pIrp) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); #ifdef LOG_ENABLED static char *s_apszFnctName[] = { "IRP_MN_START_DEVICE", "IRP_MN_QUERY_REMOVE_DEVICE", "IRP_MN_REMOVE_DEVICE", "IRP_MN_CANCEL_REMOVE_DEVICE", "IRP_MN_STOP_DEVICE", "IRP_MN_QUERY_STOP_DEVICE", "IRP_MN_CANCEL_STOP_DEVICE", "IRP_MN_QUERY_DEVICE_RELATIONS", "IRP_MN_QUERY_INTERFACE", "IRP_MN_QUERY_CAPABILITIES", "IRP_MN_QUERY_RESOURCES", "IRP_MN_QUERY_RESOURCE_REQUIREMENTS", "IRP_MN_QUERY_DEVICE_TEXT", "IRP_MN_FILTER_RESOURCE_REQUIREMENTS", "IRP_MN_0xE", "IRP_MN_READ_CONFIG", "IRP_MN_WRITE_CONFIG", "IRP_MN_EJECT", "IRP_MN_SET_LOCK", "IRP_MN_QUERY_ID", "IRP_MN_QUERY_PNP_DEVICE_STATE", "IRP_MN_QUERY_BUS_INFORMATION", "IRP_MN_DEVICE_USAGE_NOTIFICATION", "IRP_MN_SURPRISE_REMOVAL", }; Log(("VBoxGuest::vbgdNtGuestPnp: MinorFunction: %s\n", pStack->MinorFunction < RT_ELEMENTS(s_apszFnctName) ? s_apszFnctName[pStack->MinorFunction] : "Unknown")); #endif NTSTATUS rc = STATUS_SUCCESS; switch (pStack->MinorFunction) { case IRP_MN_START_DEVICE: { Log(("VBoxGuest::vbgdNtVBoxGuestPnP: START_DEVICE\n")); /* This must be handled first by the lower driver. */ rc = vbgdNtSendIrpSynchronously(pDevExt->pNextLowerDriver, pIrp, TRUE); if ( NT_SUCCESS(rc) && NT_SUCCESS(pIrp->IoStatus.Status)) { Log(("VBoxGuest::vbgdNtVBoxGuestPnP: START_DEVICE: pStack->Parameters.StartDevice.AllocatedResources = %p\n", pStack->Parameters.StartDevice.AllocatedResources)); if (!pStack->Parameters.StartDevice.AllocatedResources) { Log(("VBoxGuest::vbgdNtVBoxGuestPnP: START_DEVICE: No resources, pDevExt = %p, nextLowerDriver = %p!\n", pDevExt, pDevExt ? pDevExt->pNextLowerDriver : NULL)); rc = STATUS_UNSUCCESSFUL; } else { rc = vbgdNtInit(pDevObj, pIrp); } } if (NT_ERROR(rc)) { Log(("VBoxGuest::vbgdNtGuestPnp: START_DEVICE: Error: rc = 0x%x\n", rc)); /* Need to unmap memory in case of errors ... */ vbgdNtUnmapVMMDevMemory(pDevExt); } break; } case IRP_MN_CANCEL_REMOVE_DEVICE: { Log(("VBoxGuest::vbgdNtVBoxGuestPnP: CANCEL_REMOVE_DEVICE\n")); /* This must be handled first by the lower driver. */ rc = vbgdNtSendIrpSynchronously(pDevExt->pNextLowerDriver, pIrp, TRUE); if (NT_SUCCESS(rc) && pDevExt->devState == PENDINGREMOVE) { /* Return to the state prior to receiving the IRP_MN_QUERY_REMOVE_DEVICE request. */ pDevExt->devState = pDevExt->prevDevState; } /* Complete the IRP. */ break; } case IRP_MN_SURPRISE_REMOVAL: { Log(("VBoxGuest::vbgdNtVBoxGuestPnP: IRP_MN_SURPRISE_REMOVAL\n")); VBOXGUEST_UPDATE_DEVSTATE(pDevExt, SURPRISEREMOVED); /* Do nothing here actually. Cleanup is done in IRP_MN_REMOVE_DEVICE. * This request is not expected for VBoxGuest. */ LogRel(("VBoxGuest: unexpected device removal\n")); /* Pass to the lower driver. */ pIrp->IoStatus.Status = STATUS_SUCCESS; IoSkipCurrentIrpStackLocation(pIrp); rc = IoCallDriver(pDevExt->pNextLowerDriver, pIrp); /* Do not complete the IRP. */ return rc; } case IRP_MN_QUERY_REMOVE_DEVICE: { Log(("VBoxGuest::vbgdNtVBoxGuestPnP: QUERY_REMOVE_DEVICE\n")); #ifdef VBOX_REBOOT_ON_UNINSTALL Log(("VBoxGuest::vbgdNtGuestPnp: QUERY_REMOVE_DEVICE: Device cannot be removed without a reboot.\n")); rc = STATUS_UNSUCCESSFUL; #endif if (NT_SUCCESS(rc)) { VBOXGUEST_UPDATE_DEVSTATE(pDevExt, PENDINGREMOVE); /* This IRP passed down to lower driver. */ pIrp->IoStatus.Status = STATUS_SUCCESS; IoSkipCurrentIrpStackLocation(pIrp); rc = IoCallDriver(pDevExt->pNextLowerDriver, pIrp); Log(("VBoxGuest::vbgdNtGuestPnp: QUERY_REMOVE_DEVICE: Next lower driver replied rc = 0x%x\n", rc)); /* we must not do anything the IRP after doing IoSkip & CallDriver * since the driver below us will complete (or already have completed) the IRP. * I.e. just return the status we got from IoCallDriver */ return rc; } /* Complete the IRP on failure. */ break; } case IRP_MN_REMOVE_DEVICE: { Log(("VBoxGuest::vbgdNtVBoxGuestPnP: REMOVE_DEVICE\n")); VBOXGUEST_UPDATE_DEVSTATE(pDevExt, REMOVED); /* Free hardware resources. */ /** @todo this should actually free I/O ports, interrupts, etc. * Update/bird: vbgdNtCleanup actually does that... So, what's there to do? */ rc = vbgdNtCleanup(pDevObj); Log(("VBoxGuest::vbgdNtGuestPnp: REMOVE_DEVICE: vbgdNtCleanup rc = 0x%08X\n", rc)); /* * We need to send the remove down the stack before we detach, * but we don't need to wait for the completion of this operation * (and to register a completion routine). */ pIrp->IoStatus.Status = STATUS_SUCCESS; IoSkipCurrentIrpStackLocation(pIrp); rc = IoCallDriver(pDevExt->pNextLowerDriver, pIrp); Log(("VBoxGuest::vbgdNtGuestPnp: REMOVE_DEVICE: Next lower driver replied rc = 0x%x\n", rc)); IoDetachDevice(pDevExt->pNextLowerDriver); Log(("VBoxGuest::vbgdNtGuestPnp: REMOVE_DEVICE: Removing device ...\n")); /* Destroy device extension and clean up everything else. */ VbgdCommonDeleteDevExt(&pDevExt->Core); /* Remove DOS device + symbolic link. */ UNICODE_STRING win32Name; RtlInitUnicodeString(&win32Name, VBOXGUEST_DEVICE_NAME_DOS); IoDeleteSymbolicLink(&win32Name); Log(("VBoxGuest::vbgdNtGuestPnp: REMOVE_DEVICE: Deleting device ...\n")); /* Last action: Delete our device! pDevObj is *not* failed * anymore after this call! */ IoDeleteDevice(pDevObj); Log(("VBoxGuest::vbgdNtGuestPnp: REMOVE_DEVICE: Device removed!\n")); /* Propagating rc from IoCallDriver. */ return rc; /* Make sure that we don't do anything below here anymore! */ } case IRP_MN_CANCEL_STOP_DEVICE: { Log(("VBoxGuest::vbgdNtVBoxGuestPnP: CANCEL_STOP_DEVICE\n")); /* This must be handled first by the lower driver. */ rc = vbgdNtSendIrpSynchronously(pDevExt->pNextLowerDriver, pIrp, TRUE); if (NT_SUCCESS(rc) && pDevExt->devState == PENDINGSTOP) { /* Return to the state prior to receiving the IRP_MN_QUERY_STOP_DEVICE request. */ pDevExt->devState = pDevExt->prevDevState; } /* Complete the IRP. */ break; } case IRP_MN_QUERY_STOP_DEVICE: { Log(("VBoxGuest::vbgdNtVBoxGuestPnP: QUERY_STOP_DEVICE\n")); #ifdef VBOX_REBOOT_ON_UNINSTALL Log(("VBoxGuest::vbgdNtGuestPnp: QUERY_STOP_DEVICE: Device cannot be stopped without a reboot!\n")); pIrp->IoStatus.Status = STATUS_UNSUCCESSFUL; #endif if (NT_SUCCESS(rc)) { VBOXGUEST_UPDATE_DEVSTATE(pDevExt, PENDINGSTOP); /* This IRP passed down to lower driver. */ pIrp->IoStatus.Status = STATUS_SUCCESS; IoSkipCurrentIrpStackLocation(pIrp); rc = IoCallDriver(pDevExt->pNextLowerDriver, pIrp); Log(("VBoxGuest::vbgdNtGuestPnp: QUERY_STOP_DEVICE: Next lower driver replied rc = 0x%x\n", rc)); /* we must not do anything with the IRP after doing IoSkip & CallDriver * since the driver below us will complete (or already have completed) the IRP. * I.e. just return the status we got from IoCallDriver */ return rc; } /* Complete the IRP on failure. */ break; } case IRP_MN_STOP_DEVICE: { Log(("VBoxGuest::vbgdNtVBoxGuestPnP: STOP_DEVICE\n")); VBOXGUEST_UPDATE_DEVSTATE(pDevExt, STOPPED); /* Free hardware resources. */ /** @todo this should actually free I/O ports, interrupts, etc. * Update/bird: vbgdNtCleanup actually does that... So, what's there to do? */ rc = vbgdNtCleanup(pDevObj); Log(("VBoxGuest::vbgdNtGuestPnp: STOP_DEVICE: cleaning up, rc = 0x%x\n", rc)); /* Pass to the lower driver. */ pIrp->IoStatus.Status = STATUS_SUCCESS; IoSkipCurrentIrpStackLocation(pIrp); rc = IoCallDriver(pDevExt->pNextLowerDriver, pIrp); Log(("VBoxGuest::vbgdNtGuestPnp: STOP_DEVICE: Next lower driver replied rc = 0x%x\n", rc)); return rc; } default: { IoSkipCurrentIrpStackLocation(pIrp); rc = IoCallDriver(pDevExt->pNextLowerDriver, pIrp); return rc; } } pIrp->IoStatus.Status = rc; IoCompleteRequest(pIrp, IO_NO_INCREMENT); Log(("VBoxGuest::vbgdNtGuestPnp: Returning with rc = 0x%x\n", rc)); return rc; }
int WSPAPI WSPSend ( SOCKET Handle, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesSent, DWORD iFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, LPWSATHREADID lpThreadId, LPINT lpErrno ) /*++ Routine Description: This routine is used to write outgoing data from one or more buffers on a connection-oriented socket specified by s. It may also be used, however, on connectionless sockets which have a stipulated default peer address established via the WSPConnect() function. For overlapped sockets (created using WSPSocket() with flag WSA_FLAG_OVERLAPPED) this will occur using overlapped I/O, unless both lpOverlapped and lpCompletionRoutine are NULL in which case the socket is treated as a non-overlapped socket. A completion indication will occur (invocation of the completion routine or setting of an event object) when the supplied buffer(s) have been consumed by the transport. If the operation does not complete immediately, the final completion status is retrieved via the completion routine or WSPGetOverlappedResult(). For non-overlapped sockets, the parameters lpOverlapped, lpCompletionRoutine, and lpThreadId are ignored and WSPSend() adopts the regular synchronous semantics. Data is copied from the supplied buffer(s) into the transport's buffer. If the socket is non-blocking and stream- oriented, and there is not sufficient space in the transport's buffer, WSPSend() will return with only part of the supplied buffers having been consumed. Given the same buffer situation and a blocking socket, WSPSend() will block until all of the supplied buffer contents have been consumed. The array of WSABUF structures pointed to by the lpBuffers parameter is transient. If this operation completes in an overlapped manner, it is the service provider's responsibility to capture these WSABUF structures before returning from this call. This enables applications to build stack- based WSABUF arrays. For message-oriented sockets, care must be taken not to exceed the maximum message size of the underlying provider, which can be obtained by getting the value of socket option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted. Note that the successful completion of a WSPSend() does not indicate that the data was successfully delivered. dwFlags may be used to influence the behavior of the function invocation beyond the options specified for the associated socket. That is, the semantics of this routine are determined by the socket options and the dwFlags parameter. The latter is constructed by or-ing any of the following values: MSG_DONTROUTE - Specifies that the data should not be subject to routing. A WinSock service provider may choose to ignore this flag. MSG_OOB - Send out-of-band data (stream style socket such as SOCK_STREAM only). MSG_PARTIAL - Specifies that lpBuffers only contains a partial message. Note that the error code WSAEOPNOTSUPP will be returned which do not support partial message transmissions. If an overlapped operation completes immediately, WSPSend() returns a value of zero and the lpNumberOfBytesSent parameter is updated with the number of bytes sent. If the overlapped operation is successfully initiated and will complete later, WSPSend() returns SOCKET_ERROR and indicates error code WSA_IO_PENDING. In this case, lpNumberOfBytesSent is not updated. When the overlapped operation completes the amount of data transferred is indicated either via the cbTransferred parameter in the completion routine (if specified), or via the lpcbTransfer parameter in WSPGetOverlappedResult(). Providers must allow this routine to be called from within the completion routine of a previous WSPRecv(), WSPRecvFrom(), WSPSend() or WSPSendTo() function. However, for a given socket, I/O completion routines may not be nested. This permits time-sensitive data transmissions to occur entirely within a preemptive context. The lpOverlapped parameter must be valid for the duration of the overlapped operation. If multiple I/O operations are simultaneously outstanding, each must reference a separate overlapped structure. The WSAOVERLAPPED structure has the following form: typedef struct _WSAOVERLAPPED { DWORD Internal; // reserved DWORD InternalHigh; // reserved DWORD Offset; // reserved DWORD OffsetHigh; // reserved WSAEVENT hEvent; } WSAOVERLAPPED, FAR * LPWSAOVERLAPPED; If the lpCompletionRoutine parameter is NULL, the service provider signals the hEvent field of lpOverlapped when the overlapped operation completes if it contains a valid event object handle. The WinSock SPI client can use WSPGetOverlappedResult() to wait or poll on the event object. If lpCompletionRoutine is not NULL, the hEvent field is ignored and can be used by the WinSock SPI client to pass context information to the completion routine. It is the service provider's responsibility to arrange for invocation of the client-specified completion routine when the overlapped operation completes. Since the completion routine must be executed in the context of the same thread that initiated the overlapped operation, it cannot be invoked directly from the service provider. The WinSock DLL offers an asynchronous procedure call (APC) mechanism to facilitate invocation of completion routines. A service provider arranges for a function to be executed in the proper thread by calling WPUQueueApc(). Note that this routine must be invoked while in the context of the same process (but not necessarily the same thread) that was used to initiate the overlapped operation. It is the service provider's responsibility to arrange for this process context to be active prior to calling WPUQueueApc(). WPUQueueApc() takes as input parameters a pointer to a WSATHREADID structure (supplied to the provider via the lpThreadId input parameter), a pointer to an APC function to be invoked, and a 32 bit context value that is subsequently passed to the APC function. Because only a single 32-bit context value is available, the APC function cannot itself be the client-specified completion routine. The service provider must instead supply a pointer to its own APC function which uses the supplied context value to access the needed result information for the overlapped operation, and then invokes the client-specified completion routine. The prototype for the client-supplied completion routine is as follows: void CALLBACK CompletionRoutine( IN DWORD dwError, IN DWORD cbTransferred, IN LPWSAOVERLAPPED lpOverlapped, IN DWORD dwFlags ); CompletionRoutine is a placeholder for a client supplied function name. dwError specifies the completion status for the overlapped operation as indicated by lpOverlapped. cbTransferred specifies the number of bytes sent. No flag values are currently defined and the dwFlags value will be zero. This routine does not return a value. The completion routines may be called in any order, not necessarily in the same order the overlapped operations are completed. However, the service provider guarantees to the client that posted buffers are sent in the same order they are supplied. Arguments: s - A descriptor identifying a connected socket. lpBuffers - A pointer to an array of WSABUF structures. Each WSABUF structure contains a pointer to a buffer and the length of the buffer. This array must remain valid for the duration of the send operation. dwBufferCount - The number of WSABUF structures in the lpBuffers array. lpNumberOfBytesSent - A pointer to the number of bytes sent by this call. dwFlags - Specifies the way in which the call is made. lpOverlapped - A pointer to a WSAOVERLAPPED structure. lpCompletionRoutine - A pointer to the completion routine called when the send operation has been completed. lpThreadId - A pointer to a thread ID structure to be used by the provider in a subsequent call to WPUQueueApc(). The provider should store the referenced WSATHREADID structure (not the pointer to same) until after the WPUQueueApc() function returns. lpErrno - A pointer to the error code. Return Value: If no error occurs and the send operation has completed immediately, WSPSend() returns 0. Note that in this case the completion routine, if specified, will have already been queued. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code is available in lpErrno. The error code WSA_IO_PENDING indicates that the overlapped operation has been successfully initiated and that completion will be indicated at a later time. Any other error code indicates that no overlapped operation was initiated and no completion indication will occur. --*/ { NTSTATUS status; PWINSOCK_TLS_DATA tlsData; IO_STATUS_BLOCK localIoStatusBlock; PIO_STATUS_BLOCK ioStatusBlock; int err; AFD_SEND_INFO sendInfo; HANDLE event; PIO_APC_ROUTINE apcRoutine; PVOID apcContext; PSOCKET_INFORMATION socket = NULL; WS_ENTER( "WSPSend", (PVOID)Handle, (PVOID)lpBuffers, (PVOID)dwBufferCount, (PVOID)iFlags ); WS_ASSERT( lpErrno != NULL ); err = SockEnterApi( &tlsData ); if( err != NO_ERROR ) { WS_EXIT( "WSPSend", SOCKET_ERROR, TRUE ); *lpErrno = err; return SOCKET_ERROR; } #ifdef _AFD_SAN_SWITCH_ if (SockSanEnabled) { socket = SockFindAndReferenceSocket( Handle, TRUE ); if ( socket == NULL ) { err = WSAENOTSOCK; goto exit; } if (socket->SanSocket!=NULL) { err = SockSanSend ( socket, lpBuffers, dwBufferCount, lpNumberOfBytesSent, iFlags, lpOverlapped, lpCompletionRoutine, lpThreadId->ThreadHandle); goto exit; } } #endif //_AFD_SAN_SWITCH_ // // Set up AFD_SEND_INFO.TdiFlags; // sendInfo.BufferArray = lpBuffers; sendInfo.BufferCount = dwBufferCount; sendInfo.AfdFlags = 0; sendInfo.TdiFlags = 0; if ( iFlags != 0 ) { // // The legal flags are MSG_OOB, MSG_DONTROUTE and MSG_PARTIAL. // MSG_OOB is not legal on datagram sockets. // if ( ( (iFlags & ~(MSG_OOB | MSG_DONTROUTE | MSG_PARTIAL)) != 0 ) ) { err = WSAEOPNOTSUPP; goto exit; } if ( (iFlags & MSG_OOB) != 0 ) { sendInfo.TdiFlags |= TDI_SEND_EXPEDITED; } if ( (iFlags & MSG_PARTIAL) != 0 ) { sendInfo.TdiFlags |= TDI_SEND_PARTIAL; } } __try { // // Determine the appropriate APC routine & context, event handle, // and IO status block to use for the request. // if( lpOverlapped == NULL ) { // // This a synchronous request, use per-thread event object. // apcRoutine = NULL; apcContext = NULL; event = tlsData->EventHandle; ioStatusBlock = &localIoStatusBlock; } else { if( lpCompletionRoutine == NULL ) { // // No APC, use event object from OVERLAPPED structure. // event = lpOverlapped->hEvent; apcRoutine = NULL; apcContext = ( (ULONG_PTR)event & 1 ) ? NULL : lpOverlapped; } else { // // APC, ignore event object. // event = NULL; apcRoutine = SockIoCompletion; apcContext = lpCompletionRoutine; // // Tell AFD to skip fast IO on this request. // sendInfo.AfdFlags |= AFD_NO_FAST_IO; } // // Use part of the OVERLAPPED structure as our IO_STATUS_BLOCK. // ioStatusBlock = (PIO_STATUS_BLOCK)&lpOverlapped->Internal; // // Tell AFD this is an overlapped operation. // sendInfo.AfdFlags |= AFD_OVERLAPPED; } ioStatusBlock->Status = STATUS_PENDING; } __except (SOCK_EXCEPTION_FILTER()) { err = WSAEFAULT; goto exit; } // // Send the data over the socket. // status = NtDeviceIoControlFile( (HANDLE)Handle, event, apcRoutine, apcContext, ioStatusBlock, IOCTL_AFD_SEND, &sendInfo, sizeof(sendInfo), NULL, 0 ); if ( apcRoutine != NULL && !NT_ERROR(status) ) { tlsData->PendingAPCCount++; InterlockedIncrement( &SockProcessPendingAPCCount ); } // // If this request has no overlapped structure, then wait for // the operation to complete. // if ( status == STATUS_PENDING && lpOverlapped == NULL ) { BOOL success; success = SockWaitForSingleObject( event, Handle, SOCK_CONDITIONALLY_CALL_BLOCKING_HOOK, SOCK_SEND_TIMEOUT ); // // If the wait completed successfully, look in the IO status // block to determine the real status code of the request. If // the wait timed out, then cancel the IO and set up for an // error return. // if ( success ) { status = ioStatusBlock->Status; } else { SockCancelIo( Handle ); status = STATUS_IO_TIMEOUT; } } switch (status) { case STATUS_SUCCESS: break; case STATUS_PENDING: err = WSA_IO_PENDING; goto exit; default: if (!NT_SUCCESS(status) ) { // // Map the NTSTATUS to a WinSock error code. // err = SockNtStatusToSocketError( status ); goto exit; } } // // The request completed immediately, so return the number of // bytes sent to the user. // It is possible that application deallocated lpOverlapped // in another thread if completion port was used to receive // completion indication. We do not want to confuse the // application by returning failure, just pretend that we didn't // know about synchronous completion // __try { *lpNumberOfBytesSent = (DWORD)ioStatusBlock->Information; } __except (EXCEPTION_EXECUTE_HANDLER) { if (lpOverlapped) { err = WSA_IO_PENDING; } else { err = WSAEFAULT; } goto exit; } exit: IF_DEBUG(SEND) { if ( err != NO_ERROR ) { WS_PRINT(( "WSPSend on socket %lx failed: %ld.\n", Handle, err )); } else { #ifdef _AFD_SAN_SWITCH_ WS_PRINT(( "WSPSend on socket %lx succeeded, " "bytes = %ld\n", Handle, *lpNumberOfBytesSent )); #else WS_PRINT(( "WSPSend on socket %lx succeeded, " "bytes = %ld\n", Handle, ioStatusBlock->Information )); #endif //_AFD_SAN_SWITCH_ } } // // If there is an async thread in this process, get a pointer to the // socket information structure and reenable the appropriate event. // We don't do this if there is no async thread as a performance // optimization. Also, if we're not going to return WSAEWOULDBLOCK // we don't need to reenable FD_WRITE events. // if ( SockAsyncSelectCalled && err == WSAEWOULDBLOCK ) { #ifdef _AFD_SAN_SWITCH_ if (socket==NULL) { socket = SockFindAndReferenceSocket( Handle, TRUE ); } #else //_AFD_SAN_SWITCH_ socket = SockFindAndReferenceSocket( Handle, TRUE ); #endif //_AFD_SAN_SWITCH_ // // If the socket was found reenable the right event. If it was // not found, then presumably the socket handle was invalid. // if ( socket != NULL ) { SockAcquireSocketLockExclusive( socket ); SockReenableAsyncSelectEvent( socket, FD_WRITE ); SockReleaseSocketLock( socket ); SockDereferenceSocket( socket ); } else { if ( socket == NULL ) { WS_PRINT(( "WSPSend: SockFindAndReferenceSocket failed.\n" )); } } } #ifdef _AFD_SAN_SWITCH_ else { if (socket!=NULL) { SockDereferenceSocket( socket ); } } #endif //_AFD_SAN_SWITCH_ if ( err != NO_ERROR ) { WS_EXIT( "WSPSend", SOCKET_ERROR, TRUE ); *lpErrno = err; return SOCKET_ERROR; } WS_EXIT( "WSPSend", 0, FALSE ); return 0; } // WSPSend
RT_C_DECLS_END #ifdef ALLOC_PRAGMA #pragma alloc_text (INIT, vboxguestwinnt4CreateDevice) #pragma alloc_text (INIT, vboxguestwinnt4FindPCIDevice) #endif /** * Legacy helper function to create the device object. * * @returns NT status code. * * @param pDrvObj * @param pDevObj * @param pRegPath */ NTSTATUS vboxguestwinnt4CreateDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj, PUNICODE_STRING pRegPath) { int vrc = VINF_SUCCESS; NTSTATUS rc = STATUS_SUCCESS; Log(("VBoxGuest::vboxguestwinnt4CreateDevice: pDrvObj=%p, pDevObj=%p, pRegPath=%p\n", pDrvObj, pDevObj, pRegPath)); /* * Find our virtual PCI device */ ULONG uBusNumber, uSlotNumber; rc = vboxguestwinnt4FindPCIDevice(&uBusNumber, (PCI_SLOT_NUMBER*)&uSlotNumber); if (NT_ERROR(rc)) Log(("VBoxGuest::vboxguestwinnt4CreateDevice: Device not found!\n")); bool fSymbolicLinkCreated = false; UNICODE_STRING szDosName; PDEVICE_OBJECT pDeviceObject = NULL; if (NT_SUCCESS(rc)) { /* * Create device. */ UNICODE_STRING szDevName; RtlInitUnicodeString(&szDevName, VBOXGUEST_DEVICE_NAME_NT); rc = IoCreateDevice(pDrvObj, sizeof(VBOXGUESTDEVEXT), &szDevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject); if (NT_SUCCESS(rc)) { Log(("VBoxGuest::vboxguestwinnt4CreateDevice: Device created\n")); RtlInitUnicodeString(&szDosName, VBOXGUEST_DEVICE_NAME_DOS); rc = IoCreateSymbolicLink(&szDosName, &szDevName); if (NT_SUCCESS(rc)) { Log(("VBoxGuest::vboxguestwinnt4CreateDevice: Symlink created\n")); fSymbolicLinkCreated = true; } else Log(("VBoxGuest::vboxguestwinnt4CreateDevice: IoCreateSymbolicLink failed with rc = %#x\n", rc)); } else Log(("VBoxGuest::vboxguestwinnt4CreateDevice: IoCreateDevice failed with rc = %#x\n", rc)); } /* * Setup the device extension. */ PVBOXGUESTDEVEXT pDevExt = NULL; if (NT_SUCCESS(rc)) { Log(("VBoxGuest::vboxguestwinnt4CreateDevice: Setting up device extension ...\n")); pDevExt = (PVBOXGUESTDEVEXT)pDeviceObject->DeviceExtension; RtlZeroMemory(pDevExt, sizeof(VBOXGUESTDEVEXT)); } if (NT_SUCCESS(rc) && pDevExt) { Log(("VBoxGuest::vboxguestwinnt4CreateDevice: Device extension created\n")); /* Store a reference to ourself. */ pDevExt->win.s.pDeviceObject = pDeviceObject; /* Store bus and slot number we've queried before. */ pDevExt->win.s.busNumber = uBusNumber; pDevExt->win.s.slotNumber = uSlotNumber; #ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION rc = hlpRegisterBugCheckCallback(pDevExt); #endif } /* Do the actual VBox init ... */ if (NT_SUCCESS(rc)) rc = vboxguestwinInit(pDrvObj, pDeviceObject, pRegPath); /* Clean up in case of errors. */ if (NT_ERROR(rc)) { if (fSymbolicLinkCreated && szDosName.Length > 0) IoDeleteSymbolicLink(&szDosName); if (pDeviceObject) IoDeleteDevice(pDeviceObject); } Log(("VBoxGuest::vboxguestwinnt4CreateDevice: Returning rc = 0x%x\n", rc)); return rc; }
int GetContext( VDMCONTEXT* lpContext ) { #ifndef i386 // int mode; ULONG pTmp; NT_CPU_INFO nt_cpu_info; BOOL b; BOOL bInNano; ULONG UMask; pTmp = (ULONG)EXPRESSION("ntvdm!nt_cpu_info"); if ( pTmp ) { b = READMEM((LPVOID) pTmp, &nt_cpu_info, sizeof(NT_CPU_INFO)); if ( !b ) { PRINTF("Could not read IntelRegisters context out of process\n"); return( -1 ); } bInNano = ReadDwordSafe((ULONG) nt_cpu_info.in_nano_cpu); UMask = ReadDwordSafe((ULONG) nt_cpu_info.universe); lpContext->Eax = GetRegValue(nt_cpu_info.eax, bInNano, UMask); lpContext->Ecx = GetRegValue(nt_cpu_info.ecx, bInNano, UMask); lpContext->Edx = GetRegValue(nt_cpu_info.edx, bInNano, UMask); lpContext->Ebx = GetRegValue(nt_cpu_info.ebx, bInNano, UMask); lpContext->Ebp = GetRegValue(nt_cpu_info.ebp, bInNano, UMask); lpContext->Esi = GetRegValue(nt_cpu_info.esi, bInNano, UMask); lpContext->Edi = GetRegValue(nt_cpu_info.edi, bInNano, UMask); lpContext->Esp = GetEspValue(nt_cpu_info, bInNano); lpContext->EFlags = ReadDwordSafe(nt_cpu_info.flags); lpContext->Eip = ReadDwordSafe(nt_cpu_info.eip); lpContext->SegEs = ReadWordSafe(nt_cpu_info.es); lpContext->SegCs = ReadWordSafe(nt_cpu_info.cs); lpContext->SegSs = ReadWordSafe(nt_cpu_info.ss); lpContext->SegDs = ReadWordSafe(nt_cpu_info.ds); lpContext->SegFs = ReadWordSafe(nt_cpu_info.fs); lpContext->SegGs = ReadWordSafe(nt_cpu_info.gs); } else { PRINTF("Could not find the symbol 'ntvdm!nt_cpu_info'\n"); return( -1 ); } if ( !(ReadDwordSafe(nt_cpu_info.cr0) & 1) ) { mode = V86_MODE; } else { mode = PROT_MODE; } return( mode ); #else // NTSTATUS rc; BOOL b; ULONG EFlags; WORD cs; int mode; ULONG lpVdmTib; lpContext->ContextFlags = CONTEXT_FULL; rc = NtGetContextThread( hCurrentThread, lpContext ); if ( NT_ERROR(rc) ) { PRINTF( "bde.k: Could not get current threads context - status = %08lX\n", rc ); return( -1 ); } /* ** Get the 16-bit registers from the context */ cs = (WORD)lpContext->SegCs; EFlags = lpContext->EFlags; // BUGBUG We don't seem to be setting v86 mode correctly on x86. // if ( EFlags & V86_BITS ) { /* ** V86 Mode */ mode = V86_MODE; } else { if ( (cs & RPL_MASK) != KGDT_R3_CODE ) { mode = PROT_MODE; } else { /* ** We are in flat 32-bit address space! */ lpVdmTib = (ULONG)EXPRESSION("ntvdm!VdmTib"); if ( !lpVdmTib ) { PRINTF("Could not find the symbol 'VdmTib'\n"); return( -1 ); } b = READMEM((LPVOID)(lpVdmTib+FIELD_OFFSET(VDM_TIB,VdmContext)), lpContext, sizeof(VDMCONTEXT)); if ( !b ) { PRINTF("Could not read IntelRegisters context out of process\n"); return( -1 ); } EFlags = lpContext->EFlags; if ( EFlags & V86_BITS ) { mode = V86_MODE; } else { mode = PROT_MODE; } } } return( mode ); #endif }
int WSPAPI WSPSendTo ( SOCKET Handle, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesSent, DWORD iFlags, const struct sockaddr *SocketAddress, int SocketAddressLength, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, LPWSATHREADID lpThreadId, LPINT lpErrno ) /*++ Routine Description: This routine is normally used on a connectionless socket specified by s to send a datagram contained in one or more buffers to a specific peer socket identified by the lpTo parameter. On a connection-oriented socket, the lpTo and iToLen parameters are ignored; in this case the WSPSendTo() is equivalent to WSPSend(). For overlapped sockets (created using WSPSocket() with flag WSA_FLAG_OVERLAPPED) this will occur using overlapped I/O, unless both lpOverlapped and lpCompletionRoutine are NULL in which case the socket is treated as a non-overlapped socket. A completion indication will occur (invocation of the completion routine or setting of an event object) when the supplied buffer(s) have been consumed by the transport. If the operation does not complete immediately, the final completion status is retrieved via the completion routine or WSPGetOverlappedResult(). For non-overlapped sockets, the parameters lpOverlapped, lpCompletionRoutine, and lpThreadId are ignored and WSPSend() adopts the regular synchronous semantics. Data is copied from the supplied buffer(s) into the transport's buffer. If the socket is non-blocking and stream- oriented, and there is not sufficient space in the transport's buffer, WSPSend() will return with only part of the supplied buffers having been consumed. Given the same buffer situation and a blocking socket, WSPSend() will block until all of the supplied buffer contents have been consumed. The array of WSABUF structures pointed to by the lpBuffers parameter is transient. If this operation completes in an overlapped manner, it is the service provider's responsibility to capture these WSABUF structures before returning from this call. This enables applications to build stack- based WSABUF arrays. For message-oriented sockets, care must be taken not to exceed the maximum message size of the underlying provider, which can be obtained by getting the value of socket option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted. Note that the successful completion of a WSPSendTo() does not indicate that the data was successfully delivered. dwFlags may be used to influence the behavior of the function invocation beyond the options specified for the associated socket. That is, the semantics of this routine are determined by the socket options and the dwFlags parameter. The latter is constructed by or-ing any of the following values: MSG_DONTROUTE - Specifies that the data should not be subject to routing. A WinSock service provider may choose to ignore this flag. MSG_OOB - Send out-of-band data (stream style socket such as SOCK_STREAM only). MSG_PARTIAL - Specifies that lpBuffers only contains a partial message. Note that the error code WSAEOPNOTSUPP will be returned which do not support partial message transmissions. If an overlapped operation completes immediately, WSPSendTo() returns a value of zero and the lpNumberOfBytesSent parameter is updated with the number of bytes sent. If the overlapped operation is successfully initiated and will complete later, WSPSendTo() returns SOCKET_ERROR and indicates error code WSA_IO_PENDING. In this case, lpNumberOfBytesSent is not updated. When the overlapped operation completes the amount of data transferred is indicated either via the cbTransferred parameter in the completion routine (if specified), or via the lpcbTransfer parameter in WSPGetOverlappedResult(). Providers must allow this routine to be called from within the completion routine of a previous WSPRecv(), WSPRecvFrom(), WSPSend() or WSPSendTo() function. However, for a given socket, I/O completion routines may not be nested. This permits time-sensitive data transmissions to occur entirely within a preemptive context. The lpOverlapped parameter must be valid for the duration of the overlapped operation. If multiple I/O operations are simultaneously outstanding, each must reference a separate overlapped structure. The WSAOVERLAPPED structure has the following form: typedef struct _WSAOVERLAPPED { DWORD Internal; // reserved DWORD InternalHigh; // reserved DWORD Offset; // reserved DWORD OffsetHigh; // reserved WSAEVENT hEvent; } WSAOVERLAPPED, FAR * LPWSAOVERLAPPED; If the lpCompletionRoutine parameter is NULL, the service provider signals the hEvent field of lpOverlapped when the overlapped operation completes if it contains a valid event object handle. The WinSock SPI client can use WSPGetOverlappedResult() to wait or poll on the event object. If lpCompletionRoutine is not NULL, the hEvent field is ignored and can be used by the WinSock SPI client to pass context information to the completion routine. It is the service provider's responsibility to arrange for invocation of the client-specified completion routine when the overlapped operation completes. Since the completion routine must be executed in the context of the same thread that initiated the overlapped operation, it cannot be invoked directly from the service provider. The WinSock DLL offers an asynchronous procedure call (APC) mechanism to facilitate invocation of completion routines. A service provider arranges for a function to be executed in the proper thread by calling WPUQueueApc(). Note that this routine must be invoked while in the context of the same process (but not necessarily the same thread) that was used to initiate the overlapped operation. It is the service provider's responsibility to arrange for this process context to be active prior to calling WPUQueueApc(). WPUQueueApc() takes as input parameters a pointer to a WSATHREADID structure (supplied to the provider via the lpThreadId input parameter), a pointer to an APC function to be invoked, and a 32 bit context value that is subsequently passed to the APC function. Because only a single 32-bit context value is available, the APC function cannot itself be the client-specified completion routine. The service provider must instead supply a pointer to its own APC function which uses the supplied context value to access the needed result information for the overlapped operation, and then invokes the client-specified completion routine. The prototype for the client-supplied completion routine is as follows: void CALLBACK CompletionRoutine( IN DWORD dwError, IN DWORD cbTransferred, IN LPWSAOVERLAPPED lpOverlapped, IN DWORD dwFlags ); CompletionRoutine is a placeholder for a client supplied function name. dwError specifies the completion status for the overlapped operation as indicated by lpOverlapped. cbTransferred specifies the number of bytes sent. No flag values are currently defined and the dwFlags value will be zero. This routine does not return a value. The completion routines may be called in any order, not necessarily in the same order the overlapped operations are completed. However, the service provider guarantees to the client that posted buffers are sent in the same order they are supplied. Arguments: s - A descriptor identifying a socket. lpBuffers - A pointer to an array of WSABUF structures. Each WSABUF structure contains a pointer to a buffer and the length of the buffer. This array must remain valid for the duration of the send operation. dwBufferCount - The number of WSABUF structures in the lpBuffers array. lpNumberOfBytesSent - A pointer to the number of bytes sent by this call. dwFlags - Specifies the way in which the call is made. lpTo - An optional pointer to the address of the target socket. iTolen - The size of the address in lpTo. lpOverlapped - A pointer to a WSAOVERLAPPED structure. lpCompletionRoutine - A pointer to the completion routine called when the send operation has been completed. lpThreadId - A pointer to a thread ID structure to be used by the provider in a subsequent call to WPUQueueApc(). The provider should store the referenced WSATHREADID structure (not the pointer to same) until after the WPUQueueApc() function returns. lpErrno - A pointer to the error code. Return Value: If no error occurs and the send operation has completed immediately, WSPSendTo() returns 0. Note that in this case the completion routine, if specified, will have already been queued. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code is available in lpErrno. The error code WSA_IO_PENDING indicates that the overlapped operation has been successfully initiated and that completion will be indicated at a later time. Any other error code indicates that no overlapped operation was initiated and no completion indication will occur. --*/ { NTSTATUS status; PWINSOCK_TLS_DATA tlsData; PSOCKET_INFORMATION socket; IO_STATUS_BLOCK localIoStatusBlock; PIO_STATUS_BLOCK ioStatusBlock; AFD_SEND_DATAGRAM_INFO sendInfo; PTRANSPORT_ADDRESS tdiAddress; ULONG tdiAddressLength; int err; UCHAR tdiAddressBuffer[MAX_FAST_TDI_ADDRESS]; HANDLE event; PIO_APC_ROUTINE apcRoutine; PVOID apcContext; WS_ENTER( "WSPSendTo", (PVOID)Handle, (PVOID)lpBuffers, (PVOID)dwBufferCount, (PVOID)iFlags ); WS_ASSERT( lpErrno != NULL ); err = SockEnterApi( &tlsData ); if( err != NO_ERROR ) { WS_EXIT( "WSPSendTo", SOCKET_ERROR, TRUE ); *lpErrno = err; return SOCKET_ERROR; } // // Set up locals so that we know how to clean up on exit. // tdiAddress = (PTRANSPORT_ADDRESS)tdiAddressBuffer; // // Find a pointer to the socket structure corresponding to the // passed-in handle. // socket = SockFindAndReferenceSocket( Handle, TRUE ); if ( socket == NULL ) { err = WSAENOTSOCK; goto exit; } // // If this is not a datagram socket, just call send() to process the // call. The address and address length parameters are not checked. // if ( !IS_DGRAM_SOCK(socket) || ( (socket->State==SocketStateConnected) && ( SocketAddress == NULL || SocketAddressLength == 0 )) ) { INT ret; SockDereferenceSocket( socket ); ret = WSPSend( Handle, lpBuffers, dwBufferCount, lpNumberOfBytesSent, iFlags, lpOverlapped, lpCompletionRoutine, lpThreadId, lpErrno ); WS_EXIT( "WSPSendTo", ret, (BOOLEAN)(ret == SOCKET_ERROR) ); return ret; } IF_DEBUG(SEND) { WS_PRINT(( "WSASendTo() on socket %lx to addr", Handle )); WsPrintSockaddr( (PSOCKADDR)SocketAddress, &SocketAddressLength ); } // // If the socket is not connected, then the Address and AddressLength // fields must be specified. // if ( socket->State != SocketStateConnected ) { if ( SocketAddress == NULL ) { err = WSAENOTCONN; goto exit; } } // Note: we simply truncate sockaddr's > MaxSockaddrLength down below if ( SocketAddressLength < socket->HelperDll->MinSockaddrLength ) { err = WSAEFAULT; goto exit; } // // The legal flags are MSG_OOB, MSG_DONTROUTE, and MSG_PARTIAL. // MSG_OOB is not legal on datagram sockets. // WS_ASSERT( IS_DGRAM_SOCK( socket ) ); if ( ( (iFlags & ~(MSG_DONTROUTE)) != 0 ) ) { err = WSAEOPNOTSUPP; goto exit; } // // If data send has been shut down, fail. // if ( socket->SendShutdown ) { err = WSAESHUTDOWN; goto exit; } __try { // // Make sure that the address family passed in here is the same as // was passed in on the socket( ) call. // if ( (short)socket->AddressFamily != SocketAddress->sa_family ) { err = WSAEAFNOSUPPORT; goto exit; } // // If this socket has not been set to allow broadcasts, check if this // is an attempt to send to a broadcast address. // if ( !socket->Broadcast ) { SOCKADDR_INFO sockaddrInfo; err = socket->HelperDll->WSHGetSockaddrType( (PSOCKADDR)SocketAddress, SocketAddressLength, &sockaddrInfo ); if ( err != NO_ERROR) { goto exit; } // // If this is an attempt to send to a broadcast address, reject // the attempt. // if ( sockaddrInfo.AddressInfo == SockaddrAddressInfoBroadcast ) { err = WSAEACCES; goto exit; } } // // If this socket is not yet bound to an address, bind it to an // address. We only do this if the helper DLL for the socket supports // a get wildcard address routine--if it doesn't, the app must bind // to an address manually. // if ( socket->State == SocketStateOpen) { if (socket->HelperDll->WSHGetWildcardSockaddr != NULL ) { PSOCKADDR sockaddr; INT sockaddrLength = socket->HelperDll->MaxSockaddrLength; int result; sockaddr = ALLOCATE_HEAP( sockaddrLength ); if ( sockaddr == NULL ) { err = WSAENOBUFS; goto exit; } err = socket->HelperDll->WSHGetWildcardSockaddr( socket->HelperDllContext, sockaddr, &sockaddrLength ); if ( err != NO_ERROR ) { FREE_HEAP( sockaddr ); goto exit; } // // Acquire the lock that protect this sockets. We hold this lock // throughout this routine to synchronize against other callers // performing operations on the socket we're sending data on. // SockAcquireSocketLockExclusive( socket ); // // Recheck socket state under the lock // if (socket->State == SocketStateOpen) { result = WSPBind( Handle, sockaddr, sockaddrLength, &err ); } else result = ERROR_SUCCESS; SockReleaseSocketLock( socket ); FREE_HEAP( sockaddr ); if( result == SOCKET_ERROR ) { goto exit; } } else { // // The socket is not bound and the helper DLL does not support // a wildcard socket address. Fail, the app must bind manually. // err = WSAEINVAL; goto exit; } } // // Allocate enough space to hold the TDI address structure we'll pass // to AFD. Note that is the address is small enough, we just use // an automatic in order to improve performance. // tdiAddressLength = socket->HelperDll->MaxTdiAddressLength; if ( tdiAddressLength > MAX_FAST_TDI_ADDRESS ) { tdiAddress = ALLOCATE_HEAP( tdiAddressLength ); if ( tdiAddress == NULL ) { err = WSAENOBUFS; goto exit; } } else { WS_ASSERT( (PUCHAR)tdiAddress == tdiAddressBuffer ); } // // Convert the address from the sockaddr structure to the appropriate // TDI structure. // // Note: We'll truncate any part of the specifed sock addr beyond // that which the helper considers valid // err = SockBuildTdiAddress( tdiAddress, (PSOCKADDR)SocketAddress, (SocketAddressLength > socket->HelperDll->MaxSockaddrLength ? socket->HelperDll->MaxSockaddrLength : SocketAddressLength) ); if (err!=NO_ERROR) { goto exit; } // // Set up the AFD_SEND_DATAGRAM_INFO structure. // sendInfo.BufferArray = lpBuffers; sendInfo.BufferCount = dwBufferCount; sendInfo.AfdFlags = 0; // // Set up the TDI_REQUEST structure to send the datagram. // sendInfo.TdiConnInfo.RemoteAddressLength = tdiAddressLength; sendInfo.TdiConnInfo.RemoteAddress = tdiAddress; // // Determine the appropriate APC routine & context, event handle, // and IO status block to use for the request. // if( lpOverlapped == NULL ) { // // This a synchronous request, use per-thread event object. // apcRoutine = NULL; apcContext = NULL; event = tlsData->EventHandle; ioStatusBlock = &localIoStatusBlock; } else { if( lpCompletionRoutine == NULL ) { // // No APC, use event object from OVERLAPPED structure. // event = lpOverlapped->hEvent; apcRoutine = NULL; apcContext = ( (ULONG_PTR)event & 1 ) ? NULL : lpOverlapped; } else { // // APC, ignore event object. // event = NULL; apcRoutine = SockIoCompletion; apcContext = lpCompletionRoutine; // // Tell AFD to skip fast IO on this request. // sendInfo.AfdFlags |= AFD_NO_FAST_IO; } // // Use part of the OVERLAPPED structure as our IO_STATUS_BLOCK. // ioStatusBlock = (PIO_STATUS_BLOCK)&lpOverlapped->Internal; // // Tell AFD this is an overlapped operation. // sendInfo.AfdFlags |= AFD_OVERLAPPED; } ioStatusBlock->Status = STATUS_PENDING; } __except (SOCK_EXCEPTION_FILTER()) { err = WSAEFAULT; goto exit; } // // Send the data over the socket. // status = NtDeviceIoControlFile( socket->HContext.Handle, event, apcRoutine, apcContext, ioStatusBlock, IOCTL_AFD_SEND_DATAGRAM, &sendInfo, sizeof(sendInfo), NULL, 0 ); if ( apcRoutine != NULL && !NT_ERROR(status) ) { tlsData->PendingAPCCount++; InterlockedIncrement( &SockProcessPendingAPCCount ); } // // If this request has no overlapped structure, then wait for // the operation to complete. // if ( status == STATUS_PENDING && lpOverlapped == NULL ) { BOOL success; success = SockWaitForSingleObject( event, Handle, SOCK_CONDITIONALLY_CALL_BLOCKING_HOOK, SOCK_SEND_TIMEOUT ); // // If the wait completed successfully, look in the IO status // block to determine the real status code of the request. If // the wait timed out, then cancel the IO and set up for an // error return. // if ( success ) { status = ioStatusBlock->Status; } else { SockCancelIo( Handle ); status = STATUS_IO_TIMEOUT; } } switch (status) { case STATUS_SUCCESS: break; case STATUS_PENDING: err = WSA_IO_PENDING; goto exit; default: if (!NT_SUCCESS(status) ) { // // Map the NTSTATUS to a WinSock error code. // err = SockNtStatusToSocketError( status ); goto exit; } } // // The request completed immediately, so return the number of // bytes sent to the user. // It is possible that application deallocated lpOverlapped // in another thread if completion port was used to receive // completion indication. We do not want to confuse the // application by returning failure, just pretend that we didn't // know about synchronous completion // __try { *lpNumberOfBytesSent = (DWORD)ioStatusBlock->Information; } __except (EXCEPTION_EXECUTE_HANDLER) { if (lpOverlapped) { err = WSA_IO_PENDING; } else { err = WSAEFAULT; } goto exit; } exit: IF_DEBUG(SEND) { if ( err != NO_ERROR ) { WS_PRINT(( "WSPSendTo on socket %lx (%lx) failed: %ld.\n", Handle, socket, err )); } else { WS_PRINT(( "WSPSendTo on socket %lx (%lx) succeeded, " "bytes = %ld\n", Handle, socket, ioStatusBlock->Information )); } } if ( socket != NULL ) { if ( SockAsyncSelectCalled && err == WSAEWOULDBLOCK ) { SockAcquireSocketLockExclusive( socket ); SockReenableAsyncSelectEvent( socket, FD_WRITE ); SockReleaseSocketLock( socket ); } SockDereferenceSocket( socket ); } if ( tdiAddress != NULL && tdiAddress != (PTRANSPORT_ADDRESS)tdiAddressBuffer ) { FREE_HEAP( tdiAddress ); } if ( err != NO_ERROR ) { WS_EXIT( "WSPSendTo", SOCKET_ERROR, TRUE ); *lpErrno = err; return SOCKET_ERROR; } WS_EXIT( "WSPSendTo", 0, FALSE ); return 0; } // WSPSendTo
static DWORD WINAPI co_os_daemon_thread(LPVOID D) { co_daemon_handle_t d = D; HANDLE h = d->handle; HANDLE w[2]; OVERLAPPED overlapped; DWORD r; co_message_t *data = 0; bool_t async = PFALSE; unsigned qItems = 0; unsigned qOut = 0; unsigned qIn = 0; co_message_t **queue = 0; co_rc_t rc; co_message_t **_q; unsigned _i; unsigned _o; # define Q_REALLOC_1() \ (_q = co_os_realloc( \ (void *) queue, \ sizeof (co_message_t *) * (_i = (qItems * 2)))) # define Q_REALLOC_2() \ (_q = (co_message_t **) co_os_realloc( \ (void *) queue, \ sizeof (co_message_t *) * (_i = (qItems * 2)))) # define Q_COPY_2() \ memcpy( \ _q + (qOut += qItems), _q + _o, \ sizeof (co_message_t *) * (qItems - _o)) # define NT_ERROR(_1) { \ co_debug("co_os_daemon_thread() error [ %x , %s ]\n", \ GetLastError(), \ _1); \ goto co_os_daemon_thread_error; \ } memset(&overlapped, 0, sizeof (overlapped)); overlapped.hEvent = CreateEvent(0, TRUE, FALSE, 0); if (!overlapped.hEvent) NT_ERROR("CE001"); w[0] = overlapped.hEvent; w[1] = d->shifted; co_os_daemon_thread_loop: if (WaitForSingleObject(w[1], INFINITE) == WAIT_FAILED) NT_ERROR("W0001"); if (!queue) { queue = co_os_malloc((qItems = CO_OS_DAEMON_QUEUE_MINIMUM) * sizeof (co_message_t *)); if (!queue) goto co_os_daemon_thread_loop; } while (d->loop) { if (!(d->message || qIn == qOut)) { d->message = queue[qOut++]; if (!SetEvent(d->readable)) NT_ERROR("SE0001"); if (qOut == qItems) { qOut = 0; if (qIn == qItems) qIn = 0; } } if (async) { r = WaitForMultipleObjects(2, w, FALSE, INFINITE); if(r == WAIT_FAILED) NT_ERROR("W0002"); if (!d->message) if (!ResetEvent(d->readable)) NT_ERROR("RE0001"); if (r != WAIT_OBJECT_0) continue; if (!GetOverlappedResult(h, &overlapped, &r, FALSE)) { r = GetLastError(); if (r == ERROR_IO_INCOMPLETE) continue; if (r == ERROR_IO_PENDING) continue; if (r == ERROR_BROKEN_PIPE) goto co_os_daemon_thread_broken_pipe; NT_ERROR("GOR01"); } if(!r) { co_os_free(data); data = 0 ; } else { if(r < sizeof(co_message_t)) NT_ERROR("DS0001"); if(r != data->size + sizeof(co_message_t)) NT_ERROR("DS0002"); queue[qIn++] = data; } async = PFALSE; } if (data) { if (qIn == qItems) { if (qOut) qIn = 0; else if (Q_REALLOC_1()) queue = _q, qItems = _i; else goto co_os_daemon_thread_loop; } else if (qIn == qOut) { if (!Q_REALLOC_2()) goto co_os_daemon_thread_loop; _o = qOut; Q_COPY_2(); queue = _q, qItems = _i; } data = 0; } if (!async) { if (!PeekNamedPipe(h, 0, 0, 0, 0, &r)) NT_ERROR("PNP01"); if (!(data = co_os_malloc(r))) goto co_os_daemon_thread_loop; async = PTRUE; if (!ReadFile(h, data, r, 0, &overlapped)) { r = GetLastError(); if (r == ERROR_IO_INCOMPLETE) continue; if (r == ERROR_IO_PENDING) continue; if (r == ERROR_BROKEN_PIPE) goto co_os_daemon_thread_broken_pipe; NT_ERROR("RF001"); } } } rc = CO_RC(OK); co_os_daemon_thread_return: if (async) { CancelIo(h); co_os_free(data); async = 0; } while (d->loop && qIn != qOut) { if (!d->message) { d->message = queue[qOut++]; if (!SetEvent(d->readable)) { if (!CO_OK(rc)) break; NT_ERROR("SE0002"); } if (qOut == qItems) qOut = 0; } if (WaitForSingleObject(w[1], INFINITE) == WAIT_FAILED) { if (!CO_OK(rc)) break; NT_ERROR("W0003"); } if (!d->message) if (!ResetEvent(d->readable)) { if (!CO_OK(rc)) break; NT_ERROR("RE0002"); } } while (qIn != qOut) { co_os_free(queue[qOut++]); if (qOut == qItems) qOut = 0; } if (queue) co_os_free(queue); if (overlapped.hEvent) if ((!CloseHandle(overlapped.hEvent)) && CO_OK(rc)) co_debug("co_os_daemon_thread() error" " [ %x , CH0001 ]\n", GetLastError()); d->rc = rc; if (d->loop) if ((!SetEvent(d->readable)) && CO_OK(rc)) co_debug("co_os_daemon_thread() error" " [ %x , SE0003 ]\n", GetLastError()); return 0; co_os_daemon_thread_error: rc = CO_RC(ERROR); goto co_os_daemon_thread_return; co_os_daemon_thread_broken_pipe: rc = CO_RC(BROKEN_PIPE); goto co_os_daemon_thread_return; # undef Q_REALLOC_1 # undef Q_REALLOC_2 # undef Q_COPY_2 # undef NT_ERROR }
/** * Handle request from the Plug & Play subsystem. * * @returns NT status code * @param pDrvObj Driver object * @param pDevObj Device object */ static NTSTATUS vboxguestwinAddDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj) { NTSTATUS rc; Log(("VBoxGuest::vboxguestwinGuestAddDevice\n")); /* * Create device. */ PDEVICE_OBJECT pDeviceObject = NULL; PVBOXGUESTDEVEXT pDevExt = NULL; UNICODE_STRING devName; UNICODE_STRING win32Name; RtlInitUnicodeString(&devName, VBOXGUEST_DEVICE_NAME_NT); rc = IoCreateDevice(pDrvObj, sizeof(VBOXGUESTDEVEXT), &devName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject); if (NT_SUCCESS(rc)) { /* * Create symbolic link (DOS devices). */ RtlInitUnicodeString(&win32Name, VBOXGUEST_DEVICE_NAME_DOS); rc = IoCreateSymbolicLink(&win32Name, &devName); if (NT_SUCCESS(rc)) { /* * Setup the device extension. */ pDevExt = (PVBOXGUESTDEVEXT)pDeviceObject->DeviceExtension; RtlZeroMemory(pDevExt, sizeof(VBOXGUESTDEVEXT)); KeInitializeSpinLock(&pDevExt->win.s.MouseEventAccessLock); pDevExt->win.s.pDeviceObject = pDeviceObject; pDevExt->win.s.prevDevState = STOPPED; pDevExt->win.s.devState = STOPPED; pDevExt->win.s.pNextLowerDriver = IoAttachDeviceToDeviceStack(pDeviceObject, pDevObj); if (pDevExt->win.s.pNextLowerDriver == NULL) { Log(("VBoxGuest::vboxguestwinGuestAddDevice: IoAttachDeviceToDeviceStack did not give a nextLowerDriver!\n")); rc = STATUS_DEVICE_NOT_CONNECTED; } } else Log(("VBoxGuest::vboxguestwinGuestAddDevice: IoCreateSymbolicLink failed with rc=%#x!\n", rc)); } else Log(("VBoxGuest::vboxguestwinGuestAddDevice: IoCreateDevice failed with rc=%#x!\n", rc)); if (NT_SUCCESS(rc)) { /* * If we reached this point we're fine with the basic driver setup, * so continue to init our own things. */ #ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION vboxguestwinBugCheckCallback(pDevExt); /* Ignore failure! */ #endif /* VBoxGuestPower is pageable; ensure we are not called at elevated IRQL */ pDeviceObject->Flags |= DO_POWER_PAGABLE; /* Driver is ready now. */ pDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; } /* Cleanup on error. */ if (NT_ERROR(rc)) { if (pDevExt) { if (pDevExt->win.s.pNextLowerDriver) IoDetachDevice(pDevExt->win.s.pNextLowerDriver); } IoDeleteSymbolicLink(&win32Name); if (pDeviceObject) IoDeleteDevice(pDeviceObject); } Log(("VBoxGuest::vboxguestwinGuestAddDevice: returning with rc = 0x%x\n", rc)); return rc; }
VOID CdCompleteRequest ( _Inout_opt_ PIRP_CONTEXT IrpContext, _Inout_opt_ PIRP Irp, _In_ NTSTATUS Status ) /*++ Routine Description: This routine completes a Irp and cleans up the IrpContext. Either or both of these may not be specified. Arguments: Irp - Supplies the Irp being processed. Status - Supplies the status to complete the Irp with Return Value: None. --*/ { ASSERT_OPTIONAL_IRP_CONTEXT( IrpContext ); ASSERT_OPTIONAL_IRP( Irp ); // // Cleanup the IrpContext if passed in here. // if (ARGUMENT_PRESENT( IrpContext )) { CdCleanupIrpContext( IrpContext, FALSE ); } // // If we have an Irp then complete the irp. // if (ARGUMENT_PRESENT( Irp )) { // // Clear the information field in case we have used this Irp // internally. // if (NT_ERROR( Status ) && FlagOn( Irp->Flags, IRP_INPUT_OPERATION )) { Irp->IoStatus.Information = 0; } Irp->IoStatus.Status = Status; AssertVerifyDeviceIrp( Irp ); IoCompleteRequest( Irp, IO_CD_ROM_INCREMENT ); } return; }
NTSTATUS DigiRegisterAtlasName( IN PUNICODE_STRING DeviceName, IN PUNICODE_STRING ValueName, IN PUNICODE_STRING ValueEntry ) /*++ Routine Description: This routine will register the passed in value name and its associated value for Atlas to find. In addition, we will create a symbolic link to a name which is accessible for Atlas to open and exchange information. Arguments: DeviceName - pointer to unicode string to use when creating a symbolic link. It is assumed this device name is all ready created and ready to have symbolic links created. ValueName - pointer to unicode string to be used as the registry value name. Value - pointer to unicode string to be used as the value associated with ValueName. Return Value: - STATUS_SUCCESS if successful - Error indicating problem --*/ { #define DEFAULT_DIGI_ATLAS_DEVICEMAP L"DigiAtlas" NTSTATUS Status; UNICODE_STRING LinkName; WCHAR LinkNameBuffer[32]; // // First, we create the required link symbolic name from the passed // in value name. // RtlInitUnicodeString( &LinkName, NULL ); LinkName.Buffer = &LinkNameBuffer[0]; LinkName.MaximumLength = sizeof(LinkNameBuffer); LinkName.Length = 0; RtlAppendUnicodeToString( &LinkName, L"\\DosDevices\\" ); RtlAppendUnicodeStringToString( &LinkName, ValueEntry ); // // Create the symbolic link first. // Status = IoCreateSymbolicLink( &LinkName, DeviceName ); if( NT_ERROR(Status) ) return( Status ); // // We need to add a \\.\ to the beginning of ValueEntry. // LinkName.Length = 0; RtlZeroMemory( LinkName.Buffer, LinkName.MaximumLength ); RtlAppendUnicodeToString( &LinkName, L"\\\\.\\" ); RtlAppendUnicodeStringToString( &LinkName, ValueEntry ); Status = RtlWriteRegistryValue( RTL_REGISTRY_DEVICEMAP, DEFAULT_DIGI_ATLAS_DEVICEMAP, ValueName->Buffer, REG_SZ, LinkName.Buffer, LinkName.Length + sizeof(WCHAR) ); return( Status ); } // end DigiRegisterAtlasName