Exemplo n.º 1
0
//在这里InlineHook
VOID monitor2_inlineHookObReferenceObjectByHandle()
{

	//赋值前面定义的数组
	KIRQL Irql;

	//保存函数前五个字节内容
	RtlCopyMemory(OldObAddress,(PBYTE)ObReferenceObjectByHandle,5);
	//保存新函数五个字节之后偏移
	*(PULONG)(NewObAddress+1)=(ULONG)NewObReferenceObjectByHandle-((ULONG)ObReferenceObjectByHandle+5);

	//开始inline hook
	//关闭内存写保护
	UnProtected();

	//提升IRQL中断级
	Irql=KeRaiseIrqlToDpcLevel();
	//函数开头五个字节写JMP 
	RtlCopyMemory((PBYTE)ObReferenceObjectByHandle,NewObAddress,5);
	//恢复Irql
	KeLowerIrql(Irql);

	//开启内存写保护
	Protected();
}
Exemplo n.º 2
0
/* KphReleaseProcessorLock
 *
 * Allows threads to execute on other processors and restores the IRQL.
 *
 * ProcessorLock: A processor lock structure that is present in
 * non-paged memory.
 *
 * Comments:
 * Here is how the processor lock is released:
 *  1. Sets the signal to release the processors. The DPCs that are
 *     currently waiting for the signal will return and decrement
 *     the acquired processors counter.
 *  2. Waits for the acquired processors counter to become zero.
 *  3. Restores the old IRQL. This will always be APC_LEVEL due to
 *     the mutex.
 *  4. Frees the storage allocated for the DPCs.
 *  5. Releases the processor lock mutex. This will restore the IRQL
 *     back to normal.
 * Thread safety: Full
 * IRQL: DISPATCH_LEVEL
 */
VOID KphReleaseProcessorLock(
    __inout PKPH_PROCESSOR_LOCK ProcessorLock
)
{
    if (!ProcessorLock->Acquired)
        return;

    /* Signal for the acquired processors to be released. */
    InterlockedExchange(&ProcessorLock->ReleaseSignal, 1);

    /* Spinwait for all acquired processors to be released. */
    KphSpinUntilEqual(&ProcessorLock->AcquiredProcessors, 0);

    dprintf("KphReleaseProcessorLock: All processors released.\n");

    /* Restore the old IRQL (should always be APC_LEVEL due to the
     * fast mutex). */
    KeLowerIrql(ProcessorLock->OldIrql);

    /* Free the DPCs if necessary. */
    if (ProcessorLock->Dpcs != NULL)
    {
        ExFreePoolWithTag(ProcessorLock->Dpcs, TAG_SYNC_DPC);
        ProcessorLock->Dpcs = NULL;
    }

    ProcessorLock->Acquired = FALSE;

    /* Release the processor lock guarded lock. This will restore the
     * IRQL back to what it was before the processor lock was
     * acquired.
     */
    KphReleaseGuardedLock(&ProcessorLock->Lock);
}
Exemplo n.º 3
0
VOID
XenPci_HighSync(PXENPCI_HIGHSYNC_FUNCTION function0, PXENPCI_HIGHSYNC_FUNCTION functionN, PVOID context)
{
  ULONG ActiveProcessorCount;
  ULONG i;
  highsync_info_t *highsync_info;
  KIRQL old_irql;

  UNREFERENCED_PARAMETER(context);
  FUNCTION_ENTER();

  highsync_info = ExAllocatePoolWithTag(NonPagedPool, sizeof(highsync_info_t), XENPCI_POOL_TAG);
  RtlZeroMemory(highsync_info, sizeof(highsync_info_t));
  KeInitializeEvent(&highsync_info->highsync_complete_event, SynchronizationEvent, FALSE);
  highsync_info->function0 = function0;
  highsync_info->functionN = functionN;
  highsync_info->context = context;
  highsync_info->sync_level = HIGH_LEVEL;

#if (NTDDI_VERSION >= NTDDI_WINXP)
  ActiveProcessorCount = (ULONG)KeNumberProcessors;
#else
  ActiveProcessorCount = (ULONG)*KeNumberProcessors;
#endif

  /* Go to HIGH_LEVEL to prevent any races with Dpc's on the current processor */
  KeRaiseIrql(highsync_info->sync_level, &old_irql);

  highsync_info->do_spin = TRUE;
  for (i = 0; i < ActiveProcessorCount; i++)
  {
    if (i == 0)
      KeInitializeDpc(&highsync_info->dpcs[i], XenPci_HighSyncCallFunction0, highsync_info);
    else
      KeInitializeDpc(&highsync_info->dpcs[i], XenPci_HighSyncCallFunctionN, highsync_info);
    KeSetTargetProcessorDpc(&highsync_info->dpcs[i], (CCHAR)i);
    KeSetImportanceDpc(&highsync_info->dpcs[i], HighImportance);
    KdPrint((__DRIVER_NAME "     queuing Dpc for CPU %d\n", i));
    KeInsertQueueDpc(&highsync_info->dpcs[i], NULL, NULL);
  }
  KdPrint((__DRIVER_NAME "     All Dpc's queued\n"));

  KeMemoryBarrier();
  KeLowerIrql(old_irql);

  KdPrint((__DRIVER_NAME "     Waiting for highsync_complete_event\n"));
  KeWaitForSingleObject(&highsync_info->highsync_complete_event, Executive, KernelMode, FALSE, NULL);
#if (NTDDI_VERSION >= NTDDI_WINXP)
  KeFlushQueuedDpcs();
#else
  {
    /* just wait 1 second until all DPC's finish - not ideal but it's only for W2K */
    LARGE_INTEGER interval;
    interval.QuadPart = -1 * 1000 * 1000 * 10; /* 1 second */
    KeDelayExecutionThread(KernelMode, FALSE, &interval);
  }
#endif
  ExFreePoolWithTag(highsync_info, XENPCI_POOL_TAG);
  FUNCTION_EXIT();
}
Exemplo n.º 4
0
_Use_decl_annotations_ bool __stdcall VmmVmExitHandler(VmmInitialStack *stack) {
  // Save guest's context and raise IRQL as quick as possible
  const auto guest_irql = KeGetCurrentIrql();
  const auto guest_cr8 = IsX64() ? __readcr8() : 0;
  if (guest_irql < DISPATCH_LEVEL) {
    KeRaiseIrqlToDpcLevel();
  }
  NT_ASSERT(stack->reserved == MAXULONG_PTR);

  // Capture the current guest state
  GuestContext guest_context = {stack,
                                UtilVmRead(VmcsField::kGuestRflags),
                                UtilVmRead(VmcsField::kGuestRip),
                                guest_cr8,
                                guest_irql,
                                true};
  guest_context.gp_regs->sp = UtilVmRead(VmcsField::kGuestRsp);

  // Dispatch the current VM-exit event
  VmmpHandleVmExit(&guest_context);

  // Restore guest's context
  if (guest_context.irql < DISPATCH_LEVEL) {
    KeLowerIrql(guest_context.irql);
  }

  // Apply possibly updated CR8 by the handler
  if (IsX64()) {
    __writecr8(guest_context.cr8);
  }
  return guest_context.vm_continue;
}
Exemplo n.º 5
0
/*
 * @implemented
 */
VOID
NTAPI
KeGenericCallDpc(IN PKDEFERRED_ROUTINE Routine,
                 IN PVOID Context)
{
    ULONG Barrier = KeNumberProcessors;
    KIRQL OldIrql;
    DEFERRED_REVERSE_BARRIER ReverseBarrier;
    ASSERT(KeGetCurrentIrql () < DISPATCH_LEVEL);

    //
    // The barrier is the number of processors, each processor will decrement it
    // by one, so when all processors have run the DPC, the barrier reaches zero
    //
    ReverseBarrier.Barrier = Barrier;
    ReverseBarrier.TotalProcessors = Barrier;

    //
    // But we don't need the barrier on UP, since we can simply call the routine
    // directly while at DISPATCH_LEVEL and not worry about anything else
    //
    KeRaiseIrql(DISPATCH_LEVEL, &OldIrql);
    Routine(&KeGetCurrentPrcb()->CallDpc, Context, &Barrier, &ReverseBarrier);
    KeLowerIrql(OldIrql);
}
Exemplo n.º 6
0
static
VOID
NTAPI
AcquireMutexThread(
    PVOID Parameter)
{
    PTHREAD_DATA ThreadData = Parameter;
    KIRQL Irql;
    BOOLEAN Ret = FALSE;
    NTSTATUS Status;

    KeRaiseIrql(ThreadData->Irql, &Irql);

    if (ThreadData->Try)
    {
        Ret = ThreadData->TryAcquire(ThreadData->Mutex);
        ok_eq_bool(Ret, ThreadData->RetExpected);
    }
    else
        ThreadData->Acquire(ThreadData->Mutex);

    ok_bool_false(KeSetEvent(&ThreadData->OutEvent, 0, TRUE), "KeSetEvent returned");
    Status = KeWaitForSingleObject(&ThreadData->InEvent, Executive, KernelMode, FALSE, NULL);
    ok_eq_hex(Status, STATUS_SUCCESS);

    if (!ThreadData->Try || Ret)
        ThreadData->Release(ThreadData->Mutex);

    KeLowerIrql(Irql);
}
Exemplo n.º 7
0
VOID NBDestroyNeighborsForInterface(PIP_INTERFACE Interface)
{
    KIRQL OldIrql;
    PNEIGHBOR_CACHE_ENTRY *PrevNCE;
    PNEIGHBOR_CACHE_ENTRY NCE;
    ULONG i;

    KeRaiseIrql(DISPATCH_LEVEL, &OldIrql);
    for (i = 0; i <= NB_HASHMASK; i++)
    {
        TcpipAcquireSpinLockAtDpcLevel(&NeighborCache[i].Lock);
        
        for (PrevNCE = &NeighborCache[i].Cache;
             (NCE = *PrevNCE) != NULL;)
        {
            if (NCE->Interface == Interface)
            {
                /* Unlink and destroy the NCE */
                *PrevNCE = NCE->Next;

                NBFlushPacketQueue(NCE, NDIS_STATUS_REQUEST_ABORTED);
                ExFreePoolWithTag(NCE, NCE_TAG);

                continue;
            }
            else
            {
                PrevNCE = &NCE->Next;
            }
        }
        
        TcpipReleaseSpinLockFromDpcLevel(&NeighborCache[i].Lock);
    }
    KeLowerIrql(OldIrql);
}
Exemplo n.º 8
0
NTSTATUS	ResponsePortAskWorkerForIndicateupPacket(PDEVICE_OBJECT  DeviceObject, PVOID	pContext)
{
	PASKUserWorkItemContext	pPAskContext=NULL;
	NTSTATUS		status	=	STATUS_SUCCESS;
	PAcceptedPort	pIndicateContext=NULL;
	KIRQL			CIrql=0, CIrql2=0;
	//__asm int 3
	CIrql	=	KeGetCurrentIrql();
	pPAskContext	=	(PASKUserWorkItemContext)pContext;
	if (pPAskContext==NULL)
	{
		return status;
	}
	pIndicateContext	=	(PAcceptedPort)pPAskContext->pContext;
	IoFreeWorkItem(pPAskContext->pWorkItem);
	kfree(pPAskContext);
	
	//自定义向上提交一份
	status = BypassTcpipArpRcv((NDIS_HANDLE)pIndicateContext->ProtocolBindingContext, (NDIS_HANDLE)pIndicateContext->MacReceiveContext, pIndicateContext->HeaderBuffer, pIndicateContext->HeaderBufferSize,\
		pIndicateContext->LookAheadBuffer, pIndicateContext->LookAheadBufferSize, pIndicateContext->LookAheadBufferSize);
	if (KeGetCurrentIrql()>CIrql)
	{
		KeLowerIrql(CIrql);
	}
	if (KeGetCurrentIrql()<CIrql)
	{
		KeRaiseIrql(CIrql, &CIrql2);
	}
	kfree(pIndicateContext);
	return status;

}
Exemplo n.º 9
0
VOID
NTAPI
PspSystemThreadStartup(IN PKSTART_ROUTINE StartRoutine,
                       IN PVOID StartContext)
{
    PETHREAD Thread;
    PSTRACE(PS_THREAD_DEBUG,
            "StartRoutine: %p StartContext: %p\n", StartRoutine, StartContext);

    /* Unlock the dispatcher Database */
    KeLowerIrql(PASSIVE_LEVEL);
    Thread = PsGetCurrentThread();

    /* Make sure the thread isn't gone */
    _SEH2_TRY
    {
        if (!(Thread->Terminated) && !(Thread->DeadThread))
        {
            /* Call the Start Routine */
            StartRoutine(StartContext);
        }
    }
    _SEH2_EXCEPT(PspUnhandledExceptionInSystemThread(_SEH2_GetExceptionInformation()))
    {
        /* Bugcheck if we got here */
        KeBugCheck(KMODE_EXCEPTION_NOT_HANDLED);
    }
    _SEH2_END;

    /* Exit the thread */
    PspTerminateThreadByPointer(Thread, STATUS_SUCCESS, TRUE);
}
Exemplo n.º 10
0
VOID
NTAPI
VdmEndExecution(IN PKTRAP_FRAME TrapFrame,
                IN PVDM_TIB VdmTib)
{
    KIRQL OldIrql;
    CONTEXT Context;
    PAGED_CODE();

    /* Sanity check */
    ASSERT((TrapFrame->EFlags & EFLAGS_V86_MASK) ||
           (TrapFrame->SegCs != (KGDT_R3_CODE | RPL_MASK)));

    /* Raise to APC_LEVEL */
    KeRaiseIrql(APC_LEVEL, &OldIrql);

    /* Set success */
    VdmTib->MonitorContext.Eax = STATUS_SUCCESS;

    /* Make a copy of the monitor context */
    Context = VdmTib->MonitorContext;
    
    /* Check if V86 mode was enabled or the trap was edited */
    if ((Context.EFlags & EFLAGS_V86_MASK) || (Context.SegCs & FRAME_EDITED))
    {
        /* Switch contexts */
        VdmSwapContext(TrapFrame, &VdmTib->VdmContext, &Context);

        /* Check if VME is supported and V86 mode was enabled */
        if ((KeI386VirtualIntExtensions) &&
            (VdmTib->VdmContext.EFlags & EFLAGS_V86_MASK))
        {
            /* Check for VIF (virtual interrupt) flag state */
            if (VdmTib->VdmContext.EFlags & EFLAGS_VIF)
            {
                /* Set real IF flag */
                VdmTib->VdmContext.EFlags |= EFLAGS_INTERRUPT_MASK;
            }
            else
            {
                /* Remove real IF flag */
                VdmTib->VdmContext.EFlags &= ~EFLAGS_INTERRUPT_MASK;
            }
            
            /* Turn off VIP and VIF */
            TrapFrame->EFlags &= ~(EFLAGS_VIP | EFLAGS_VIF);
            VdmTib->VdmContext.EFlags &= ~(EFLAGS_VIP | EFLAGS_VIF);
        }
        else
        {
            /* Set the EFLAGS based on our software copy of EFLAGS */
            VdmTib->VdmContext.EFlags = (VdmTib->VdmContext.EFlags & ~EFLAGS_INTERRUPT_MASK) |
                                        (*VdmState & EFLAGS_INTERRUPT_MASK);
        }
    }

    /* Lower IRQL and reutrn */
    KeLowerIrql(OldIrql);
}
Exemplo n.º 11
0
static VOID
XenPci_HighSyncCallFunction0(
  PRKDPC Dpc,
  PVOID Context,
  PVOID SystemArgument1,
  PVOID SystemArgument2)
{
  highsync_info_t *highsync_info = Context;
  ULONG ActiveProcessorCount;
  KIRQL old_irql;
  
  UNREFERENCED_PARAMETER(Dpc);
  UNREFERENCED_PARAMETER(SystemArgument1);
  UNREFERENCED_PARAMETER(SystemArgument2);

  FUNCTION_ENTER();
#if (NTDDI_VERSION >= NTDDI_WINXP)
  ActiveProcessorCount = (ULONG)KeNumberProcessors;
#else
  ActiveProcessorCount = (ULONG)*KeNumberProcessors;
#endif
  InterlockedIncrement(&highsync_info->nr_procs_at_dispatch_level);
  if (highsync_info->sync_level > DISPATCH_LEVEL)
  {
    while (highsync_info->nr_procs_at_dispatch_level < (LONG)ActiveProcessorCount)
    {
      KeStallExecutionProcessor(1);
      KeMemoryBarrier();
    }
  }
  _disable(); //__asm cli;  
  KeRaiseIrql(highsync_info->sync_level, &old_irql);
  while (highsync_info->nr_spinning_at_sync_level < (LONG)ActiveProcessorCount - 1)
  {
    KeStallExecutionProcessor(1);
    KeMemoryBarrier();
  }
  highsync_info->function0(highsync_info->context);
  KeLowerIrql(old_irql);
  _enable(); //__asm sti;
  highsync_info->do_spin = FALSE;
  KeMemoryBarrier();  
  /* wait for all the other processors to complete spinning, just in case it matters */
  while (highsync_info->nr_spinning_at_sync_level)
  {
    KeStallExecutionProcessor(1);
    KeMemoryBarrier();
  }
  InterlockedDecrement(&highsync_info->nr_procs_at_dispatch_level);
  /* wait until nr_procs_at_dispatch_level drops to 0 indicating that nothing else requires highsync_info */
  while (highsync_info->nr_procs_at_dispatch_level)
  {
    KeStallExecutionProcessor(1);
    KeMemoryBarrier();
  }
  KeSetEvent(&highsync_info->highsync_complete_event, IO_NO_INCREMENT, FALSE);

  FUNCTION_EXIT();
}
Exemplo n.º 12
0
VOID
HalCalibratePerformanceCounter (
    IN volatile PLONG Number
    )

/*++

Routine Description:

    This routine resets the performance counter value for the current
    processor to zero. The reset is done such that the resulting value
    is closely synchronized with other processors in the configuration.

Arguments:

    Number - Supplies a pointer to count of the number of processors in
    the configuration.

Return Value:

    None.

--*/

{

    KSPIN_LOCK Lock;
    KIRQL OldIrql;
    PKPRCB Prcb;

    //
    // Raise IRQL to HIGH_LEVEL, decrement the number of processors, and
    // wait until the number is zero.
    //

    KeInitializeSpinLock(&Lock);
    KeRaiseIrql(HIGH_LEVEL, &OldIrql);
    if (ExInterlockedDecrementLong(Number, &Lock) != RESULT_ZERO) {
        do {

        } while (*Number !=0);
    }

    //
    // Write the compare register, clear the count register, and zero the
    // performance counter for the current processor.
    //

    HalpWriteCompareRegisterAndClear(DEFAULT_PROFILE_COUNT);
    Prcb = KeGetCurrentPrcb();
    HalpPerformanceCounter[Prcb->Number].QuadPart = 0;

    //
    // Restore IRQL to its previous value and return.
    //

    KeLowerIrql(OldIrql);
    return;
}
Exemplo n.º 13
0
NTSTATUS
NTAPI
BeepCleanup(IN PDEVICE_OBJECT DeviceObject,
            IN PIRP Irp)
{
    KIRQL OldIrql, CancelIrql;
    PKDEVICE_QUEUE_ENTRY Packet;
    PIRP CurrentIrp;

    /* Raise IRQL and acquire the cancel lock */
    KeRaiseIrql(DISPATCH_LEVEL, &OldIrql);
    IoAcquireCancelSpinLock(&CancelIrql);

    /* Get the current IRP */
    CurrentIrp = DeviceObject->CurrentIrp;
    DeviceObject->CurrentIrp = NULL;
    while (CurrentIrp)
    {
        /* Clear its cancel routine */
        (VOID)IoSetCancelRoutine(CurrentIrp, NULL);

        /* Cancel the IRP */
        CurrentIrp->IoStatus.Status = STATUS_CANCELLED;
        CurrentIrp->IoStatus.Information = 0;

        /* Release the cancel lock and complete it */
        IoReleaseCancelSpinLock(CancelIrql);
        IoCompleteRequest(CurrentIrp, IO_NO_INCREMENT);

        /* Reacquire the lock and get the next queue packet */
        IoAcquireCancelSpinLock(&CancelIrql);
        Packet = KeRemoveDeviceQueue(&DeviceObject->DeviceQueue);
        if (Packet)
        {
            /* Get the IRP */
            CurrentIrp = CONTAINING_RECORD(Packet,
                                           IRP,
                                           Tail.Overlay.DeviceQueueEntry);
        }
        else
        {
            /* No more IRPs */
            CurrentIrp = NULL;
        }
    }

    /* Release lock and go back to low IRQL */
    IoReleaseCancelSpinLock(CancelIrql);
    KeLowerIrql(OldIrql);

    /* Complete the IRP */
    Irp->IoStatus.Status = STATUS_SUCCESS;
    Irp->IoStatus.Information = 0;
    IoCompleteRequest(Irp, IO_NO_INCREMENT);

    /* Stop and beep and return */
    HalMakeBeep(0);
    return STATUS_SUCCESS;
}
Exemplo n.º 14
0
static VOID CfixkrsReleaseLockFilamentRegistry( 
	__in PCFIXKRP_FILAMENT_REGISTRY Registry,
	__in KIRQL OldIrql
	)
{
	KeReleaseSpinLockFromDpcLevel( &Registry->Lock );
	KeLowerIrql( OldIrql );
}
Exemplo n.º 15
0
static void TestFormattedAssertionAtElevatedIrql()
{
	KIRQL OldIrql;
	KeRaiseIrql( DISPATCH_LEVEL, &OldIrql );
	CFIX_ASSERT_MESSAGE( TRUE, L"%d%s", 1, L"123" );
	CFIX_ASSERT_MESSAGE( TRUE, L"test" );
	KeLowerIrql( OldIrql );
}
Exemplo n.º 16
0
/*
 * @implemented
 */
VOID
FASTCALL
KfReleaseSpinLock(PKSPIN_LOCK SpinLock,
                  KIRQL OldIrql)
{
    /* Simply lower IRQL back */
    KeLowerIrql(OldIrql);
}
RTDECL(void) RTThreadPreemptRestore(PRTTHREADPREEMPTSTATE pState)
{
    AssertPtr(pState);

    RT_ASSERT_PREEMPT_CPUID_RESTORE(pState);
    KeLowerIrql(pState->uchOldIrql);
    pState->uchOldIrql = 255;
}
Exemplo n.º 18
0
/*
 * @implemented
 */
VOID
FASTCALL
KeReleaseInStackQueuedSpinLock(IN PKLOCK_QUEUE_HANDLE LockHandle)
{
    /* Simply lower IRQL back */
    KxReleaseSpinLock(LockHandle->LockQueue.Lock); // HACK
    KeLowerIrql(LockHandle->OldIrql);
}
Exemplo n.º 19
0
VOID MPCreateThread(VOID (*FunctionPointer)(IN PKDPC, IN PVOID, IN PVOID, IN PVOID))
{
	/*
	*
	* Multi-Processor Consideration ::
	*
	* Each processor has it's own IDT.
	* 
	*/
	CCHAR i;
	long currentProcessor =0;
	PKDPC pkDpc =NULL;
	KIRQL oldIrql, currentIrql;

	allProcessorDone =0;

	currentIrql = KeGetCurrentIrql();

	if (currentIrql < DISPATCH_LEVEL)
		KeRaiseIrql(DISPATCH_LEVEL, &oldIrql);

	InterlockedAnd(&allProcessorDone, 0);

	pkDpc = (PKDPC)ExAllocatePoolWithTag(NonPagedPool, KeNumberProcessors * sizeof(KDPC), (ULONG)' pni');

	if (!pkDpc)
	{
		DbgPrint("Insufficient Resource error\n");
		return;
	}

	currentProcessor = KeGetCurrentProcessorNumber();

	for (i = 0; i < KeNumberProcessors; i++)
	{
		cpuNum[i] =i;
		KeInitializeDpc(&pkDpc[i],
			FunctionPointer,
			&cpuNum[i]);
		KeSetTargetProcessorDpc(&pkDpc[i], i);
		KeInsertQueueDpc(&pkDpc[i], NULL, NULL);
	}

	// wait for all of the processor's hooking initialization.
	while(InterlockedCompareExchange(&allProcessorDone, KeNumberProcessors - 1, KeNumberProcessors - 1) != KeNumberProcessors - 1)
	{
		_asm pause;
	}

	if (currentIrql < DISPATCH_LEVEL)
		KeLowerIrql(oldIrql);

	if (pkDpc)
	{
		ExFreePool(pkDpc);
		pkDpc = NULL;
	}
}
Exemplo n.º 20
0
NTKERNELAPI
BOOLEAN
KeDeregisterBugCheckCallback (
    IN PKBUGCHECK_CALLBACK_RECORD CallbackRecord
    )

/*++

Routine Description:

    This function deregisters a bug check callback record.

Arguments:

    CallbackRecord - Supplies a pointer to a bug check callback record.

Return Value:

    If the specified bug check callback record is successfully deregistered,
    then a value of TRUE is returned. Otherwise, a value of FALSE is returned.

--*/

{

    BOOLEAN Deregister;
    KIRQL OldIrql;

    //
    // Raise IRQL to HIGH_LEVEL and acquire the bug check callback list
    // spinlock.
    //

    KeRaiseIrql(HIGH_LEVEL, &OldIrql);
    KiAcquireSpinLock(&KeBugCheckCallbackLock);

    //
    // If the specified callback record is currently registered, then
    // deregister the callback record.
    //

    Deregister = FALSE;
    if (CallbackRecord->State == BufferInserted) {
        CallbackRecord->State = BufferEmpty;
        RemoveEntryList(&CallbackRecord->Entry);
        Deregister = TRUE;
    }

    //
    // Release the bug check callback spinlock, lower IRQL to its previous
    // value, and return whether the callback record was successfully
    // deregistered.
    //

    KiReleaseSpinLock(&KeBugCheckCallbackLock);
    KeLowerIrql(OldIrql);
    return Deregister;
}
Exemplo n.º 21
0
void FailingTestAtElevatedIrql()
{
	KIRQL OldIrql;
	KeRaiseIrql( DISPATCH_LEVEL, &OldIrql );
	CFIX_LOG( L"Test" );
	CFIX_ASSERT( !"Fail" );
	CFIX_LOG( L"?" );
	KeLowerIrql( OldIrql );
}
Exemplo n.º 22
0
NDIS_STATUS NTAPI
ProTransferData(
    IN  NDIS_HANDLE         MacBindingHandle,
    IN  NDIS_HANDLE         MacReceiveContext,
    IN  UINT                ByteOffset,
    IN  UINT                BytesToTransfer,
    IN  OUT PNDIS_PACKET    Packet,
    OUT PUINT               BytesTransferred)
/*
 * FUNCTION: Forwards a request to copy received data into a protocol-supplied packet
 * ARGUMENTS:
 *     MacBindingHandle  = Adapter binding handle
 *     MacReceiveContext = MAC receive context
 *     ByteOffset        = Offset in packet to place data
 *     BytesToTransfer   = Number of bytes to copy into packet
 *     Packet            = Pointer to NDIS packet descriptor
 *     BytesTransferred  = Address of buffer to place number of bytes copied
 */
{
    PADAPTER_BINDING AdapterBinding = GET_ADAPTER_BINDING(MacBindingHandle);
    PLOGICAL_ADAPTER Adapter        = AdapterBinding->Adapter;
    NDIS_STATUS Status;
    KIRQL OldIrql;

    NDIS_DbgPrint(MAX_TRACE, ("Called.\n"));

    /* FIXME: Interrupts must be disabled for adapter */
    /* XXX sd - why is that true? */

    if (Adapter->NdisMiniportBlock.IndicatedPacket[KeGetCurrentProcessorNumber()]) {
	NDIS_DbgPrint(MAX_TRACE, ("LoopPacket\n"));
        /* NDIS is responsible for looping this packet */
        NdisCopyFromPacketToPacket(Packet,
                                   ByteOffset + Adapter->MediumHeaderSize,
                                   BytesToTransfer + Adapter->MediumHeaderSize,
                                   Adapter->NdisMiniportBlock.IndicatedPacket[KeGetCurrentProcessorNumber()],
                                   0,
                                   BytesTransferred);
        return NDIS_STATUS_SUCCESS;
    }

    ASSERT(Adapter->NdisMiniportBlock.DriverHandle->MiniportCharacteristics.TransferDataHandler);

    KeRaiseIrql(DISPATCH_LEVEL, &OldIrql);

    Status = (*Adapter->NdisMiniportBlock.DriverHandle->MiniportCharacteristics.TransferDataHandler)(
        Packet,
        BytesTransferred,
        Adapter->NdisMiniportBlock.MiniportAdapterContext,
        MacReceiveContext,
        ByteOffset,
        BytesToTransfer);

    KeLowerIrql(OldIrql);

    return Status;
}
Exemplo n.º 23
0
/*
 * @implemented
 */
VOID
FASTCALL
KfReleaseSpinLock(PKSPIN_LOCK SpinLock,
                  KIRQL OldIrql)
{
    /* Release the lock and lower IRQL back */
    KxReleaseSpinLock(SpinLock);
    KeLowerIrql(OldIrql);
}
Exemplo n.º 24
0
/*
 * @implemented
 */
VOID
KeReleaseQueuedSpinLock(IN KSPIN_LOCK_QUEUE_NUMBER LockNumber,
                        IN KIRQL OldIrql)
{
    /* Release the lock */
    KxReleaseSpinLock(KeGetCurrentPrcb()->LockQueue[LockNumber].Lock); // HACK

    /* Lower IRQL back */
    KeLowerIrql(OldIrql);
}
Exemplo n.º 25
0
Arquivo: kdb.c Projeto: GYGit/reactos
VOID
NTAPI
KiEspToTrapFrame(IN PKTRAP_FRAME TrapFrame,
                 IN ULONG_PTR Esp)
{
    KIRQL OldIrql;
    ULONG Previous;

    /* Raise to APC_LEVEL if needed */
    OldIrql = KeGetCurrentIrql();
    if (OldIrql < APC_LEVEL) KeRaiseIrql(APC_LEVEL, &OldIrql);

    /* Get the old ESP */
    Previous = KiEspFromTrapFrame(TrapFrame);

    /* Check if this is user-mode  */
    if ((TrapFrame->SegCs & MODE_MASK))
    {
        /* Write it directly */
        TrapFrame->Rsp = Esp;
    }
    else
    {
        /* Don't allow ESP to be lowered, this is illegal */
        if (Esp < Previous) KeBugCheckEx(SET_OF_INVALID_CONTEXT,
                                         Esp,
                                         Previous,
                                         (ULONG_PTR)TrapFrame,
                                         0);

        /* Create an edit frame, check if it was alrady */
        if (!(TrapFrame->SegCs & FRAME_EDITED))
        {
            /* Update the value */
            TrapFrame->Rsp = Esp;
        }
        else
        {
            /* Check if ESP changed */
            if (Previous != Esp)
            {
                /* Save CS */
                TrapFrame->SegCs &= ~FRAME_EDITED;

                /* Save ESP */
                TrapFrame->Rsp = Esp;
            }
        }
    }

    /* Restore IRQL */
    if (OldIrql < APC_LEVEL) KeLowerIrql(OldIrql);

}
Exemplo n.º 26
0
extern "C" NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject,PUNICODE_STRING RegistryPath){
	DbgPrint("SwapContext Hook to detect hidden processes\n");
	DbgPrint("Processes :");
	DriverObject->DriverUnload = DriverUnload;
	char detour_bytes[] = {0xe9,0xaa,0xbb,0xcc,0xdd,0x90};
	unsigned int saved_CR0;
	KIRQL Irql;
	/*KiDispatchInterrupt is exported*/
	PUCHAR p = (PUCHAR)KiDispatchInterrupt;
	PUCHAR det = (PUCHAR)HooK;
	int j;
	unsigned int relative = *(unsigned int*)(p + 0xDE);
	PUCHAR SwapContext = (PUCHAR)((unsigned int)(p+0xDD) + relative + 5);
	//DbgPrint("KiSwapContext at : %p\n",SwapContext);
	/*Implement the inline hook*/
	relative = (unsigned int)HooK - (unsigned int)SwapContext - 5;
	*(unsigned int*)&detour_bytes[1] = relative;
	/*Disable write protection*/
	__asm{
		push eax
		mov eax,CR0
		mov saved_CR0,eax
		and eax,0xFFFEFFFF
		mov CR0,eax
		pop eax
	}
	/*Set the detour function jump addresses in runtime*/
	for(j=0;;j++){
		if(det[j] == 0xAA && det[j+1] == 0xAA && det[j+2] == 0xAA && det[j+3] == 0xAA)
			break;
	}
	/*set the relative address for the conditional jump ()*/
	*(unsigned int*)&det[j] = (unsigned int)((SwapContext+0xa) - (det+j-2) - 6);
	/*set the relative address for the jump back to SwapContext*/
	for(;;j++){
		if(det[j] == 0xBB && det[j+1] == 0xBB && det[j+2] == 0xBB && det[j+3] == 0xBB)
			break;
	}
	*(unsigned int*)&det[j] = (unsigned int)((SwapContext + 6) - (det+j-1) - 5);
	/*Raise IRQL to patch safely*/
	Irql = KeRaiseIrqlToDpcLevel();
	/*implement the patch*/
	for(int i=0;i<6;i++){
		SwapContext[i] = detour_bytes[i];
	}
	KeLowerIrql(Irql);
	__asm{
		push eax
		mov eax,saved_CR0
		mov CR0,eax
		pop eax
	}
	return STATUS_SUCCESS;
}
Exemplo n.º 27
0
VOID
HalDisplayString (
    PUCHAR String
    )

/*++

Routine Description:

    This routine displays a character string on the display screen.

Arguments:

    String - Supplies a pointer to the characters that are to be displayed.

Return Value:

    None.

--*/

{
    KIRQL  OldIrql;

    KeRaiseIrql(HIGH_LEVEL, &OldIrql);

    if(HalpIsMulti) KiAcquireSpinLock(&HalpDisplayAdapterLock);

    //
    // If ownership of the display has been switched to the system display
    // driver, then reinitialize the display controller and revert ownership
    // to the HAL.
    //

    if (HalpDisplayOwnedByHal == FALSE) {

            HalpDisplayControllerSetup();

    }

    // display the string 

    if( HalpVideoChip == VIDEO_CHIP_UNKNOWN) {
	    ((SNI_PRIVATE_VECTOR *)(SYSTEM_BLOCK->VendorVector))->printf(String);	
    } else {
	    HalpDisplayVGAString(String);
    }

    if(HalpIsMulti) KiReleaseSpinLock(&HalpDisplayAdapterLock);

    KeLowerIrql(OldIrql);

    return;
}
Exemplo n.º 28
0
VOID
HalDisableSystemInterrupt (
    IN ULONG Vector,
    IN KIRQL Irql
    )

/*++

Routine Description:

    This routine disables the specified system interrupt.

Arguments:

    Vector - Supplies the vector of the system interrupt that is disabled.

    Irql - Supplies the IRQL of the interrupting source.

Return Value:

    None.

--*/

{

    KIRQL OldIrql;

    //
    // Raise IRQL to the highest level and acquire device enable spinlock.
    //

    KeRaiseIrql(HIGH_LEVEL, &OldIrql);
    KiAcquireSpinLock(&HalpSystemInterruptLock);

    if (Vector >= DEVICE_VECTORS ) {
        if ( Vector < DEVICE_VECTORS + MPIC_BASE_VECTOR ) {

            HalpDisableSioInterrupt(Vector);

        } else if ( Vector <= DEVICE_VECTORS + MPIC_MAX_VECTOR ) {

            HalpDisableMpicInterrupt(Vector);
       }
    }

    //
    // Release the device enable spin lock and lower IRQL to the previous level.
    //

    KiReleaseSpinLock(&HalpSystemInterruptLock);
    KeLowerIrql(OldIrql);
    return;
}
Exemplo n.º 29
0
static VOID LogThreeMessagesAtDirql()
{
	KIRQL Irql;
	KeRaiseIrql( DISPATCH_LEVEL + 1, &Irql );
	
	CFIX_ASSERT( "Truth" );

	CFIX_LOG( L"Log at %s", L"elevated irql" );
	CFIX_LOG( L"Log at %s", L"elevated irql" );
	CFIX_LOG( L"Log at %s", L"elevated irql" );

	KeLowerIrql( Irql );
}
Exemplo n.º 30
0
VOID EnumDriverByLdrDataTableEntry(PALL_DRIVERS DriversInfor, ULONG_PTR ulCount)
{
	PKLDR_DATA_TABLE_ENTRY Entry = NULL, FirstEntry = NULL;
	ULONG nMax = PAGE_SIZE;
	ULONG i = 0;
	KIRQL OldIrql;

	FirstEntry = Entry = (PKLDR_DATA_TABLE_ENTRY)Ntoskrnl_KLDR_DATA_TABLE_ENTRY;

	if (!FirstEntry || !DriversInfor)
	{
		return;
	}
	OldIrql = KeRaiseIrqlToDpcLevel();
	__try
	{
		do
		{
			if ((ULONG_PTR)Entry->DllBase > SYSTEM_ADDRESS_START && Entry->SizeOfImage > 0)
			{
				ULONG_PTR Temp = DriversInfor->ulCount;
				if (ulCount > Temp)
				{

					DriversInfor->Drivers[Temp].LodeOrder = ++i;
					DriversInfor->Drivers[Temp].Base = (ULONG_PTR)Entry->DllBase;
					DriversInfor->Drivers[Temp].Size = Entry->SizeOfImage;

					if (IsUnicodeStringValid(&(Entry->FullDllName)))
					{
						wcsncpy(DriversInfor->Drivers[Temp].wzDriverPath, Entry->FullDllName.Buffer, Entry->FullDllName.Length);
					}
					else if (IsUnicodeStringValid(&(Entry->BaseDllName)))
					{
						wcsncpy(DriversInfor->Drivers[Temp].wzDriverPath, Entry->BaseDllName.Buffer, Entry->BaseDllName.Length);
					}
				}
				DriversInfor->ulCount++;
			}

			Entry = (PKLDR_DATA_TABLE_ENTRY)Entry->InLoadOrderLinks.Flink;

		}while(Entry && Entry != FirstEntry && nMax--);	
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		DbgPrint("LdrDataTable Exception!\r\n");
	}

	KeLowerIrql(OldIrql);
}