Example #1
0
int lkl_env_init(unsigned long mem_size)
{
	HANDLE init_thread_handle, timer_thread_handle;
	NTSTATUS status;

	nops.phys_mem_size=mem_size;

	KeInitializeTimerEx(&timer, SynchronizationTimer);
        KeInitializeSemaphore(&init_sem, 0, 100);
        KeInitializeSemaphore(&timer_killer_sem, 0, 100);

	/* create the initial thread */
	status = PsCreateSystemThread(&init_thread_handle, THREAD_ALL_ACCESS,
				      NULL, NULL, NULL, init_thread, NULL);
	if (status != STATUS_SUCCESS)
		goto err;


	/* wait for the initial thread to complete initialization to
	 * be able to interact with it */
        status = KeWaitForSingleObject(&init_sem, Executive, KernelMode, FALSE, NULL);
	if (status != STATUS_SUCCESS)
		goto close_init_thread;

	/* create the timer thread responsible with delivering timer interrupts */
	status = PsCreateSystemThread(&timer_thread_handle, THREAD_ALL_ACCESS,
				      NULL, NULL, NULL, timer_thread, NULL);
	if (status != STATUS_SUCCESS)
		goto close_init_thread;


	/* get references to the init and timer threads to be able to wait on them */
	status = ObReferenceObjectByHandle(init_thread_handle, THREAD_ALL_ACCESS,
					   NULL, KernelMode, &init_thread_obj, NULL);
	if (!NT_SUCCESS(status))
		goto close_timer_thread;

	status = ObReferenceObjectByHandle(timer_thread_handle, THREAD_ALL_ACCESS,
					   NULL, KernelMode, &timer_thread_obj, NULL);
	if (!NT_SUCCESS(status))
		goto deref_init_thread_obj;

	/* we don't need the handles, we have access to the objects */
	ZwClose(timer_thread_handle);
	ZwClose(init_thread_handle);
	return STATUS_SUCCESS;


deref_init_thread_obj:
	ObDereferenceObject(init_thread_obj);
close_timer_thread:
	ZwClose(timer_thread_handle);
close_init_thread:
	ZwClose(init_thread_handle);
err:
	return status;
}
Example #2
0
ACPI_STATUS
AcpiOsExecute (
    ACPI_EXECUTE_TYPE       Type,
    ACPI_OSD_EXEC_CALLBACK  Function,
    void                    *Context)
{
    HANDLE ThreadHandle;
    OBJECT_ATTRIBUTES ObjectAttributes;
    NTSTATUS Status;

    DPRINT("AcpiOsExecute\n");

    InitializeObjectAttributes(&ObjectAttributes,
                               NULL,
                               OBJ_KERNEL_HANDLE,
                               NULL,
                               NULL);

    Status = PsCreateSystemThread(&ThreadHandle,
                                  THREAD_ALL_ACCESS,
                                  &ObjectAttributes,
                                  NULL,
                                  NULL,
                                  (PKSTART_ROUTINE)Function,
                                  Context);
    if (!NT_SUCCESS(Status))
        return AE_ERROR;

    ZwClose(ThreadHandle);

    return AE_OK;
}
Example #3
0
NTSTATUS
NTAPI
INIT_FUNCTION
MmInitMpwThread(VOID)
{
   KPRIORITY Priority;
   NTSTATUS Status;
   CLIENT_ID MpwThreadId;
   
   KeInitializeEvent(&MpwThreadEvent, SynchronizationEvent, FALSE);

   Status = PsCreateSystemThread(&MpwThreadHandle,
                                 THREAD_ALL_ACCESS,
                                 NULL,
                                 NULL,
                                 &MpwThreadId,
                                 (PKSTART_ROUTINE) MmMpwThreadMain,
                                 NULL);
   if (!NT_SUCCESS(Status))
   {
      return(Status);
   }

   Priority = 27;
   NtSetInformationThread(MpwThreadHandle,
                          ThreadPriority,
                          &Priority,
                          sizeof(Priority));

   return(STATUS_SUCCESS);
}
Example #4
0
sys_thread_t
sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio)
{
    thread_t Container;
    NTSTATUS Status;

    Container = ExAllocatePool(NonPagedPool, sizeof(*Container));
    if (!Container)
        return 0;

    Container->ThreadFunction = thread;
    Container->ThreadContext = arg;

    Status = PsCreateSystemThread(&Container->Handle,
                                  THREAD_ALL_ACCESS,
                                  NULL,
                                  NULL,
                                  NULL,
                                  LwipThreadMain,
                                  Container);

    if (!NT_SUCCESS(Status))
    {
        ExFreePool(Container);
        return 0;
    }

    return 0;
}
Example #5
0
NTSTATUS
DokanStartEventNotificationThread(
	__in PDEVICE_EXTENSION	DeviceExtension)
{
	NTSTATUS status;
	HANDLE	thread;

	DDbgPrint("==> DokanStartEventNotificationThread\n");

	KeResetEvent(&DeviceExtension->ReleaseEvent);

	status = PsCreateSystemThread(&thread, THREAD_ALL_ACCESS,
		NULL, NULL, NULL,
		(PKSTART_ROUTINE)NotificationThread,
		DeviceExtension);

	if (!NT_SUCCESS(status)) {
		return status;
	}

	ObReferenceObjectByHandle(thread, THREAD_ALL_ACCESS, NULL,
		KernelMode, (PVOID*)&DeviceExtension->EventNotificationThread, NULL);

	ZwClose(thread);

	DDbgPrint("<== DokanStartEventNotificationThread\n");

	return STATUS_SUCCESS;
}
Example #6
0
/**
 *	创建线程
 */
BOOLEAN ipfirewall_create_install_thread()
{
	NTSTATUS ntStatus;

	__try
	{
		//	初始化事件句柄
		KeInitializeEvent( &g_ipfirewall_hkEvent, NotificationEvent, FALSE );

		//	设置事件句柄为未激发状态,使得 KeWaitForSingleObject 阻塞等待
		KeResetEvent( &g_ipfirewall_hkEvent );

		//	是否开始
		g_ipfirewall_bThreadStart = FALSE;

		//	创建线程
		ntStatus = PsCreateSystemThread( &g_ipfirewall_hThread, 0, NULL, NULL, NULL, ipfirewall_install_thread_proc, NULL );
	}
	__except( EXCEPTION_EXECUTE_HANDLER )
	{
		KdPrint(("EXCEPTION_EXECUTE_HANDLER in: ipfirewall_create_install_thread"));
	}

	//	...
	return NT_SUCCESS( ntStatus );
}
Example #7
0
// 中断请求等级 passive
NTSTATUS InitThreadKeyLogger(IN PDRIVER_OBJECT pDriverObject)
{

	PDEVICE_EXTENSION pKeyboardDeviceExtension = (PDEVICE_EXTENSION)pDriverObject->DeviceObject->DeviceExtension;

	//为设备扩展创建工作线程
	pKeyboardDeviceExtension->bThreadTerminate = false;

	//创建工作线程
	HANDLE hThread;
	NTSTATUS status	= PsCreateSystemThread(&hThread,(ACCESS_MASK)0,NULL,(HANDLE)0,NULL,ThreadKeyLogger,
						pKeyboardDeviceExtension);

	if(!NT_SUCCESS(status))
		return status;

	DbgPrint("Key logger thread created...\n");

	//获取线程对象的指针
	ObReferenceObjectByHandle(hThread,THREAD_ALL_ACCESS,NULL,KernelMode,
		(PVOID*)&pKeyboardDeviceExtension->pThreadObj, NULL);

	DbgPrint("Key logger thread initialized; pThreadObject =  %x\n",
		&pKeyboardDeviceExtension->pThreadObj);

	ZwClose(hThread);

	return status;
}
Example #8
0
/****************************************************************************
REMARKS:
Function to register a driver heart beat callback function. The first
function that is called sets the interval for all the callback functions
and they will be called in the order they were registered. This function
will implement this mechanism in whatever way is appropriate for the
device driver environment.

Note that currently there is no mechanism to specify the timer intervals at
run-time, so we use a pre-determined value of 32 milliseconds that will be
useful for NT display driver polling and DPVL update functions.
****************************************************************************/
void PMAPI PM_registerHeartBeatCallback(
    PM_heartBeat_cb cb,
    void *data)
{
    // Kernel objects must always be resident in memory
    if (_PM_hb == NULL) {
        _PM_hb = ExAllocatePool(NonPagedPool, sizeof(_PM_heartBeat_t));
        if (_PM_hb == NULL)
            return;
        RtlZeroMemory(_PM_hb, sizeof(_PM_heartBeat_t));
        }

    // If first time called, start periodic timer (pre-determined intervals)
    if (_PM_hb->numHeartBeatCallbacks == 0) {
        KeInitializeTimer(&_PM_hb->kTimer);
        KeInitializeDpc(&_PM_hb->kTimerDpc,_PM_heartBeatTimeout,(void*)_PM_hb);
        KeSetTimerEx(&_PM_hb->kTimer,RtlConvertLongToLargeInteger(-10000*HEART_BEAT_MS),
            HEART_BEAT_MS,&_PM_hb->kTimerDpc);
        KeInitializeEvent(&_PM_hb->kTimerEvent,NotificationEvent,FALSE);
        // Callbacks will be executed within driver helper thread, not DPC
        _PM_hb->bThreadRunning = true;
        PsCreateSystemThread(&_PM_hb->hDriverThread,THREAD_ALL_ACCESS,NULL,
            NULL,NULL,_PM_heartBeatThread,(void*)_PM_hb);
        }

    // Add heart beat callback to list
    PM_lockSNAPAccess(-1,true);
    if (_PM_hb->numHeartBeatCallbacks < MAX_HEART_BEAT_CALLBACKS) {
        _PM_hb->heartBeat[_PM_hb->numHeartBeatCallbacks] = cb;
        _PM_hb->heartBeatData[_PM_hb->numHeartBeatCallbacks] = data;
        _PM_hb->numHeartBeatCallbacks++;
        }
    PM_unlockSNAPAccess(-1);
}
DECLHIDDEN(int) rtThreadNativeCreate(PRTTHREADINT pThreadInt, PRTNATIVETHREAD pNativeThread)
{
    /*
     * PsCreateSysemThread create a thread an give us a handle in return.
     * We requests the object for that handle and then close it, so what
     * we keep around is the pointer to the thread object and not a handle.
     * The thread will dereference the object before returning.
     */
    HANDLE hThread = NULL;
    OBJECT_ATTRIBUTES ObjAttr;
    InitializeObjectAttributes(&ObjAttr, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
    NTSTATUS rc = PsCreateSystemThread(&hThread,
                                       THREAD_ALL_ACCESS,
                                       &ObjAttr,
                                       NULL /* ProcessHandle - kernel */,
                                       NULL /* ClientID - kernel */,
                                       rtThreadNativeMain,
                                       pThreadInt);
    if (NT_SUCCESS(rc))
    {
        PVOID pvThreadObj;
        rc = ObReferenceObjectByHandle(hThread, THREAD_ALL_ACCESS, NULL /* object type */,
                                       KernelMode, &pvThreadObj, NULL /* handle info */);
        if (NT_SUCCESS(rc))
        {
            ZwClose(hThread);
            *pNativeThread = (RTNATIVETHREAD)pvThreadObj;
        }
        else
            AssertMsgFailed(("%#x\n", rc));
    }
    return RTErrConvertFromNtStatus(rc);
}
Example #10
0
NTSTATUS
DokanStartCheckThread(__in PDokanDCB Dcb)
/*++

Routine Description:

        execute DokanTimeoutThread

--*/
{
  NTSTATUS status;
  HANDLE thread;

  DDbgPrint("==> DokanStartCheckThread\n");

  status = PsCreateSystemThread(&thread, THREAD_ALL_ACCESS, NULL, NULL, NULL,
                                (PKSTART_ROUTINE)DokanTimeoutThread, Dcb);

  if (!NT_SUCCESS(status)) {
    return status;
  }

  ObReferenceObjectByHandle(thread, THREAD_ALL_ACCESS, NULL, KernelMode,
                            (PVOID *)&Dcb->TimeoutThread, NULL);

  ZwClose(thread);

  DDbgPrint("<== DokanStartCheckThread\n");

  return STATUS_SUCCESS;
}
Example #11
0
NTSTATUS
DokanStartCheckThread(
	__in PDEVICE_EXTENSION	DeviceExtension)
/*++

Routine Description:

	execute DokanTimeoutThread

--*/
{
	NTSTATUS status;
	HANDLE	thread;

	DDbgPrint("==> DokanStartCheckThread\n");

	KeInitializeEvent(&DeviceExtension->KillEvent, NotificationEvent, FALSE);

	status = PsCreateSystemThread(&thread, THREAD_ALL_ACCESS,
		NULL, NULL, NULL, (PKSTART_ROUTINE)DokanTimeoutThread, DeviceExtension);

	if (!NT_SUCCESS(status)) {
		return status;
	}

	ObReferenceObjectByHandle(thread, THREAD_ALL_ACCESS, NULL,
		KernelMode, (PVOID*)&DeviceExtension->TimeoutThread, NULL);

	ZwClose(thread);

	DDbgPrint("<== DokanStartCheckThread\n");

	return STATUS_SUCCESS;
}
Example #12
0
void DebugPrintInit(char* DriverName)
{
	//初始化全局变量
	HANDLE ThreadHandle;
	NTSTATUS status;

	ExitNow=FALSE;
	DebugPrintStarted=FALSE;
	ThreadObjectPointer=NULL;
	KeInitializeEvent(&ThreadEvent,SynchronizationEvent,FALSE);
	KeInitializeEvent(&ThreadExiting,SynchronizationEvent,FALSE);
	KeInitializeSpinLock(&EventListLock);
	InitializeListHead(&EventList);

	status=PsCreateSystemThread(&ThreadHandle,THREAD_ALL_ACCESS,NULL,NULL,NULL,DebugPrintSystemThread,NULL);
	if(!NT_SUCCESS(status))
	{
		DBGPRINT("FA SONG XIN XI SHI WU");
		return;
	}
	else
	{
		DBGPRINT("FA SONG XIN XI CHENG GONG");
	}
	status=ObReferenceObjectByHandle(ThreadHandle,THREAD_ALL_ACCESS,NULL,KernelMode,&ThreadObjectPointer,NULL);
	if(NT_SUCCESS(status))
		ZwClose(ThreadHandle);
}
Example #13
0
NTSTATUS DriverEntry(PDRIVER_OBJECT	theDriverObject, PUNICODE_STRING theRegistryPath)
{
	HANDLE hThread = NULL;
	NTSTATUS ntStatus = 0;
	OBJECT_ATTRIBUTES ThreadAttributes;
	KEVENT kEvent = { 0 };
	PETHREAD pThread = 0;
	theDriverObject->DriverUnload = OnUnload;
	DbgPrint("Entering KERNEL mode..");
	InitializeObjectAttributes(&ThreadAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
	__try
	{
		KeInitializeEvent(&kEvent, SynchronizationEvent, 0);
		ntStatus = PsCreateSystemThread(&hThread, GENERIC_ALL, &ThreadAttributes, NULL, NULL, (PKSTART_ROUTINE) &ThreadStart, &kEvent);
		if (NT_SUCCESS(ntStatus))
		{
			KeWaitForSingleObject(&kEvent, Executive, KernelMode, FALSE, NULL);
			ZwClose(hThread);
		}
		else
		{
			DbgPrint("Could not create system thread!");
		}
	}
	__except (EXCEPTION_EXECUTE_HANDLER)
	{
		DbgPrint("Error while creating system thread!");
	}
	return STATUS_SUCCESS;
}
Example #14
0
timeout_id_t timeout(void (*func)(void *), void* unused, hrtime_t nano)
{
	struct timeout_func *to_func;
	OBJECT_ATTRIBUTES ObjectAttributes;
	NTSTATUS st;
	HANDLE thand;
	UNREFERENCED_PARAMETER(unused);
	
	InitializeObjectAttributes(&ObjectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
	to_func = ExAllocatePoolWithTag(NonPagedPool, sizeof(struct timeout_func), 'Tag1');
	if (to_func == NULL)
		return (timeout_id_t) NULL;
	to_func->time = nano;
	to_func->f = func;
	KeInitializeTimer(&to_func->Timer);
	to_func->Thread = NULL;
	
	st = PsCreateSystemThread(&thand, THREAD_ALL_ACCESS, &ObjectAttributes, NULL, 
		NULL, FTTimeout, (PVOID) to_func);
	
	if (st == STATUS_SUCCESS) {
		/* To wait for the thread to terminate, you need the address of the
		underlying KTHREAD object instead of the handle you get back from PsCreateSystemThread */
		ObReferenceObjectByHandle(thand, THREAD_ALL_ACCESS, NULL, KernelMode, 
			(PVOID*)&to_func->Thread, NULL);
		/* Dont need the handle once we have the address of the KTHREAD */
		ZwClose(thand);
	} else
		dprintf("fasttrap.sys: timeout() Thread creationfailed\n");

	return (timeout_id_t) to_func->Thread;
}
Example #15
0
VOID DokanDeleteMountPoint(__in PDokanDCB Dcb) {
  NTSTATUS status;

  if (Dcb->MountPoint != NULL && Dcb->MountPoint->Length > 0) {
    if (Dcb->UseMountManager) {
      Dcb->UseMountManager = FALSE; // To avoid recursive call
      DokanSendVolumeDeletePoints(Dcb->MountPoint, Dcb->DiskDeviceName);
    } else {
      // Run DokanDeleteMountPointProc in System thread.
      HANDLE handle;
      PKTHREAD thread;
      OBJECT_ATTRIBUTES objectAttribs;

      InitializeObjectAttributes(&objectAttribs, NULL, OBJ_KERNEL_HANDLE, NULL,
                                 NULL);
      status = PsCreateSystemThread(
          &handle, THREAD_ALL_ACCESS, &objectAttribs, NULL, NULL,
          (PKSTART_ROUTINE)DokanDeleteMountPointSysProc, Dcb);
      if (!NT_SUCCESS(status)) {
        DDbgPrint("DokanDeleteMountPoint PsCreateSystemThread failed: 0x%X\n",
                  status);
      } else {
        ObReferenceObjectByHandle(handle, THREAD_ALL_ACCESS, NULL, KernelMode,
                                  &thread, NULL);
        ZwClose(handle);
        KeWaitForSingleObject(thread, Executive, KernelMode, FALSE, NULL);
        ObDereferenceObject(thread);
      }
    }
  }
}
  int abstraction_thread_start( thread_state_t *thread_state, unsigned int cpu, thread_function_t thread_function, void *thread_user_state )
  {
    int
      rv = 0;

    KAFFINITY
      affinity_mask

    NTSTATUS
      nts_create,
      nts_affinity;

    assert( thread_state != NULL );
    // TRD : cpu can be any value in its range
    assert( thread_function != NULL );
    // TRD : thread_user_state can be NULL

    affinity_mask = 1 << cpu;

    nts_create = PsCreateSystemThread( thread_state, THREAD_ALL_ACCESS, NULL, NULL, NULL, thread_function, thread_user_state );

    nts_affinity = ZwSetInformationThread( thread_state, ThreadAffinityMask, &affinity_mask, sizeof(KAFFINITY) );

    if( nts_create == STATUS_SUCCESS and nts_affinity == STATUS_SUCCESS )
      rv = 1;

    return( rv );
  }
Example #17
0
File: main.c Project: HideSand/ksm
NTSTATUS DriverEntry(PDRIVER_OBJECT driverObject, PUNICODE_STRING registryPath)
{
	LdrDataTableEntry *entry = driverObject->DriverSection;
	PsLoadedModuleList = entry->in_load_links.Flink;
	driverObject->DriverUnload = DriverUnload;

	VCPU_DEBUG("We're mapped at %p (size: %d bytes (%d KB), on %d pages)\n",
		   entry->base, entry->size, entry->size / 1024, entry->size / PAGE_SIZE);
	LdrDataTableEntry *kentry = container_of(PsLoadedModuleList->Flink, LdrDataTableEntry, in_load_links);
	g_kernel_base = kentry->base;

	VCPU_DEBUG("Kernel: %p -> %p (size: 0x%X pages: %d) path: %wS\n",
		   kentry->base, (uintptr_t)kentry->base + kentry->size,
		   kentry->size, BYTES_TO_PAGES(kentry->size),
		   kentry->path.Buffer);
	ExInitializeDriverRuntime(DrvRtPoolNxOptIn);

	NTSTATUS status = ksm_init();
	if (NT_SUCCESS(status))
		status = register_power_callback(&g_dev_ext);

	if (NT_SUCCESS(status))
		status = PsCreateSystemThread(&hThread, STANDARD_RIGHTS_ALL, NULL, NULL, &cid, (PKSTART_ROUTINE)sys_thread, NULL);

	VCPU_DEBUG("ret: 0x%08X\n", status);
	return status;
}
Example #18
0
// *****************************************************************************
NTSTATUS INTERNAL
    HGM_ActivateDevice
    (
    PDEVICE_OBJECT  DeviceObject
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;

    PDEVICE_EXTENSION   DeviceExtension;
    OBJECT_ATTRIBUTES ObjectAttributes;
    HANDLE Thread;
    PVOID pkThread;
    PAGED_CODE();
    DeviceExtension = GET_MINIDRIVER_DEVICE_EXTENSION (DeviceObject);

    if(!DeviceExtension->ScanThread)
//    if(!Global.ThreadIniciado)
    {
//      Global.ThreadIniciado = 1;
      InitializeObjectAttributes(&ObjectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL)
      KeInitializeEvent(&(DeviceExtension->FinishThread), NotificationEvent, FALSE);
      KeInitializeEvent(&(DeviceExtension->DoScan), SynchronizationEvent, FALSE);
      KeInitializeEvent(&(DeviceExtension->ScanReady), SynchronizationEvent, FALSE);
      ntStatus = PsCreateSystemThread(&Thread, THREAD_ALL_ACCESS,
                                       &ObjectAttributes, NULL, NULL, ScaningThread, (PVOID) DeviceObject);
      ObReferenceObjectByHandle(Thread, THREAD_ALL_ACCESS, NULL, KernelMode, &pkThread,NULL);
      KeSetPriorityThread(pkThread, LOW_REALTIME_PRIORITY - 1);
      DeviceExtension->ScanThread = (PKTHREAD) pkThread;
    };
    return ntStatus;
} /* HGM_GetAttributes */
Example #19
0
BOOLEAN
NetEvtInit(PNETEVTCTX	NetEvtCtx) {
	NTSTATUS			ntStatus ;
	OBJECT_ATTRIBUTES	objectAttributes;

	//
	//	create the datagram server thread
	//
	InitializeObjectAttributes(&objectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);

	KeInitializeEvent(
		&NetEvtCtx->ShutdownEvent,
		NotificationEvent,
		FALSE
		) ;

	ntStatus = PsCreateSystemThread(
					&NetEvtCtx->HThread,
					THREAD_ALL_ACCESS,
					&objectAttributes,
					NULL,
					NULL,
					NetEventDetectorProc,
					NetEvtCtx
	);
	if(!NT_SUCCESS(ntStatus)) {
		SPY_LOG_PRINT( LFS_DEBUG_LFS_TRACE, ("[LFS] couldn't start Redirection server\n")) ;
		return FALSE ;
	}

	return TRUE ;
}
Example #20
0
struct xm_thread *
XmSpawnThread(NTSTATUS (*cb)(struct xm_thread *xt, void *d), void *d)
{
    struct xm_thread *work;
    NTSTATUS stat;
    HANDLE tmpHandle;

    work = XmAllocateMemory(sizeof(*work));
    if (!work) return NULL;
    work->exit = FALSE;
    KeInitializeEvent(&work->event, NotificationEvent, FALSE);
    work->cb = cb;
    work->data = d;
    stat = PsCreateSystemThread(&tmpHandle, THREAD_ALL_ACCESS, NULL,
                                INVALID_HANDLE_VALUE, NULL, xm_thread_func,
                                work);
    if (!NT_SUCCESS(stat)) {
        XmFreeMemory(work);
        return NULL;
    }
    stat = ObReferenceObjectByHandle(tmpHandle, SYNCHRONIZE, NULL,
                                     KernelMode, &work->thread,
                                     NULL);
    ZwClose(tmpHandle);
    if (!NT_SUCCESS(stat)) {
        /* We can't reliably kill the thread in this case, and
           therefore can't release memory.  Instruct it to exit soon
           and hope for the best. */
        work->exit = TRUE;
        KeSetEvent(&work->event, IO_NO_INCREMENT, FALSE);
        return NULL;
    }

    return work;
}
Example #21
0
static void* thread_create(void (*fn)(void*), void *arg)
{
	void *thread;
	if (PsCreateSystemThread(&thread, THREAD_ALL_ACCESS, NULL, NULL, NULL,
				 (void DDKAPI (*)(void*))fn, arg) != STATUS_SUCCESS)
		return NULL;
	return thread;
}
Example #22
0
VOID TunerScanWorkItem(IN PDEVICE_OBJECT DeviceObject,IN PVOID Context)
{
    HANDLE           handle;
    NTSTATUS          WaitStatus;

    UNREFERENCED_PARAMETER(DeviceObject); 

    PEventHandlerData EventBlock= static_cast<PEventHandlerData>( Context);

    DbgPrint("MY-Event::TunerScanWorkItem");

    OBJECT_ATTRIBUTES oa;
    InitializeObjectAttributes(&oa, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);

    if (STATUS_SUCCESS != PsCreateSystemThread(&handle, THREAD_ALL_ACCESS, &oa, NULL, NULL, ScanThread, EventBlock))
    {
        return;
    }

    ObReferenceObjectByHandle(handle, THREAD_ALL_ACCESS, NULL,
        KernelMode, (PVOID*) &EventBlock->thread, NULL);

    KeSetEvent(&(EventBlock->InitEvent), 0,FALSE);
    ZwClose(handle);
    do
    {
        WaitStatus = KeWaitForSingleObject(&(EventBlock->TuneEvent),
	        Executive,
	        KernelMode,
	        FALSE,
	        NULL);
        if (!NT_SUCCESS(WaitStatus)) {
	        break;
        }
        if(EventBlock->bStopScan)
        {
	        StopPollingThread();
	        KsGenerateEvent(EventBlock->EventEntry);//fire an Event to the app that we are stopped
	        break;
        }
        CEncoderDevice* EncDevice = EventBlock->pDevice;
        EncDevice->CurrentFrequency = EventBlock->CurrentFrequency;

        KeClearEvent(&(EventBlock->TuneEvent));
        DbgPrint( "MY-TunerScanWorkItem : Firing an event from driver to the app\n");
        KsGenerateEvent(EventBlock->EventEntry);

#pragma warning(push)
#pragma warning(disable:4127)
    }while(1);
#pragma warning (pop)
    DbgPrint( "MY-TunerScanWorkItem terminating\n");
    IoFreeWorkItem(EventHandler->ThreadItem); // Release Work Item
    EventHandler->EventEntry = NULL;
    ExFreePoolWithTag(EventHandler, MS_SAMPLE_ANALOG_POOL_TAG);
    EventHandler = NULL;
}
Example #23
0
//#######################################################################################
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@				D R I V E R   E N T R Y   P O I N T						 @@@@@@@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//#######################################################################################
NTSTATUS
DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryString)
{
	
	NTSTATUS	Status = STATUS_SUCCESS;
	UNICODE_STRING   uniDeviceName;
	UNICODE_STRING   uniLinkName;
	PDEVICE_OBJECT   DeviceObject = NULL;
	ULONG_PTR        i  = 0;

	HANDLE hThread;

//	CHAR tmp = VmIsActive();

	RtlInitUnicodeString(&uniDeviceName,DEVICE_NAME);
	RtlInitUnicodeString(&uniLinkName,LINK_NAME);

	for (i=0;i<IRP_MJ_MAXIMUM_FUNCTION;i++)
	{
		DriverObject->MajorFunction[i] = DefaultPassThrough;
	}
	DriverObject->DriverUnload = UnloadDriver;

	DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = ControlPassThrough;

	//创建设备对象
	Status = IoCreateDevice(DriverObject,0,&uniDeviceName,FILE_DEVICE_UNKNOWN,0,FALSE,&DeviceObject);

	if (!NT_SUCCESS(Status))
	{

		return Status;
	}

	Status = IoCreateSymbolicLink(&uniLinkName,&uniDeviceName);

	if (!NT_SUCCESS(Status))
	{
		IoDeleteDevice(DeviceObject);

		return Status;
	}

	ServiceCallInitialize();

	Status = PsCreateSystemThread(&hThread, THREAD_ALL_ACCESS, NULL, NULL, NULL, VmStart, NULL);

	if (!NT_SUCCESS(Status))
	{
		return Status;
	}
		

	ZwClose(hThread);
	return STATUS_SUCCESS;
}
NTSTATUS
OobEditInit(
   _Out_ STREAM_EDITOR* streamEditor
   )
{
   NTSTATUS status = STATUS_SUCCESS;

   HANDLE threadHandle;
   
   streamEditor->editInline = FALSE;

   KeInitializeSpinLock(&streamEditor->oobEditInfo.editLock);   

   KeInitializeEvent(
      &streamEditor->oobEditInfo.editEvent,
      NotificationEvent,
      FALSE
      );

  streamEditor->oobEditInfo.busyThreshold = 32 * 1024;
  streamEditor->oobEditInfo.editState = OOB_EDIT_IDLE;

  InitializeListHead(&streamEditor->oobEditInfo.outgoingDataQueue);


   status = PsCreateSystemThread(
               &threadHandle,
               THREAD_ALL_ACCESS,
               NULL,
               NULL,
               NULL,
               StreamOobEditWorker,
               &gStreamEditor
               );

   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }

   status = ObReferenceObjectByHandle(
               threadHandle,
               0,
               NULL,
               KernelMode,
               &gThreadObj,
               NULL
               );
   NT_ASSERT(NT_SUCCESS(status));

   ZwClose(threadHandle);

Exit:

   return status;
}
Example #25
0
void DebugPrintInit(char* _DriverName)
{
	HANDLE threadHandle;
	NTSTATUS status;

	// Copy the driver's name out of INIT code segment
	DriverNameLen = 1 + ANSIstrlen(_DriverName);
	DriverName = (char*)ExAllocatePool(NonPagedPool,DriverNameLen);
	if( DriverName==NULL) return;
	RtlCopyMemory( DriverName, _DriverName, DriverNameLen);

	/////////////////////////////////////////////////////////////////////////
	// Prepare for thread start

	ExitNow = FALSE;
	KeInitializeEvent(&ThreadEvent, SynchronizationEvent, FALSE);
	KeInitializeEvent(&ThreadExiting, SynchronizationEvent, FALSE);
	// Initialise event list
	KeInitializeSpinLock(&EventListLock);
	InitializeListHead(&EventList);

	/////////////////////////////////////////////////////////////////////////
	// Start system thread to write events to DebugPrint driver

	status = PsCreateSystemThread( &threadHandle, THREAD_ALL_ACCESS, NULL, NULL, NULL,
									DebugPrintSystemThread, NULL);
	if( !NT_SUCCESS(status))
		return;

	/////////////////////////////////////////////////////////////////////////
	// Save a pointer to thread and close handle.

	status = ObReferenceObjectByHandle( threadHandle, THREAD_ALL_ACCESS, NULL, KernelMode,
										&ThreadObjectPointer, NULL);

	if( NT_SUCCESS(status))
		ZwClose(threadHandle);
	else
	{
		// Uh oh... force thread to exit
		ExitNow = TRUE;
		KeSetEvent( &ThreadEvent, 0, FALSE);
		return;
	}

	DebugPrintStarted = TRUE;

	// Send event that we've started logging
	DebugPrintMsg("DebugPrint logging started");
}
Example #26
0
/*! .

	\param [in]
	\param [out]
	\param [in,out]

	\pre
	\post
	\return

*/
NTSTATUS
FlTimerThreadCreate()
{
    NTSTATUS status = STATUS_SUCCESS;
    HANDLE handle;
    OBJECT_ATTRIBUTES objectAttribs;


    TimerThreadStopExec = FALSE;

    InitializeObjectAttributes(
        &objectAttribs, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);

    KeInitializeEvent(&ThreadSleepWakeup, SynchronizationEvent, FALSE);
    DriverInfoData->TimerThreadSleepWakeup = &ThreadSleepWakeup;

    KeInitializeTimer(&Timer);
    DriverInfoData->Timer = &Timer;



    status = PsCreateSystemThread(&handle,
                                  THREAD_ALL_ACCESS,
                                  &objectAttribs,
                                  NULL,
                                  NULL,
                                  (PKSTART_ROUTINE)TimerThreadExecRoutine,
                                  NULL);

    if (!NT_SUCCESS(status))
    {
        KeCancelTimer(&Timer);
        DriverInfoData->Timer = NULL;
        DriverInfoData->TimerThreadSleepWakeup = NULL;

        DBGPRINT_ARG1("[flmonflt] PsCreateSystemThread failed: 0x%X\n", status);
    }
    else
    {
        ObReferenceObjectByHandle(handle, THREAD_ALL_ACCESS, NULL,
                                  KernelMode, &DriverInfoData->TimerThread, NULL);

        ZwClose(handle);

        DBGPRINT("[flmonflt] PsCreateSystemThread succeeded.\n");
    }

    return status;
}
Example #27
0
VOID KphTestPushLock()
{
    ULONG i;
    
    ExInitializePushLock(&TestLock);
    
    for (i = 0; i < 10; i++)
    {
        HANDLE threadHandle;
        OBJECT_ATTRIBUTES objectAttributes;
        
        InitializeObjectAttributes(&objectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
        PsCreateSystemThread(&threadHandle, 0, &objectAttributes, NULL, NULL, KphpTestPushLockThreadStart, NULL);
    }
}
Example #28
0
NTSTATUS DriverEntry( IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING theRegistryPath )
{
	ULONG ulSize;
	ULONG ulKeServiceDescriptorTable;
	int i = 0;
	HANDLE HThreadHandle;
	HANDLE ThreadHandle;

	DriverObject->DriverUnload = DriverUnload;

	PDriverObject = DriverObject;

	RetAddress=*(DWORD*)((DWORD)&DriverObject-4);

	ulMyDriverBase = DriverObject->DriverStart;
	ulMyDriverSize = DriverObject->DriverSize;

	DebugOn = FALSE;  //开启调式信息

	KdPrint(("//***************************************//\r\n"
	       	"//   A-Protect Anti-Rootkit Kernel Module  //\r\n"
			"//   Kernel Module Version LE 2012-0.4.3  //\r\n"
		     "//  website:http://www.3600safe.com       //\r\n"
	         "//***************************************//\r\n"));

	SystemEProcess = PsGetCurrentProcess();

	WinVersion = GetWindowsVersion();  //初始化系统版本
	if (WinVersion)
		KdPrint(("Init Windows version Success\r\n"));

	DepthServicesRegistry = NULL;
	//-----------------------------------------
	//创建一个系统线程做操作
	//-----------------------------------------
	if (PsCreateSystemThread(
		&HThreadHandle,
		0,
		NULL,
		NULL,
		NULL,
		IsKernelBooting,
		NULL) == STATUS_SUCCESS)
	{
		ZwClose(HThreadHandle);
	}
	return STATUS_SUCCESS;
}
Example #29
0
VOID
INIT_FUNCTION
NTAPI
MiInitBalancerThread(VOID)
{
   KPRIORITY Priority;
   NTSTATUS Status;
#if !defined(__GNUC__)

   LARGE_INTEGER dummyJunkNeeded;
   dummyJunkNeeded.QuadPart = -20000000; /* 2 sec */
   ;
#endif


   KeInitializeEvent(&MiBalancerEvent, SynchronizationEvent, FALSE);
   KeInitializeTimerEx(&MiBalancerTimer, SynchronizationTimer);
   KeSetTimerEx(&MiBalancerTimer,
#if defined(__GNUC__)
                (LARGE_INTEGER)(LONGLONG)-20000000LL,     /* 2 sec */
#else
                dummyJunkNeeded,
#endif
                2000,         /* 2 sec */
                NULL);

   Status = PsCreateSystemThread(&MiBalancerThreadHandle,
                                 THREAD_ALL_ACCESS,
                                 NULL,
                                 NULL,
                                 &MiBalancerThreadId,
                                 (PKSTART_ROUTINE) MiBalancerThread,
                                 NULL);
   if (!NT_SUCCESS(Status))
   {
      KeBugCheck(MEMORY_MANAGEMENT);
   }

   Priority = LOW_REALTIME_PRIORITY + 1;
   NtSetInformationThread(MiBalancerThreadHandle,
                          ThreadPriority,
                          &Priority,
                          sizeof(Priority));

}
Example #30
0
NTSTATUS
ReadonlyDismountVolumeStart (
	IN  PREADONLY		Readonly
	)
{
	NTSTATUS			status;
	OBJECT_ATTRIBUTES	objectAttributes;
	LARGE_INTEGER		timeOut;

	if (Readonly->DismountThreadHandle)
		return STATUS_SUCCESS;

	InitializeObjectAttributes( &objectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL );

	status = PsCreateSystemThread( &Readonly->DismountThreadHandle,
								   THREAD_ALL_ACCESS,
								   &objectAttributes,
								   NULL,
								   NULL,
								   ReadonlyDismountVolumeThreadProc,
								   Readonly );

	if (!NT_SUCCESS(status)) {
		
		return status;
	}

	timeOut.QuadPart = -LFS_TIME_OUT;		
	
	status = KeWaitForSingleObject( &Readonly->DiskmountReadyEvent,
									Executive,
									KernelMode,
									FALSE,
									&timeOut );

	if (status != STATUS_SUCCESS) {
	
		return status;
	}

	KeClearEvent( &Readonly->DiskmountReadyEvent );

	return status;
}