/* * Dump to text one entry of a ll_bitlockerAccountInfo linked list */ void Bitlocker_Dump(s_bitlockerAccountInfo *bitlockerAccountEntry,LPSTR szOut) { WCHAR szVolumeGUID[128],szRecoveryGUID[128]; WCHAR szKeyPackageFileName[MAX_PATH+1]; StringFromGUID2(bitlockerAccountEntry->msFVE_VolumeGUID,szVolumeGUID,sizeof(szVolumeGUID)); StringFromGUID2(bitlockerAccountEntry->msFVE_RecoveryGUID,szRecoveryGUID,sizeof(szRecoveryGUID)); RtlZeroMemory(szKeyPackageFileName,sizeof(szKeyPackageFileName)); RtlMoveMemory(szKeyPackageFileName,szRecoveryGUID+1,2*(lstrlenW(szRecoveryGUID)-2)); lstrcatW(szKeyPackageFileName,L".pk"); if(!BitLocker_DumpKeyPackage(bitlockerAccountEntry,szKeyPackageFileName)) lstrcpynW(szKeyPackageFileName,L"(Error while saving)",MAX_PATH); sprintf_s(szOut,2048,"Bitlocker entry\r\n\tVolume GUID: %ls\r\n\tRecovery GUID: %ls\r\n\tRecovery password: %ls\r\n\tKey-package: saved to binary file %ls\r\n", szVolumeGUID,szRecoveryGUID, bitlockerAccountEntry->msFVE_RecoveryPassword, szKeyPackageFileName); }
VAPI(VanillaImage) VanillaLoadImageFromBinary(VanillaBinary Binary) { if (!Binary || Binary->Length <= 0) { return NULL; } CoInitialize(NULL); VanillaImage Image = new VImage; Image->GMem = GlobalAlloc(GMEM_FIXED, Binary->Length); LPVOID Mem = GlobalLock(Image->GMem); RtlMoveMemory(Mem, Binary->Address, Binary->Length); GlobalUnlock(Image->GMem); CreateStreamOnHGlobal(Image->GMem, false, &Image->Stream); Image->Image = new Gdiplus::Bitmap(Image->Stream); Image->Width = Image->Image->GetWidth(); Image->Height = Image->Image->GetHeight(); CoUninitialize(); return Image; }
NTSTATUS HwlTerminateProcess64(PEPROCESS Process) { //get pspterminatethreadbypointer ULONG32 callcode=0; ULONG64 AddressOfPspTTBP=0, AddressOfPsTST=0, i=0; PETHREAD Thread=NULL; PEPROCESS tProcess=NULL; NTSTATUS status=0; if(PspTerminateThreadByPointer==NULL) { AddressOfPsTST=(ULONG64)GetFunctionAddr(L"PsTerminateSystemThread"); if(AddressOfPsTST==0) return STATUS_UNSUCCESSFUL; for(i=1;i<0xff;i++) { if(MmIsAddressValid((PVOID)(AddressOfPsTST+i))!=FALSE) { if(*(BYTE *)(AddressOfPsTST+i)==0x01 && *(BYTE *)(AddressOfPsTST+i+1)==0xe8) //目标地址-原始地址-5=机器码 ==> 目标地址=机器码+5+原始地址 { RtlMoveMemory(&callcode,(PVOID)(AddressOfPsTST+i+2),4); AddressOfPspTTBP=(ULONG64)callcode + 5 + AddressOfPsTST+i+1; } } } PspTerminateThreadByPointer=(PSPTERMINATETHREADBYPOINTER)AddressOfPspTTBP; } //loop call pspterminatethreadbypointer for(i=4;i<0x40000;i+=4) { status=PsLookupThreadByThreadId((HANDLE)i, &Thread); if(NT_SUCCESS(status)) { tProcess=IoThreadToProcess(Thread); if(tProcess==Process) PspTerminateThreadByPointer(Thread,0,1); ObDereferenceObject(Thread); } } //return status return STATUS_SUCCESS; }
bool initializeLog() { wchar_t buf[255]; if(true == QueryReg(L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services\\MoneyHubPrt",L"ImagePath",buf,sizeof(buf)) ) { wchar_t *p = wcsrchr(buf,L'\\'); if(p != NULL) { *((p-buf+1)+buf) = L'\0'; //wcscat_s(buf,sizeof(255),L"sysLog.txt"); RtlMoveMemory(buf+wcslen(buf),L"syslog.txt",24); LogInitialize(LOG_TYPE_DEBUG,buf); return true; } else return false; } else return false; }
NTSTATUS Reg_GetGuidValue(_In_ HANDLE hKey, _In_ LPCWSTR pszValueName, _Out_ PGUID pValue) { NTSTATUS Status = STATUS_SUCCESS; UNICODE_STRING ValueName; RtlInitUnicodeString(&ValueName, pszValueName); struct { KEY_VALUE_PARTIAL_INFORMATION Info; GUID Extra; } Buffer; ULONG ResultLength; Status = ZwQueryValueKey(hKey, &ValueName, KeyValuePartialInformation, &Buffer, sizeof(Buffer), &ResultLength); if (NT_SUCCESS(Status)) { if (REG_BINARY == Buffer.Info.Type && sizeof(GUID) == Buffer.Info.DataLength) { RtlMoveMemory(pValue, Buffer.Info.Data, sizeof(GUID)); } else Status = STATUS_INVALID_BUFFER_SIZE; } return Status; }
static VOID RefillSocketBuffer( PAFD_FCB FCB ) { /* Make sure nothing's in flight first */ if (FCB->ReceiveIrp.InFlightRequest) return; /* Now ensure that receive is still allowed */ if (FCB->TdiReceiveClosed) return; /* Check if the buffer is full */ if (FCB->Recv.Content == FCB->Recv.Size) { /* If there are bytes used, we can solve this problem */ if (FCB->Recv.BytesUsed != 0) { /* Reposition the unused portion to the beginning of the receive window */ RtlMoveMemory(FCB->Recv.Window, FCB->Recv.Window + FCB->Recv.BytesUsed, FCB->Recv.Content - FCB->Recv.BytesUsed); FCB->Recv.Content -= FCB->Recv.BytesUsed; FCB->Recv.BytesUsed = 0; } else { /* No space in the buffer to receive */ return; } } AFD_DbgPrint(MID_TRACE,("Replenishing buffer\n")); TdiReceive( &FCB->ReceiveIrp.InFlightRequest, FCB->Connection.Object, TDI_RECEIVE_NORMAL, FCB->Recv.Window + FCB->Recv.Content, FCB->Recv.Size - FCB->Recv.Content, &FCB->ReceiveIrp.Iosb, ReceiveComplete, FCB ); }
HRESULT STDMETHODCALLTYPE IActiveScriptSite_Create( __RPC__inout IActiveScriptSite_ **This ) { *This = (IActiveScriptSite_ *) GlobalAlloc(GPTR, sizeof(_IActiveScriptSite_)); if (*This) { _IActiveScriptSite_ * hObject = (_IActiveScriptSite_ *) *This; hObject->lpVtbl = GlobalAlloc(GPTR, sizeof(IActiveScriptSite_Vtbl)); RtlMoveMemory(hObject->lpVtbl, &_IActiveScriptSite_Vtbl, sizeof(*(hObject->lpVtbl))); hObject->RefCount = 0; hObject->lpVtbl->AddRef(*This); IHost_Create(&hObject->hHost); return S_OK; } else { return E_OUTOFMEMORY; } }
static NTSTATUS CmiAddKeyToHashTable( IN PCMHIVE RegistryHive, IN OUT PCM_KEY_FAST_INDEX HashCell, IN HCELL_INDEX HashCellIndex, IN PCM_KEY_NODE NewKeyCell, IN HCELL_INDEX NKBOffset) { ULONG i; ULONG HashKey = 0; if (NewKeyCell->Flags & KEY_COMP_NAME) { RtlCopyMemory( &HashKey, NewKeyCell->Name, min(NewKeyCell->NameLength, sizeof(ULONG))); } for (i = 0; i < HashCell->Count; i++) { if (HashCell->List[i].HashKey > HashKey) break; } if (i < HashCell->Count) { RtlMoveMemory(HashCell->List + i + 1, HashCell->List + i, (HashCell->Count - i) * sizeof(HashCell->List[0])); } HashCell->List[i].Cell = NKBOffset; HashCell->List[i].HashKey = HashKey; HashCell->Count++; HvMarkCellDirty(&RegistryHive->Hive, HashCellIndex, FALSE); return STATUS_SUCCESS; }
/* * @implemented */ BOOLEAN NTAPI Ke386SetIoAccessMap(IN ULONG MapNumber, IN PKIO_ACCESS_MAP IopmBuffer) { PKPROCESS CurrentProcess; PKPRCB Prcb; PVOID pt; if ((MapNumber > IOPM_COUNT) || (MapNumber == IO_ACCESS_MAP_NONE)) return FALSE; Prcb = KeGetCurrentPrcb(); // Copy the IOP map and load the map for the current process. pt = &(KeGetPcr()->TSS->IoMaps[MapNumber-1].IoMap); RtlMoveMemory(pt, (PVOID)IopmBuffer, IOPM_SIZE); CurrentProcess = Prcb->CurrentThread->ApcState.Process; KeGetPcr()->TSS->IoMapBase = CurrentProcess->IopmOffset; return TRUE; }
PUNICODE_STRING Uwcsdup(PUNICODE_STRING src) { PUNICODE_STRING rtn; if (!src) return NULL; rtn = ExAllocatePoolWithTag ( PagedPool, sizeof(UNICODE_STRING)+src->Length+ sizeof(UNICODE_NULL), CRASH_TAG); if (!rtn) { debugOutput(L"Allocate paged pool failed, Uwcsdup\n"); } else { rtn->Length = src->Length; rtn->MaximumLength = src->Length + sizeof(UNICODE_NULL); rtn->Buffer = (WCHAR *)(((unsigned char *)rtn)+ sizeof(UNICODE_STRING)); RtlMoveMemory(rtn->Buffer, src->Buffer, src->Length); *(rtn->Buffer+src->Length/sizeof(WCHAR)) = UNICODE_NULL; } return rtn; }
VOID StatReadStats (PULONG Buffer) { PACCUMULATORS Accum; ULONG i, r1; pPSTATS Inf; PKPCR Pcr; PAGED_CODE(); Buffer[0] = sizeof (PSTATS); Inf = (pPSTATS)(Buffer + 1); for (i = 0; i < MAXIMUM_PROCESSORS; i++, Inf++) { Pcr = KiProcessorControlRegister[i]; if (Pcr == NULL) { continue; } Accum = StatProcessorAccumulators[i]; do { r1 = Accum->CountStart; Inf->Counters[0] = Accum->Counters[0]; Inf->Counters[1] = Accum->Counters[1]; Inf->TSC = Accum->TSC; Inf->SpinLockAcquires = Pcr->KernelReserved[0]; Inf->SpinLockCollisions = Pcr->KernelReserved[1]; Inf->SpinLockSpins = Pcr->KernelReserved[2]; Inf->Irqls = Pcr->KernelReserved[3]; } while (r1 != Accum->CountEnd); RtlMoveMemory (Inf->ThunkCounters, (CONST VOID *)(Accum->ThunkCounters), StatMaxThunkCounter * sizeof (ULONG)); } }
__declspec(dllexport) void TITCALL ExporterInit(DWORD MemorySize, ULONG_PTR ImageBase, DWORD ExportOrdinalBase, char* szExportModuleName) { if(expTableData != NULL) { ExporterCleanup(); } expExportData.Base = ExportOrdinalBase; expTableData = VirtualAlloc(NULL, MemorySize, MEM_COMMIT, PAGE_READWRITE); if(szExportModuleName != NULL) { RtlMoveMemory(expTableData, szExportModuleName, lstrlenA(szExportModuleName)); expTableDataCWP = (LPVOID)((ULONG_PTR)expTableData + lstrlenA(szExportModuleName) + 2); expNamePresent = true; } else { expTableDataCWP = expTableData; expNamePresent = false; } expImageBase = ImageBase; }
NTSTATUS NTAPI PinWavePciAudioPosition( IN PIRP Irp, IN PKSIDENTIFIER Request, IN OUT PVOID Data) { CPortPinWavePci *Pin; PSUBDEVICE_DESCRIPTOR Descriptor; // get sub device descriptor Descriptor = (PSUBDEVICE_DESCRIPTOR)KSPROPERTY_ITEM_IRP_STORAGE(Irp); // sanity check PC_ASSERT(Descriptor); PC_ASSERT(Descriptor->PortPin); PC_ASSERT_IRQL(DISPATCH_LEVEL); // cast to pin impl Pin = (CPortPinWavePci*)Descriptor->PortPin; //sanity check PC_ASSERT(Pin->m_Stream); if (Request->Flags & KSPROPERTY_TYPE_GET) { // FIXME non multithreading-safe // copy audio position RtlMoveMemory(Data, &Pin->m_Position, sizeof(KSAUDIO_POSITION)); DPRINT("Play %lu Record %lu\n", Pin->m_Position.PlayOffset, Pin->m_Position.WriteOffset); Irp->IoStatus.Information = sizeof(KSAUDIO_POSITION); return STATUS_SUCCESS; } // not supported return STATUS_NOT_SUPPORTED; }
NTSTATUS KspCopyCreateRequest( IN PIRP Irp, IN LPWSTR ObjectClass, IN OUT PULONG Size, OUT PVOID * Result) { PIO_STACK_LOCATION IoStack; ULONG ObjectLength, ParametersLength; PVOID Buffer; /* get current irp stack */ IoStack = IoGetCurrentIrpStackLocation(Irp); /* get object class length */ ObjectLength = (wcslen(ObjectClass) + 1) * sizeof(WCHAR); /* check for minium length requirement */ if (ObjectLength + *Size > IoStack->FileObject->FileName.MaximumLength) return STATUS_UNSUCCESSFUL; /* extract parameters length */ ParametersLength = IoStack->FileObject->FileName.MaximumLength - ObjectLength; /* allocate buffer */ Buffer = AllocateItem(NonPagedPool, ParametersLength); if (!Buffer) return STATUS_INSUFFICIENT_RESOURCES; /* copy parameters */ RtlMoveMemory(Buffer, &IoStack->FileObject->FileName.Buffer[ObjectLength / sizeof(WCHAR)], ParametersLength); /* store result */ *Result = Buffer; *Size = ParametersLength; return STATUS_SUCCESS; }
VOID xmsMoveMemory( ULONG Destination, ULONG Source, ULONG Count ) /*++ Routine Description: This routine moves a block of memory, and notifies the emulator. It correctly handles overlapping source and destination Arguments: Destination -- Supplies a pointer to the destination Linear Address Source -- Supplies a pointer to the source Linear Address Count -- Supplies the number of bytes to move Return Value: None. --*/ { // // Move the memory // RtlMoveMemory( (PVOID)Destination, (PVOID)Source, Count ); }
NTSTATUS EvtWmiInstanceSetInstance( IN WDFWMIINSTANCE WmiInstance, IN ULONG InBufferSize, IN PVOID InBuffer ) { FireflyDeviceInformation* pInfo; ULONG length; NTSTATUS status; PAGED_CODE(); UNREFERENCED_PARAMETER(InBufferSize); pInfo = InstanceGetInfo(WmiInstance); // // Our mininum buffer size has been checked by the Framework // and failed automatically if too small. // length = sizeof(*pInfo); RtlMoveMemory(pInfo, InBuffer, length); // // Tell the HID device about the new tail light state // status = FireflySetFeature( WdfObjectGet_DEVICE_CONTEXT(WdfWmiInstanceGetDevice(WmiInstance)), TAILLIGHT_PAGE, TAILLIGHT_FEATURE, pInfo->TailLit ); return status; }
virtual NTSTATUS Create(PDEVICE_RELATIONS Relations) { PDEVICE_RELATIONS NonPagedRelations = nullptr; if (Relations != nullptr) { m_PagedRelations = Relations; size_t RelationsSize = sizeof(DEVICE_RELATIONS) + sizeof(PDEVICE_OBJECT ) * Relations->Count - sizeof(PDEVICE_OBJECT); auto status = m_NonPagedCopy.Create(RelationsSize, NonPagedPool); if (!NT_SUCCESS(status)) { return status; } NonPagedRelations = static_cast<PDEVICE_RELATIONS>(m_NonPagedCopy.Ptr()); RtlMoveMemory(NonPagedRelations, Relations, RelationsSize); } return CDeviceRelations::Create(NonPagedRelations); }
static void divert_do_recv(PIRP Irp) { struct divert_packet *dp; PUCHAR currentAddress; currentAddress = MmGetSystemAddressForMdlSafe(Irp->MdlAddress, NormalPagePriority); dp = _packet_queue.dp_next; _packet_queue.dp_next = dp->dp_next; dp->dp_next = _packet_free.dp_next; _packet_free.dp_next = dp; if (dp->dp_flags) { RtlMoveMemory(currentAddress, dp->dp_packet, dp->dp_len); Irp->IoStatus.Information = dp->dp_len; } Irp->IoStatus.Status = STATUS_SUCCESS; IoCompleteRequest(Irp, IO_NO_INCREMENT); }
/**************************************************************************** ** ** Name: pfBuildInstanceDefinition - Build an instance of an object ** ** Description: ** ** Inputs: pBuffer - pointer to buffer where instance is to be constructed pBufferNext - pointer to a pointer which will contain next available location, DWORD aligned ParentObjectTitleIndex - Title Index of parent object type; 0 if no parent object ParentObjectInstance - Index into instances of parent object type, starting at 0, for this instances parent object instance UniqueID - a unique identifier which should be used instead of the Name for identifying this instance Name - Name of this instance ** ** Outputs: ** ** Returns: ** ** Exceptions: ** ** Side Effects: ** ** History: ** 10-Oct-1998 (wonst02) ** Original. ** ****************************************************************************/ BOOL pfBuildInstanceDefinition( PERF_INSTANCE_DEFINITION *pBuffer, PVOID *pBufferNext, DWORD ParentObjectTitleIndex, DWORD ParentObjectInstance, DWORD UniqueID, LPCWSTR Name ) { DWORD NameLength; LPWSTR pName; /* ** Include trailing null in name size */ NameLength = (lstrlenW(Name) + 1) * sizeof(WCHAR); pBuffer->ByteLength = sizeof(PERF_INSTANCE_DEFINITION) + DWORD_MULTIPLE(NameLength); pBuffer->ParentObjectTitleIndex = ParentObjectTitleIndex; pBuffer->ParentObjectInstance = ParentObjectInstance; pBuffer->UniqueID = UniqueID; pBuffer->NameOffset = sizeof(PERF_INSTANCE_DEFINITION); pBuffer->NameLength = NameLength; /* copy name to name buffer */ pName = (LPWSTR)&pBuffer[1]; RtlMoveMemory(pName,Name,NameLength); /* update "next byte" pointer */ *pBufferNext = (PVOID) ((PCHAR) pBuffer + pBuffer->ByteLength); return 0; }
BOOLEAN NTAPI KdpPrintString(IN PSTRING Output) { STRING Data, Header; DBGKD_DEBUG_IO DebugIo; USHORT Length = Output->Length; /* Copy the string */ RtlMoveMemory(KdpMessageBuffer, Output->Buffer, Length); /* Make sure we don't exceed the KD Packet size */ if ((sizeof(DBGKD_DEBUG_IO) + Length) > PACKET_MAX_SIZE) { /* Normalize length */ Length = PACKET_MAX_SIZE - sizeof(DBGKD_DEBUG_IO); } /* Build the packet header */ DebugIo.ApiNumber = DbgKdPrintStringApi; DebugIo.ProcessorLevel = (USHORT)KeProcessorLevel; DebugIo.Processor = KeGetCurrentPrcb()->Number; DebugIo.u.PrintString.LengthOfString = Length; Header.Length = sizeof(DBGKD_DEBUG_IO); Header.Buffer = (PCHAR)&DebugIo; /* Build the data */ Data.Length = Length; Data.Buffer = KdpMessageBuffer; /* Send the packet */ KdSendPacket(PACKET_TYPE_KD_DEBUG_IO, &Header, &Data, &KdpContext); /* Check if the user pressed CTRL+C */ return KdpPollBreakInWithPortLock(); }
NTSTATUS NtGetContextThread( IN HANDLE ThreadHandle, IN OUT PCONTEXT ThreadContext ) /*++ Routine Description: This function returns the usermode context of the specified thread. This function will fail if the specified thread is a system thread. It will return the wrong answer if the thread is a non-system thread that does not execute in user-mode. Arguments: ThreadHandle - Supplies an open handle to the thread object from which to retrieve context information. The handle must allow THREAD_GET_CONTEXT access to the thread. ThreadContext - Supplies the address of a buffer that will receive the context of the specified thread. Return Value: None. --*/ { ULONG Alignment; ULONG ContextFlags; GETSETCONTEXT ContextFrame; ULONG ContextLength; KIRQL Irql; KPROCESSOR_MODE Mode; NTSTATUS Status; PETHREAD Thread; PAGED_CODE(); // // Get previous mode and reference specified thread. // Mode = KeGetPreviousMode(); Status = ObReferenceObjectByHandle(ThreadHandle, THREAD_GET_CONTEXT, PsThreadType, Mode, (PVOID *)&Thread, NULL); // // If the reference was successful, the check if the specified thread // is a system thread. // if (NT_SUCCESS(Status)) { // // If the thread is not a system thread, then attempt to get the // context of the thread. // if (IS_SYSTEM_THREAD(Thread) == FALSE) { // // Attempt to get the context of the specified thread. // try { // // Set the default alignment, capture the context flags, // and set the default size of the context record. // Alignment = CONTEXT_ALIGN; ContextFlags = ProbeAndReadUlong(&ThreadContext->ContextFlags); ContextLength = sizeof(CONTEXT); #if defined(_X86_) // // CONTEXT_EXTENDED_REGISTERS is SET, then we want sizeof(CONTEXT) set above // otherwise (not set) we only want the old part of the context record. // if ((ContextFlags & CONTEXT_EXTENDED_REGISTERS) != CONTEXT_EXTENDED_REGISTERS) { ContextLength = FIELD_OFFSET(CONTEXT, ExtendedRegisters); } #endif #if defined(_MIPS_) // // The following code is included for backward compatibility // with old code that does not understand extended context // records on MIPS systems. // if ((ContextFlags & CONTEXT_EXTENDED_INTEGER) != CONTEXT_EXTENDED_INTEGER) { Alignment = sizeof(ULONG); ContextLength = FIELD_OFFSET(CONTEXT, ContextFlags) + 4; } #endif if (Mode != KernelMode) { ProbeForWrite(ThreadContext, ContextLength, Alignment); } } except(EXCEPTION_EXECUTE_HANDLER) { Status = GetExceptionCode(); } // // If an exception did not occur during the probe of the thread // context, then get the context of the target thread. // if (NT_SUCCESS(Status)) { KeInitializeEvent(&ContextFrame.OperationComplete, NotificationEvent, FALSE); ContextFrame.Context.ContextFlags = ContextFlags; ContextFrame.Mode = Mode; if (Thread == PsGetCurrentThread()) { ContextFrame.Apc.SystemArgument1 = NULL; ContextFrame.Apc.SystemArgument2 = Thread; KeRaiseIrql(APC_LEVEL, &Irql); PspGetSetContextSpecialApc(&ContextFrame.Apc, NULL, NULL, &ContextFrame.Apc.SystemArgument1, &ContextFrame.Apc.SystemArgument2); KeLowerIrql(Irql); // // Move context to specfied context record. If an exception // occurs, then silently handle it and return success. // try { RtlMoveMemory(ThreadContext, &ContextFrame.Context, ContextLength); } except(EXCEPTION_EXECUTE_HANDLER) { } } else { KeInitializeApc(&ContextFrame.Apc, &Thread->Tcb, OriginalApcEnvironment, PspGetSetContextSpecialApc, NULL, NULL, KernelMode, NULL); if (!KeInsertQueueApc(&ContextFrame.Apc, NULL, Thread, 2)) { Status = STATUS_UNSUCCESSFUL; } else { KeWaitForSingleObject(&ContextFrame.OperationComplete, Executive, KernelMode, FALSE, NULL); // // Move context to specfied context record. If an // exception occurs, then silently handle it and // return success. // try { RtlMoveMemory(ThreadContext, &ContextFrame.Context, ContextLength); } except(EXCEPTION_EXECUTE_HANDLER) { } } } } } else {
MIXER_STATUS QueryKeyValue( IN HANDLE hKey, IN LPWSTR lpKeyName, OUT PVOID * ResultBuffer, OUT PULONG ResultLength, OUT PULONG KeyType) { NTSTATUS Status; UNICODE_STRING KeyName; ULONG Length; PKEY_VALUE_PARTIAL_INFORMATION PartialInformation; /* initialize key name */ RtlInitUnicodeString(&KeyName, lpKeyName); /* now query MatchingDeviceId key */ Status = ZwQueryValueKey(hKey, &KeyName, KeyValuePartialInformation, NULL, 0, &Length); /* check for success */ if (Status != STATUS_BUFFER_TOO_SMALL) return MM_STATUS_UNSUCCESSFUL; /* allocate a buffer for key data */ PartialInformation = AllocateItem(NonPagedPool, Length); if (!PartialInformation) return MM_STATUS_NO_MEMORY; /* now query MatchingDeviceId key */ Status = ZwQueryValueKey(hKey, &KeyName, KeyValuePartialInformation, PartialInformation, Length, &Length); /* check for success */ if (!NT_SUCCESS(Status)) { FreeItem(PartialInformation); return MM_STATUS_UNSUCCESSFUL; } if (KeyType) { /* return key type */ *KeyType = PartialInformation->Type; } if (ResultLength) { /* return data length */ *ResultLength = PartialInformation->DataLength; } *ResultBuffer = AllocateItem(NonPagedPool, PartialInformation->DataLength); if (!*ResultBuffer) { /* not enough memory */ FreeItem(PartialInformation); return MM_STATUS_NO_MEMORY; } /* copy key value */ RtlMoveMemory(*ResultBuffer, PartialInformation->Data, PartialInformation->DataLength); /* free key info */ FreeItem(PartialInformation); return MM_STATUS_SUCCESS; }
LRESULT APIENTRY co_IntCallWindowProc(WNDPROC Proc, BOOLEAN IsAnsiProc, HWND Wnd, UINT Message, WPARAM wParam, LPARAM lParam, INT lParamBufferSize) { WINDOWPROC_CALLBACK_ARGUMENTS StackArguments; PWINDOWPROC_CALLBACK_ARGUMENTS Arguments; NTSTATUS Status; PVOID ResultPointer, pActCtx; PWND pWnd; ULONG ResultLength; ULONG ArgumentLength; LRESULT Result; /* Do not allow the desktop thread to do callback to user mode */ ASSERT(PsGetCurrentThreadWin32Thread() != gptiDesktopThread); if (lParamBufferSize != -1) { ArgumentLength = sizeof(WINDOWPROC_CALLBACK_ARGUMENTS) + lParamBufferSize; Arguments = IntCbAllocateMemory(ArgumentLength); if (NULL == Arguments) { ERR("Unable to allocate buffer for window proc callback\n"); return -1; } RtlMoveMemory((PVOID) ((char *) Arguments + sizeof(WINDOWPROC_CALLBACK_ARGUMENTS)), (PVOID) lParam, lParamBufferSize); } else { Arguments = &StackArguments; ArgumentLength = sizeof(WINDOWPROC_CALLBACK_ARGUMENTS); } Arguments->Proc = Proc; Arguments->IsAnsiProc = IsAnsiProc; Arguments->Wnd = Wnd; Arguments->Msg = Message; Arguments->wParam = wParam; Arguments->lParam = lParam; Arguments->lParamBufferSize = lParamBufferSize; ResultPointer = NULL; ResultLength = ArgumentLength; IntSetTebWndCallback (&Wnd, &pWnd, &pActCtx); UserLeaveCo(); Status = KeUserModeCallback(USER32_CALLBACK_WINDOWPROC, Arguments, ArgumentLength, &ResultPointer, &ResultLength); _SEH2_TRY { /* Simulate old behaviour: copy into our local buffer */ RtlMoveMemory(Arguments, ResultPointer, ArgumentLength); } _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { ERR("Failed to copy result from user mode, Message %d lParam size %d!\n", Message, lParamBufferSize); Status = _SEH2_GetExceptionCode(); } _SEH2_END; UserEnterCo(); IntRestoreTebWndCallback (Wnd, pWnd, pActCtx); if (!NT_SUCCESS(Status)) { ERR("Call to user mode failed!\n"); if (lParamBufferSize != -1) { IntCbFreeMemory(Arguments); } return -1; } Result = Arguments->Result; if (lParamBufferSize != -1) { PTHREADINFO pti = PsGetCurrentThreadWin32Thread(); // Is this message being processed from inside kernel space? BOOL InSendMessage = (pti->pcti->CTI_flags & CTI_INSENDMESSAGE); TRACE("Copy lParam Message %d lParam %d!\n", Message, lParam); switch (Message) { default: TRACE("Don't copy lParam, Message %d Size %d lParam %d!\n", Message, lParamBufferSize, lParam); break; // Write back to user/kernel space. Also see g_MsgMemory. case WM_CREATE: case WM_GETMINMAXINFO: case WM_GETTEXT: case WM_NCCALCSIZE: case WM_NCCREATE: case WM_STYLECHANGING: case WM_WINDOWPOSCHANGING: case WM_SIZING: case WM_MOVING: TRACE("Copy lParam, Message %d Size %d lParam %d!\n", Message, lParamBufferSize, lParam); if (InSendMessage) // Copy into kernel space. RtlMoveMemory((PVOID) lParam, (PVOID) ((char *) Arguments + sizeof(WINDOWPROC_CALLBACK_ARGUMENTS)), lParamBufferSize); else { _SEH2_TRY { // Copy into user space. RtlMoveMemory((PVOID) lParam, (PVOID) ((char *) Arguments + sizeof(WINDOWPROC_CALLBACK_ARGUMENTS)), lParamBufferSize); } _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { ERR("Failed to copy lParam to user space, Message %d!\n", Message); } _SEH2_END; } break; } IntCbFreeMemory(Arguments); }
NTSTATUS WdmAudControlOpenMixer( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp, IN PWDMAUD_DEVICE_INFO DeviceInfo, IN PWDMAUD_CLIENT ClientInfo) { HANDLE hMixer; PWDMAUD_HANDLE Handles; //PWDMAUD_DEVICE_EXTENSION DeviceExtension; NTSTATUS Status; PKEVENT EventObject = NULL; DPRINT("WdmAudControlOpenMixer\n"); //DeviceExtension = (PWDMAUD_DEVICE_EXTENSION)DeviceObject->DeviceExtension; if (DeviceInfo->u.hNotifyEvent) { Status = ObReferenceObjectByHandle(DeviceInfo->u.hNotifyEvent, EVENT_MODIFY_STATE, *ExEventObjectType, UserMode, (LPVOID*)&EventObject, NULL); if (!NT_SUCCESS(Status)) { DPRINT1("Invalid notify event passed %p from client %p\n", DeviceInfo->u.hNotifyEvent, ClientInfo); DbgBreakPoint(); return SetIrpIoStatus(Irp, STATUS_UNSUCCESSFUL, 0); } } if (MMixerOpen(&MixerContext, DeviceInfo->DeviceIndex, ClientInfo, EventCallback, &hMixer) != MM_STATUS_SUCCESS) { ObDereferenceObject(EventObject); DPRINT1("Failed to open mixer\n"); return SetIrpIoStatus(Irp, STATUS_UNSUCCESSFUL, 0); } Handles = AllocateItem(NonPagedPool, sizeof(WDMAUD_HANDLE) * (ClientInfo->NumPins+1)); if (Handles) { if (ClientInfo->NumPins) { RtlMoveMemory(Handles, ClientInfo->hPins, sizeof(WDMAUD_HANDLE) * ClientInfo->NumPins); FreeItem(ClientInfo->hPins); } ClientInfo->hPins = Handles; ClientInfo->hPins[ClientInfo->NumPins].Handle = hMixer; ClientInfo->hPins[ClientInfo->NumPins].Type = MIXER_DEVICE_TYPE; ClientInfo->hPins[ClientInfo->NumPins].NotifyEvent = EventObject; ClientInfo->NumPins++; } else { ObDereferenceObject(EventObject); return SetIrpIoStatus(Irp, STATUS_UNSUCCESSFUL, sizeof(WDMAUD_DEVICE_INFO)); } DeviceInfo->hDevice = hMixer; return SetIrpIoStatus(Irp, STATUS_SUCCESS, sizeof(WDMAUD_DEVICE_INFO)); }
VOID Copy(PVOID Src, PVOID Dst, ULONG NumBytes) { RtlMoveMemory(Src, Dst, NumBytes); }
BOOL APIENTRY MoveFileExW( LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, DWORD dwFlags ) /*++ Routine Description: An existing file can be renamed using MoveFile. Arguments: lpExistingFileName - Supplies the name of an existing file that is to be renamed. lpNewFileName - Supplies the new name for the existing file. The new name must reside in the same file system/drive as the existing file and must not already exist. dwFlags - Supplies optional flag bits to control the behavior of the rename. The following bits are currently defined: MOVEFILE_REPLACE_EXISTING - if the new file name exists, replace it by renaming the old file name on top of the new file name. MOVEFILE_COPY_ALLOWED - if the new file name is on a different volume than the old file name, and causes the rename operation to fail, then setting this flag allows the MoveFileEx API call to simulate the rename with a call to CopyFile followed by a call to DeleteFile to the delete the old file if the CopyFile was successful. MOVEFILE_DELAY_UNTIL_REBOOT - dont actually do the rename now, but instead queue the rename so that it will happen the next time the system boots. If this flag is set, then the lpNewFileName parameter may be NULL, in which case a delay DeleteFile of the old file name will occur the next time the system is booted. The delay rename/delete operations occur immediately after AUTOCHK is run, but prior to creating any paging files, so it can be used to delete paging files from previous boots before they are reused. MOVEFILE_WRITE_THROUGH - perform the rename operation in such a way that the file has actually been moved on the disk before the API returns to the caller. Note that this flag causes a flush at the end of a copy operation (if one were allowed and necessary), and has no effect if the rename operation is delayed until the next reboot. Return Value: TRUE - The operation was successful. FALSE/NULL - The operation failed. Extended error status is available using GetLastError. --*/ { NTSTATUS Status; BOOLEAN ReplaceIfExists; OBJECT_ATTRIBUTES Obja; HANDLE Handle; UNICODE_STRING OldFileName; UNICODE_STRING NewFileName; IO_STATUS_BLOCK IoStatusBlock; PFILE_RENAME_INFORMATION NewName; BOOLEAN TranslationStatus; RTL_RELATIVE_NAME RelativeName; PVOID FreeBuffer; ULONG OpenFlags; BOOLEAN fDoCrossVolumeMove; BOOLEAN b; #ifdef _CAIRO_ OBJECTID oid; OBJECTID *poid; // only can be valid when fDoCrossVolumeMove = TRUE #else PVOID poid = NULL; #endif // // if the target is a device, do not allow the rename ! // if ( lpNewFileName ) { if ( RtlIsDosDeviceName_U((PWSTR)lpNewFileName) ) { SetLastError(ERROR_ALREADY_EXISTS); return FALSE; } } if (dwFlags & MOVEFILE_REPLACE_EXISTING) { ReplaceIfExists = TRUE; } else { ReplaceIfExists = FALSE; } TranslationStatus = RtlDosPathNameToNtPathName_U( lpExistingFileName, &OldFileName, NULL, &RelativeName ); if ( !TranslationStatus ) { SetLastError(ERROR_PATH_NOT_FOUND); return FALSE; } FreeBuffer = OldFileName.Buffer; if (!(dwFlags & MOVEFILE_DELAY_UNTIL_REBOOT)) { if ( RelativeName.RelativeName.Length ) { OldFileName = *(PUNICODE_STRING)&RelativeName.RelativeName; } else { RelativeName.ContainingDirectory = NULL; } InitializeObjectAttributes( &Obja, &OldFileName, OBJ_CASE_INSENSITIVE, RelativeName.ContainingDirectory, NULL ); // // Open the file for delete access // OpenFlags = FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT | (dwFlags & MOVEFILE_WRITE_THROUGH) ? FILE_WRITE_THROUGH : 0; Status = NtOpenFile( &Handle, #ifdef _CAIRO_ FILE_READ_ATTRIBUTES | #endif (ACCESS_MASK)DELETE | SYNCHRONIZE, &Obja, &IoStatusBlock, FILE_SHARE_READ | FILE_SHARE_WRITE, OpenFlags ); if ( !NT_SUCCESS(Status) ) { RtlFreeHeap(RtlProcessHeap(), 0, FreeBuffer); BaseSetLastNTError(Status); return FALSE; } } if (!(dwFlags & MOVEFILE_DELAY_UNTIL_REBOOT) || (lpNewFileName != NULL)) { TranslationStatus = RtlDosPathNameToNtPathName_U( lpNewFileName, &NewFileName, NULL, NULL ); if ( !TranslationStatus ) { RtlFreeHeap(RtlProcessHeap(), 0, FreeBuffer); SetLastError(ERROR_PATH_NOT_FOUND); NtClose(Handle); return FALSE; } } else { RtlInitUnicodeString( &NewFileName, NULL ); } if (dwFlags & MOVEFILE_DELAY_UNTIL_REBOOT) { // // copy allowed is not permitted on delayed renames // // // (typical stevewo hack, preserved for sentimental value) // // If ReplaceIfExists is TRUE, prepend an exclamation point // to the new filename in order to pass this bit of data // along to the session manager. // if (ReplaceIfExists && (NewFileName.Length != 0)) { PWSTR NewBuffer; NewBuffer = RtlAllocateHeap( RtlProcessHeap(), MAKE_TAG( TMP_TAG ), NewFileName.Length + sizeof(WCHAR) ); if (NewBuffer != NULL) { NewBuffer[0] = L'!'; CopyMemory(&NewBuffer[1], NewFileName.Buffer, NewFileName.Length); NewFileName.Length += sizeof(WCHAR); NewFileName.MaximumLength += sizeof(WCHAR); RtlFreeHeap(RtlProcessHeap(), 0, NewFileName.Buffer); NewFileName.Buffer = NewBuffer; } } if ( dwFlags & MOVEFILE_COPY_ALLOWED ) { Status = STATUS_INVALID_PARAMETER; } else { Status = BasepMoveFileDelayed(&OldFileName, &NewFileName); } RtlFreeHeap(RtlProcessHeap(), 0, FreeBuffer); RtlFreeHeap(RtlProcessHeap(), 0, NewFileName.Buffer); if (NT_SUCCESS(Status)) { return(TRUE); } else { BaseSetLastNTError(Status); return(FALSE); } } RtlFreeHeap(RtlProcessHeap(), 0, FreeBuffer); FreeBuffer = NewFileName.Buffer; NewName = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( TMP_TAG ), NewFileName.Length+sizeof(*NewName)); if (NewName != NULL) { RtlMoveMemory( NewName->FileName, NewFileName.Buffer, NewFileName.Length ); NewName->ReplaceIfExists = ReplaceIfExists; NewName->RootDirectory = NULL; NewName->FileNameLength = NewFileName.Length; RtlFreeHeap(RtlProcessHeap(), 0, FreeBuffer); Status = NtSetInformationFile( Handle, &IoStatusBlock, NewName, NewFileName.Length+sizeof(*NewName), FileRenameInformation ); RtlFreeHeap(RtlProcessHeap(), 0, NewName); } else { Status = STATUS_NO_MEMORY; } fDoCrossVolumeMove = (Status == STATUS_NOT_SAME_DEVICE) && (dwFlags & MOVEFILE_COPY_ALLOWED); #ifdef _CAIRO_ if (fDoCrossVolumeMove) { // Get the object'd OBJECTID poid = RtlQueryObjectId(Handle, &oid) == STATUS_SUCCESS ? &oid : NULL; } #endif NtClose(Handle); if ( NT_SUCCESS(Status) ) { return TRUE; } else if ( fDoCrossVolumeMove ) { HELPER_CONTEXT Context; Context.pObjectId = poid; Context.dwFlags = dwFlags; b = CopyFileExW( lpExistingFileName, lpNewFileName, poid || dwFlags & MOVEFILE_WRITE_THROUGH ? BasepCrossVolumeMoveHelper : NULL, &Context, NULL, ReplaceIfExists ? 0 : COPY_FILE_FAIL_IF_EXISTS ); if ( b ) { // // the copy worked... Delete the source of the rename // if it fails, try a set attributes and then a delete // if (!DeleteFileW( lpExistingFileName ) ) { // // If the delete fails, we will return true, but possibly // leave the source dangling // SetFileAttributesW(lpExistingFileName,FILE_ATTRIBUTE_NORMAL); DeleteFileW( lpExistingFileName ); } return TRUE; } else { return FALSE; } } else { BaseSetLastNTError(Status); return FALSE; } }
VOID DumpEvent( IN PRTL_EVENT Event, IN PRTL_EVENT_ID_INFO EventId ) { ULONG i, j; PRTL_EVENT_PARAMETER_INFO ParameterInfo; PRTL_EVENT_PARAMETER_VALUE_INFO ValueInfo; PULONG ParameterData; USHORT StackBackTraceLength; ULONG StackBackTrace[ MAX_STACK_DEPTH ]; ULONG NumberFlagsFound; PWSTR Src; LPSTR AnsiSrc; CHAR NameBuffer[ 256 ]; printf( "%04x.%04x - %s(", Event->ClientId.UniqueProcess, Event->ClientId.UniqueThread, EventId->Name ); ParameterData = (PULONG)((PCHAR)Event + Event->OffsetToParameterData); if (StackBackTraceLength = Event->StackBackTraceLength) { RtlMoveMemory( StackBackTrace, (Event + 1), StackBackTraceLength * sizeof( ULONG )); } ParameterInfo = (PRTL_EVENT_PARAMETER_INFO) ((PCHAR)EventId + EventId->OffsetToParameterInfo); for (i=0; i<EventId->NumberOfParameters; i++) { if (i != 0) { printf( "," ); } if (ParameterInfo->Label[ 0 ] != '\0') { printf( " %s: ", ParameterInfo->Label ); } else { printf( " " ); } switch( ParameterInfo->Type ) { // // No additional data for these parameter types; // case RTL_EVENT_STATUS_PARAM: if (PageFaultEventId == EventId) { switch (*ParameterData) { case STATUS_PAGE_FAULT_TRANSITION: AnsiSrc = "Transition"; break; case STATUS_PAGE_FAULT_DEMAND_ZERO: AnsiSrc = "DemandZero"; break; case STATUS_PAGE_FAULT_COPY_ON_WRITE: AnsiSrc = "CopyOnWrite"; break; case STATUS_PAGE_FAULT_GUARD_PAGE: AnsiSrc = "Guard"; break; case STATUS_PAGE_FAULT_PAGING_FILE: AnsiSrc = "Disk"; break; default: AnsiSrc = NULL; break; } } else { AnsiSrc = FindSymbolicNameForStatus( *ParameterData ); } if (AnsiSrc) { printf( "%s", AnsiSrc ); ParameterData += 1; break; } case RTL_EVENT_ULONG_PARAM: printf( "%08x", *ParameterData++ ); break; case RTL_EVENT_ADDRESS_PARAM: GetSymbolicNameForAddress( Event->ClientId.UniqueProcess, *ParameterData++, NameBuffer, sizeof( NameBuffer ) ); printf( "%s", NameBuffer ); break; case RTL_EVENT_ENUM_PARAM: ValueInfo = (PRTL_EVENT_PARAMETER_VALUE_INFO)((PCHAR)ParameterInfo + ParameterInfo->OffsetToValueNames); for (j=0; j<ParameterInfo->NumberOfValueNames; j++) { if (ValueInfo->Value == *ParameterData) { ParameterData += 1; printf( "%s", ValueInfo->ValueName ); ValueInfo = NULL; break; } ValueInfo = (PRTL_EVENT_PARAMETER_VALUE_INFO) ((PCHAR)ValueInfo + ValueInfo->Length); } if (ValueInfo) { printf( "%08x", *ParameterData++ ); } break; case RTL_EVENT_FLAGS_PARAM: ValueInfo = (PRTL_EVENT_PARAMETER_VALUE_INFO)((PCHAR)ParameterInfo + ParameterInfo->OffsetToValueNames); NumberFlagsFound = 0; for (j=0; j<ParameterInfo->NumberOfValueNames; j++) { if (ValueInfo->Value & *ParameterData) { if (NumberFlagsFound++ != 0) { printf( " | " ); } printf( "%s", ValueInfo->ValueName ); } ValueInfo = (PRTL_EVENT_PARAMETER_VALUE_INFO) ((PCHAR)ValueInfo + ValueInfo->Length); } if (NumberFlagsFound == 0) { printf( "%08x", *ParameterData ); } ParameterData += 1; break; case RTL_EVENT_PWSTR_PARAM: case RTL_EVENT_PUNICODE_STRING_PARAM: Src = (PWSTR)ParameterData; printf( "'%ws'", Src ); while (*Src++) { } ParameterData = (PULONG)ALIGN_UP( Src, ULONG ); break; case RTL_EVENT_PANSI_STRING_PARAM: AnsiSrc = (LPSTR)ParameterData; printf( "'%s'", AnsiSrc ); while (*AnsiSrc++) { } ParameterData = (PULONG)ALIGN_UP( AnsiSrc, ULONG ); break; case RTL_EVENT_STRUCTURE_PARAM: default: break; } ParameterInfo = (PRTL_EVENT_PARAMETER_INFO) ((PCHAR)ParameterInfo + ParameterInfo->Length); } printf( " )\n" ); for (i=0; i<StackBackTraceLength; i++) { GetSymbolicNameForAddress( Event->ClientId.UniqueProcess, StackBackTrace[ i ], NameBuffer, sizeof( NameBuffer ) ); printf( " %s\n", NameBuffer ); } printf( " )\n" ); return; }
MIXER_STATUS MMixerOpenMidiPin( IN PMIXER_CONTEXT MixerContext, IN PMIXER_LIST MixerList, IN ULONG DeviceId, IN ULONG PinId, IN ACCESS_MASK DesiredAccess, IN PIN_CREATE_CALLBACK CreateCallback, IN PVOID Context, OUT PHANDLE PinHandle) { PKSPIN_CONNECT PinConnect; PKSDATAFORMAT DataFormat; LPMIXER_DATA MixerData; NTSTATUS Status; MIXER_STATUS MixerStatus; MixerData = MMixerGetDataByDeviceId(MixerList, DeviceId); if (!MixerData) return MM_STATUS_INVALID_PARAMETER; /* allocate pin connect */ PinConnect = MMixerAllocatePinConnect(MixerContext, sizeof(KSDATAFORMAT)); if (!PinConnect) { /* no memory */ return MM_STATUS_NO_MEMORY; } /* initialize pin connect struct */ MMixerInitializePinConnect(PinConnect, PinId); /* get offset to dataformat */ DataFormat = (PKSDATAFORMAT) (PinConnect + 1); /* initialize data format */ RtlMoveMemory(&DataFormat->MajorFormat, &KSDATAFORMAT_TYPE_MUSIC, sizeof(GUID)); RtlMoveMemory(&DataFormat->SubFormat, &KSDATAFORMAT_SUBTYPE_MIDI, sizeof(GUID)); RtlMoveMemory(&DataFormat->Specifier, &KSDATAFORMAT_SPECIFIER_NONE, sizeof(GUID)); if (CreateCallback) { /* let the callback handle the creation */ MixerStatus = CreateCallback(Context, DeviceId, PinId, MixerData->hDevice, PinConnect, DesiredAccess, PinHandle); } else { /* now create the pin */ Status = KsCreatePin(MixerData->hDevice, PinConnect, DesiredAccess, PinHandle); /* normalize status */ if (Status == STATUS_SUCCESS) MixerStatus = MM_STATUS_SUCCESS; else MixerStatus = MM_STATUS_UNSUCCESSFUL; } /* free create info */ MixerContext->Free(PinConnect); /* done */ return MixerStatus; }
BOOL EditSymbols( LPSTR pImageName, LPSTR pDbgFileName ) { PIMAGE_NT_HEADERS NtHeaders; HANDLE FileHandle, SymbolFileHandle; HANDLE hMappedFile; LPVOID ImageBase; PIMAGE_DEBUG_DIRECTORY DebugDirectories; PIMAGE_DEBUG_DIRECTORY DebugDirectoriesSave; DWORD DebugDirectorySize, NumberOfDebugDirectories; DWORD SavedErrorCode; PIMAGE_DEBUG_DIRECTORY DebugDirectory; DWORD i; DWORD NewFileSize, HeaderSum, CheckSum; DWORD ImageNameOffset, DebugDataSize; LPBYTE DebugData; IMAGE_SEPARATE_DEBUG_HEADER DbgFileHeader; ImageBase = NULL; hMappedFile = 0; FileHandle = SymbolFileHandle = 0; DebugDirectoriesSave = NULL; // // open and map the file. // FileHandle = CreateFile( pImageName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if (FileHandle == INVALID_HANDLE_VALUE) { return FALSE; } hMappedFile = CreateFileMapping( FileHandle, NULL, PAGE_READWRITE, 0, 0, NULL ); if (!hMappedFile) { CloseHandle( FileHandle ); return FALSE; } ImageBase = MapViewOfFile( hMappedFile, FILE_MAP_WRITE, 0, 0, 0 ); if (!ImageBase) { CloseHandle( hMappedFile ); CloseHandle( FileHandle ); return FALSE; } // // Everything is mapped. Now check the image and find nt image headers // NtHeaders = ImageNtHeader( ImageBase ); if (NtHeaders == NULL) { SetLastError( ERROR_BAD_EXE_FORMAT ); goto nosyms; } if ((NtHeaders->OptionalHeader.MajorLinkerVersion < 3) && (NtHeaders->OptionalHeader.MinorLinkerVersion < 5) ) { SetLastError( ERROR_BAD_EXE_FORMAT ); goto nosyms; } if (!(NtHeaders->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED)) { SetLastError( ERROR_ALREADY_ASSIGNED ); goto nosyms; } DebugDirectories = (PIMAGE_DEBUG_DIRECTORY) ImageDirectoryEntryToData( ImageBase, FALSE, IMAGE_DIRECTORY_ENTRY_DEBUG, &DebugDirectorySize ); if (!DebugDirectoryIsUseful(DebugDirectories, DebugDirectorySize)) { SetLastError( ERROR_BAD_EXE_FORMAT ); goto nosyms; } NumberOfDebugDirectories = DebugDirectorySize / sizeof( IMAGE_DEBUG_DIRECTORY ); SymbolFileHandle = CreateFile( pDbgFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if (SymbolFileHandle == INVALID_HANDLE_VALUE) goto nosyms; if (!ReadFile( SymbolFileHandle, &DbgFileHeader, sizeof(DbgFileHeader), &DebugDataSize, NULL) || DebugDataSize != sizeof(DbgFileHeader)) { SetLastError( ERROR_BAD_EXE_FORMAT ); goto nosyms; } if (DbgFileHeader.Signature != IMAGE_SEPARATE_DEBUG_SIGNATURE || (DbgFileHeader.Flags & ~IMAGE_SEPARATE_DEBUG_FLAGS_MASK) != 0 || DbgFileHeader.Machine != NtHeaders->FileHeader.Machine || DbgFileHeader.Characteristics != NtHeaders->FileHeader.Characteristics || DbgFileHeader.TimeDateStamp != NtHeaders->FileHeader.TimeDateStamp || DbgFileHeader.CheckSum != NtHeaders->OptionalHeader.CheckSum || DbgFileHeader.ImageBase != NtHeaders->OptionalHeader.ImageBase || DbgFileHeader.SizeOfImage != NtHeaders->OptionalHeader.SizeOfImage) { SetLastError( ERROR_BAD_EXE_FORMAT ); goto nosyms; } if (DbgFileHeader.Flags & IMAGE_SEPARATE_DEBUG_MISMATCH) { fprintf(stderr, "Warning: %s updated unsafely; symbols may be wrong\n", pDbgFileName); } // check if this is the right dbg file // save the DebugDirectory and get ready to write the // debug data to the image file. DebugDirectoriesSave = (PIMAGE_DEBUG_DIRECTORY) malloc( DebugDirectorySize ); if (DebugDirectoriesSave == NULL) goto nosyms; RtlMoveMemory( DebugDirectoriesSave, DebugDirectories, DebugDirectorySize); DebugDirectory = DebugDirectoriesSave; NewFileSize = SetFilePointer( FileHandle, 0, NULL, FILE_END ); NewFileSize = (NewFileSize + 3) & ~3; for (i=0; i<NumberOfDebugDirectories; i++) { // Is it one of the debug sections we need to special case? if (DebugDirectory->Type == IMAGE_DEBUG_TYPE_MISC) { // fix the mage name ImageNameOffset = (DWORD) ((PCHAR) ImageBase + DebugDirectory->PointerToRawData + FIELD_OFFSET( IMAGE_DEBUG_MISC, Data )); RtlCopyMemory((LPVOID)ImageNameOffset, FilePart, strlen(FilePart) + 1); } else if (DebugDirectory->Type != IMAGE_DEBUG_TYPE_FPO) { DebugData = (LPBYTE) malloc( DebugDirectory->SizeOfData ); if (SetFilePointer( SymbolFileHandle, DebugDirectory->PointerToRawData, NULL, FILE_BEGIN ) != DebugDirectory->PointerToRawData) { SetLastError( ERROR_BAD_EXE_FORMAT ); goto nosyms; } if (ReadFile( SymbolFileHandle, DebugData, DebugDirectory->SizeOfData, &DebugDataSize, NULL) && DebugDataSize == DebugDirectory->SizeOfData) { if (WriteFile( FileHandle, DebugData, DebugDirectory->SizeOfData, &DebugDataSize, NULL) && DebugDataSize == DebugDirectory->SizeOfData) { DebugDirectory->PointerToRawData = NewFileSize; NewFileSize += DebugDataSize; NewFileSize = (NewFileSize + 3) & ~3; } else { SetLastError( ERROR_WRITE_FAULT ); free( DebugData ); goto nosyms; } } else { SetLastError( ERROR_BAD_EXE_FORMAT ); free( DebugData ); goto nosyms; } free( DebugData ); } DebugDirectory += 1; } // somehow I needed to close the file and re-open it again. // otherwise it would AV inside CheckSumMappedFile. UnmapViewOfFile( ImageBase ); CloseHandle( hMappedFile ); ImageBase = NULL; hMappedFile = 0; SetFilePointer( FileHandle, NewFileSize, NULL, FILE_BEGIN ); SetEndOfFile( FileHandle ); CloseHandle( FileHandle ); // // re-open and map the file. // FileHandle = CreateFile( pImageName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); hMappedFile = CreateFileMapping( FileHandle, NULL, PAGE_READWRITE, 0, 0, NULL ); if (!hMappedFile) { goto nosyms; } ImageBase = MapViewOfFile( hMappedFile, FILE_MAP_WRITE, 0, 0, 0 ); if (!ImageBase) { goto nosyms; } NtHeaders = ImageNtHeader( ImageBase ); if (NtHeaders == NULL) { SetLastError( ERROR_BAD_EXE_FORMAT ); goto nosyms; } DebugDirectories = (PIMAGE_DEBUG_DIRECTORY) ImageDirectoryEntryToData( ImageBase, FALSE, IMAGE_DIRECTORY_ENTRY_DEBUG, &DebugDirectorySize ); if (DebugDirectories == NULL || DebugDirectorySize == 0) { SetLastError( ERROR_BAD_EXE_FORMAT ); goto nosyms; } RtlMoveMemory( DebugDirectories, DebugDirectoriesSave, DebugDirectorySize); free( DebugDirectoriesSave ); NtHeaders->FileHeader.Characteristics &= ~IMAGE_FILE_DEBUG_STRIPPED; CheckSumMappedFile( ImageBase, NewFileSize, &HeaderSum, &CheckSum ); NtHeaders->OptionalHeader.CheckSum = CheckSum; CloseHandle( SymbolFileHandle ); UnmapViewOfFile( ImageBase ); CloseHandle( hMappedFile ); CloseHandle( FileHandle ); return TRUE; nosyms: SavedErrorCode = GetLastError(); if (DebugDirectoriesSave) free( DebugDirectoriesSave ); if (SymbolFileHandle && SymbolFileHandle != INVALID_HANDLE_VALUE) { CloseHandle( SymbolFileHandle ); } if (ImageBase) UnmapViewOfFile( ImageBase ); if (hMappedFile) CloseHandle( hMappedFile ); if (FileHandle && FileHandle != INVALID_HANDLE_VALUE) { CloseHandle( FileHandle ); } SetLastError( SavedErrorCode ); return FALSE; }
//失败返回0 ULONG GetTargetProtocolBlockWin7(char *ProName, DWORD dwLen) { UNICODE_STRING uniNPF; ULONG uHeader=0; NTSTATUS status = STATUS_SUCCESS; PNDIS_PROTOCOL_BLOCKWin7 pProtoBLock=NULL; BOOLEAN bFound = FALSE; PNDIS_PROTOCOL_BLOCKWin7 pNpfProtocolBlock=NULL; char szBuffer[1024]; ANSI_STRING aniStr1; RtlZeroMemory(szBuffer, sizeof(szBuffer)); if (dwLen>sizeof(szBuffer)) { return STATUS_UNSUCCESSFUL; } RtlMoveMemory(szBuffer, ProName, dwLen); RtlInitAnsiString(&aniStr1, szBuffer); RtlAnsiStringToUnicodeString(&uniNPF, &aniStr1, TRUE); do { uHeader = GetProtocolHeader(); if (uHeader==0) { status = STATUS_UNSUCCESSFUL; break; } pProtoBLock = (PNDIS_PROTOCOL_BLOCKWin7)uHeader; while(pProtoBLock) { if (RtlEqualUnicodeString(&pProtoBLock->Name, &uniNPF,TRUE)) { bFound = TRUE; break; } pProtoBLock = (PNDIS_PROTOCOL_BLOCKWin7)pProtoBLock->NextProtocol; } if (!bFound) { kprintf("Can not find protocol name: %s\n", ProName); break; } pNpfProtocolBlock = pProtoBLock; //NdisDeregisterProtocol(&status, (NDIS_HANDLE)uHeader); // deregister it } while (0); RtlFreeUnicodeString(&uniNPF); return (ULONG)pNpfProtocolBlock; }