示例#1
0
BOOLEAN PhpHeadQueryObjectHack(
    VOID
    )
{
    PhAcquireQueuedLockExclusive(&PhQueryObjectMutex);

    // Create a query thread if we don't have one.
    if (!PhQueryObjectThreadHandle)
    {
        PhQueryObjectThreadHandle = CreateThread(NULL, 0, PhpQueryObjectThreadStart, NULL, 0, NULL);

        if (!PhQueryObjectThreadHandle)
        {
            PhReleaseQueuedLockExclusive(&PhQueryObjectMutex);
            return FALSE;
        }
    }

    // Create the events if they don't exist.

    if (!PhQueryObjectStartEvent)
    {
        if (!NT_SUCCESS(NtCreateEvent(
            &PhQueryObjectStartEvent,
            EVENT_ALL_ACCESS,
            NULL,
            SynchronizationEvent,
            FALSE
            )))
        {
            PhReleaseQueuedLockExclusive(&PhQueryObjectMutex);
            return FALSE;
        }
    }

    if (!PhQueryObjectCompletedEvent)
    {
        if (!NT_SUCCESS(NtCreateEvent(
            &PhQueryObjectCompletedEvent,
            EVENT_ALL_ACCESS,
            NULL,
            SynchronizationEvent,
            FALSE
            )))
        {
            PhReleaseQueuedLockExclusive(&PhQueryObjectMutex);
            return FALSE;
        }
    }

    return TRUE;
}
示例#2
0
文件: coninput.c 项目: RPG-7/reactos
NTSTATUS NTAPI
ConDrvInitInputBuffer(IN PCONSOLE Console,
                      IN ULONG InputBufferSize)
{
    NTSTATUS Status;
    OBJECT_ATTRIBUTES ObjectAttributes;

    ConSrvInitObject(&Console->InputBuffer.Header, INPUT_BUFFER, Console);

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

    Status = NtCreateEvent(&Console->InputBuffer.ActiveEvent, EVENT_ALL_ACCESS,
                           &ObjectAttributes, NotificationEvent, FALSE);
    if (!NT_SUCCESS(Status))
        return Status;

    Console->InputBuffer.InputBufferSize = InputBufferSize;
    InitializeListHead(&Console->InputBuffer.InputEvents);
    Console->InputBuffer.Mode = ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT |
                                ENABLE_ECHO_INPUT      | ENABLE_MOUSE_INPUT;

    return STATUS_SUCCESS;
}
示例#3
0
文件: push.c 项目: Volkanite/Push
DWORD __stdcall RetrieveProcessEvent( VOID* Parameter )
{
    OVERLAPPED              ov          = { 0 };
    //BOOLEAN                    bReturnCode = FALSE;
    UINT32                  iBytesReturned;
    PROCESS_CALLBACK_INFO   processInfo;


    // Create an event handle for async notification from the driver
    NtCreateEvent(&ov.hEvent, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE);

    // Get the process info
    PushGetProcessInfo(&processInfo);

    //
    // Wait here for the event handle to be set, indicating
    // that the IOCTL processing is completed.
    //
    GetOverlappedResult(
        R0DriverHandle,
        &ov,
        &iBytesReturned,
        TRUE
        );

    OnProcessEvent(processInfo.hProcessID);
    NtClose(ov.hEvent);

    return 0;
}
示例#4
0
文件: push.c 项目: Volkanite/Push
DWORD __stdcall RetrieveImageEvent( VOID* Parameter )
{
    OVERLAPPED          ov          = { 0 };
    //BOOLEAN                bReturnCode = FALSE;
    UINT32              iBytesReturned;
    IMAGE_CALLBACK_INFO imageInfo;

    // Create an event handle for async notification from the driver
    NtCreateEvent(&ov.hEvent, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE);

    // Get the process info
    PushGetImageInfo(&imageInfo);

    Log(L"%i loaded D3D module", imageInfo.processID);


    //
    // Wait here for the event handle to be set, indicating
    // that the IOCTL processing is completed.
    //
    GetOverlappedResult(
        R0DriverHandle,
        &ov,
        &iBytesReturned,
        TRUE
        );

    CreateOverlay(imageInfo.processID);
    NtClose(ov.hEvent);

    return 0;
}
示例#5
0
文件: handle.c 项目: shuowen/OpenNT
VOID
FreeCon(
    IN HANDLE ConsoleHandle
)

/*++

Routine Description:

    This routine frees a console and its associated
    data - input buffer and screen buffer.

Arguments:

    ConsoleHandle - Handle of console to free.

Return Value:

Note:

    The console handle table lock must be held when calling this routine.

--*/

{
    PCONSOLE_INFORMATION Console;
    NTSTATUS Status;
    HANDLE hWait;
    HWND hWnd;
    LARGE_INTEGER li;

    Status = DereferenceConsoleHandle(ConsoleHandle,
                                      &Console
                                     );
    ASSERT (NT_SUCCESS(Status));
    Console->Flags |= CONSOLE_TERMINATING;
    NtSetEvent(Console->TerminationEvent,NULL);
    hWnd = Console->hWnd;
    UnlockConsole(Console);

    //
    // Use an event to synchronize the window destruction with
    // the termination of the thread
    //

    if (hWnd != NULL) {
        Status = NtCreateEvent(&hWait, EVENT_ALL_ACCESS,
                               NULL, SynchronizationEvent, FALSE);
        ASSERT(NT_SUCCESS(Status));
        if (GetWindowThreadProcessId(hWnd, NULL) ==
                (DWORD)NtCurrentTeb()->ClientId.UniqueThread) {
            DestroyWindowsWindow(Console,hWait);
        } else {
            PostMessage(hWnd, CM_DESTROY_WINDOW, (DWORD)hWait, 0);
            li.QuadPart = (LONGLONG)-10000 * 10000;
            NtWaitForSingleObject(hWait, FALSE, &li);
        }
        NtClose(hWait);
    }
}
示例#6
0
文件: input.c 项目: aaam/NativeShell
/*++
 * @name RtlCliOpenInputDevice
 *
 * The RtlCliOpenInputDevice routine opens an input device.
 *
 * @param Handle
 *        Pointer where the handle for the input device will be returned.
 *
 * @param Type
 *        Type of the input device to use.
 *
 * @return STATUS_SUCCESS or error code when attemping to open the device.
 *
 * @remarks This routine supports both mouse and keyboard input devices.
 *
 *--*/
NTSTATUS
RtlCliOpenInputDevice(OUT PHANDLE Handle,
                      IN CON_DEVICE_TYPE Type)
{
    UNICODE_STRING Driver;
    OBJECT_ATTRIBUTES ObjectAttributes;
    IO_STATUS_BLOCK Iosb;
    HANDLE hDriver;
    NTSTATUS Status;

    //
    // Chose the driver to use
    // FIXME: Support MouseType later
    // FIXME: Don't hardcode keyboard path
    //
    if (Type == KeyboardType)
    {
        RtlInitUnicodeString(&Driver, L"\\Device\\KeyboardClass0");
    }

    //
    // Initialize the object attributes
    //
    InitializeObjectAttributes(&ObjectAttributes,
                               &Driver,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    //
    // Open a handle to it
    //
    Status = NtCreateFile(&hDriver,
                          SYNCHRONIZE | GENERIC_READ | FILE_READ_ATTRIBUTES,
                          &ObjectAttributes,
                          &Iosb,
                          NULL,
                          FILE_ATTRIBUTE_NORMAL,
                          0,
                          FILE_OPEN,
                          FILE_DIRECTORY_FILE,
                          NULL,
                          0);

    //
    // Now create an event that will be used to wait on the device
    //
    InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL);
    Status = NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &ObjectAttributes, 1, 0);

    //
    // Return the handle
    //
    *Handle = hDriver;
    return Status;
}
示例#7
0
文件: console.c 项目: GYGit/reactos
VOID NTAPI
ConDrvPause(PCONSOLE Console)
{
    /* In case we already have a pause event, just exit... */
    if (Console->UnpauseEvent) return;

    /* ... otherwise create it */
    NtCreateEvent(&Console->UnpauseEvent, EVENT_ALL_ACCESS,
                  NULL, NotificationEvent, FALSE);
}
示例#8
0
文件: isotest.c 项目: GYGit/reactos
BOOL
ReadBlock(HANDLE FileHandle,
	  PVOID Buffer,
	  PLARGE_INTEGER Offset,
	  ULONG Length,
	  PULONG BytesRead)
{
  IO_STATUS_BLOCK IoStatusBlock;
  OBJECT_ATTRIBUTES ObjectAttributes;
  NTSTATUS Status;
  HANDLE EventHandle;

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

  Status = NtCreateEvent(&EventHandle,
			 EVENT_ALL_ACCESS,
			 &ObjectAttributes,
			 TRUE,
			 FALSE);
  if (!NT_SUCCESS(Status))
    {
      printf("NtCreateEvent() failed\n");
      return(FALSE);
    }

  Status = NtReadFile(FileHandle,
		      EventHandle,
		      NULL,
		      NULL,
		      &IoStatusBlock,
		      Buffer,
		      Length,
		      Offset,
		      NULL);
  if (Status == STATUS_PENDING)
    {
      NtWaitForSingleObject(EventHandle, FALSE, NULL);
      Status = IoStatusBlock.Status;
    }

  NtClose(EventHandle);

  if (Status != STATUS_PENDING && BytesRead != NULL)
    {
      *BytesRead = IoStatusBlock.Information;
    }
  if (!NT_SUCCESS(Status) && Status != STATUS_END_OF_FILE)
    {
      printf("ReadBlock() failed (Status: %lx)\n", Status);
      return(FALSE);
    }

  return(TRUE);
}
示例#9
0
文件: except.c 项目: amir9/longene
/******************************************************************
 *		start_debugger_atomic
 *
 * starts the debugger in an atomic way:
 *	- either the debugger is not started and it is started
 *	- or the debugger has already been started by another thread
 *	- or the debugger couldn't be started
 *
 * returns TRUE for the two first conditions, FALSE for the last
 */
static	int	start_debugger_atomic(PEXCEPTION_POINTERS epointers)
{
    static HANDLE	hRunOnce /* = 0 */;

    if (hRunOnce == 0)
    {
	OBJECT_ATTRIBUTES	attr;
	HANDLE			hEvent;

	attr.Length                   = sizeof(attr);
	attr.RootDirectory            = 0;
	attr.Attributes               = OBJ_INHERIT;
	attr.ObjectName               = NULL;
	attr.SecurityDescriptor       = NULL;
	attr.SecurityQualityOfService = NULL;

	/* ask for manual reset, so that once the debugger is started,
	 * every thread will know it */
	NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
	if (InterlockedCompareExchangePointer( (PVOID)&hRunOnce, hEvent, 0 ) == 0)
	{
	    /* ok, our event has been set... we're the winning thread */
	    BOOL	ret = start_debugger( epointers, hRunOnce );
	    DWORD	tmp;

	    if (!ret)
	    {
		/* so that the other threads won't be stuck */
		NtSetEvent( hRunOnce, &tmp );
	    }
	    return ret;
	}

	/* someone beat us here... */
	CloseHandle( hEvent );
    }

    /* and wait for the winner to have actually created the debugger */
    WaitForSingleObject( hRunOnce, INFINITE );
    /* in fact, here, we only know that someone has tried to start the debugger,
     * we'll know by reposting the exception if it has actually attached
     * to the current process */
    return TRUE;
}
示例#10
0
static void wine_cond_real_init(pthread_cond_t *cond)
{
  wine_cond_detail *detail = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(wine_cond_detail));
  detail->waiters_count = 0;
  detail->was_broadcast = 0;
  NtCreateSemaphore( &detail->sema, SEMAPHORE_ALL_ACCESS, NULL, 0, 0x7fffffff );
  NtCreateEvent( &detail->waiters_done, EVENT_ALL_ACCESS, NULL, FALSE, FALSE );
  RtlInitializeCriticalSection (&detail->waiters_count_lock);

  if (interlocked_cmpxchg_ptr((void**)&(((wine_cond)cond)->cond), detail, NULL) != NULL)
  {
    /* too late, some other thread already did it */
    P_OUTPUT("FIXME:pthread_cond_init:expect troubles...\n");
    NtClose(detail->sema);
    RtlDeleteCriticalSection(&detail->waiters_count_lock);
    NtClose(detail->waiters_done);
    RtlFreeHeap(GetProcessHeap(), 0, detail);
  }
}
示例#11
0
文件: vdm.c 项目: staring/RosFE
NTSTATUS NTAPI BaseSrvCreatePairWaitHandles(PHANDLE ServerEvent, PHANDLE ClientEvent)
{
    NTSTATUS Status;

    /* Create the event */
    Status = NtCreateEvent(ServerEvent, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE);
    if (!NT_SUCCESS(Status)) return Status;

    /* Duplicate the event into the client process */
    Status = NtDuplicateObject(NtCurrentProcess(),
                               *ServerEvent,
                               CsrGetClientThread()->Process->ProcessHandle,
                               ClientEvent,
                               0,
                               0,
                               DUPLICATE_SAME_ATTRIBUTES | DUPLICATE_SAME_ACCESS);

    if (!NT_SUCCESS(Status)) NtClose(*ServerEvent);
    return Status;
}
示例#12
0
/* destroy a process when its refcount is 0 */
void process_destroy(struct object *obj)
{
	struct w32process *process = (struct w32process *)obj;

	ktrace("obj %p\n", obj);

	set_process_startup_state(process, STARTUP_ABORTED);
	if (process->console)
		release_object(process->console);
	if (process->parent)
		release_object(process->parent);
#if 0
	if (process->msg_fd)
		release_object(process->msg_fd);
#endif
	list_remove(&process->entry);

	/* to terminate the services.exe.so */
	if (is_last_list(&process_list)) {
		OBJECT_ATTRIBUTES attr;
		WCHAR process_system[] = {'_','_','p','r','o','c','e','s','s','_','s','y','s','t','e','m',0};
		UNICODE_STRING name;
		NTSTATUS status;
		HANDLE handle = NULL;

		init_unistr(&name, (PWSTR)process_system);
		INIT_OBJECT_ATTR(&attr, &name, 0, base_dir_handle, NULL);
		status = NtCreateEvent(&handle, 0, &attr, 1, 0);
		if (status && status != STATUS_OBJECT_NAME_EXISTS)
			return;
		NtSetEvent(handle, NULL);
		NtClose(handle);
	}
	if (process->idle_event)
		release_object(process->idle_event);
	if (process->queue)
		release_object(process->queue);
	if (process->token)
		release_object(process->token);
}
示例#13
0
文件: event.c 项目: RPG-7/reactos
int
WSPAPI
WSPEventSelect(
	SOCKET Handle,
	WSAEVENT hEventObject,
	long lNetworkEvents,
	LPINT lpErrno)
{
	IO_STATUS_BLOCK				IOSB;
	AFD_EVENT_SELECT_INFO		EventSelectInfo;
	PSOCKET_INFORMATION			Socket = NULL;
	NTSTATUS					Status;
	BOOLEAN						BlockMode;
	HANDLE                                  SockEvent;

	Status = NtCreateEvent( &SockEvent, EVENT_ALL_ACCESS,
				NULL, 1, FALSE );

	if( !NT_SUCCESS(Status) ) return -1;

	/* Get the Socket Structure associate to this Socket*/
	Socket = GetSocketStructure(Handle);
	if (!Socket)
	{
		NtClose(SockEvent);
		*lpErrno = WSAENOTSOCK;
		return SOCKET_ERROR;
	}

	/* Set Socket to Non-Blocking */
	BlockMode = TRUE;
	SetSocketInformation(Socket, AFD_INFO_BLOCKING_MODE, &BlockMode, NULL, NULL);
	Socket->SharedData.NonBlocking = TRUE;

	/* Deactivate Async Select if there is one */
	if (Socket->EventObject) {
		Socket->SharedData.hWnd = NULL;
		Socket->SharedData.wMsg = 0;
		Socket->SharedData.AsyncEvents = 0;
		Socket->SharedData.SequenceNumber++; // This will kill Async Select after the next completion
	}

	/* Set Structure Info */
	EventSelectInfo.EventObject = hEventObject;
	EventSelectInfo.Events = 0;

	/* Set Events to wait for */
	if (lNetworkEvents & FD_READ) {
		EventSelectInfo.Events |= AFD_EVENT_RECEIVE;
    }

    if (lNetworkEvents & FD_WRITE) {
	EventSelectInfo.Events |= AFD_EVENT_SEND;
    }

    if (lNetworkEvents & FD_OOB) {
        EventSelectInfo.Events |= AFD_EVENT_OOB_RECEIVE;
    }

    if (lNetworkEvents & FD_ACCEPT) {
	EventSelectInfo.Events |= AFD_EVENT_ACCEPT;
    }

    if (lNetworkEvents & FD_CONNECT) {
        EventSelectInfo.Events |= AFD_EVENT_CONNECT | AFD_EVENT_CONNECT_FAIL;
    }

    if (lNetworkEvents & FD_CLOSE) {
	EventSelectInfo.Events |= AFD_EVENT_DISCONNECT | AFD_EVENT_ABORT | AFD_EVENT_CLOSE;
    }

    if (lNetworkEvents & FD_QOS) {
	EventSelectInfo.Events |= AFD_EVENT_QOS;
    }

    if (lNetworkEvents & FD_GROUP_QOS) {
	EventSelectInfo.Events |= AFD_EVENT_GROUP_QOS;
    }

    /* Send IOCTL */
    Status = NtDeviceIoControlFile((HANDLE)Handle,
				   SockEvent,
				   NULL,
				   NULL,
				   &IOSB,
				   IOCTL_AFD_EVENT_SELECT,
				   &EventSelectInfo,
				   sizeof(EventSelectInfo),
				   NULL,
				   0);

    TRACE("AFD: %x\n", Status);

    /* Wait for return */
    if (Status == STATUS_PENDING) {
        WaitForSingleObject(SockEvent, INFINITE);
        Status = IOSB.Status;
    }

    TRACE("Waited\n");

    NtClose( SockEvent );

    if (Status != STATUS_SUCCESS)
    {
        ERR("Got status 0x%08x.\n", Status);
        return MsafdReturnWithErrno(Status, lpErrno, 0, NULL);
    }

    TRACE("Closed event\n");

    /* Set Socket Data*/
    Socket->EventObject = hEventObject;
    Socket->NetworkEvents = lNetworkEvents;

    TRACE("Leaving\n");

    return 0;
}
示例#14
0
int
WSPAPI
WSPRecv(SOCKET Handle,
        LPWSABUF lpBuffers,
        DWORD dwBufferCount,
        LPDWORD lpNumberOfBytesRead,
        LPDWORD ReceiveFlags,
        LPWSAOVERLAPPED lpOverlapped,
        LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
        LPWSATHREADID lpThreadId,
        LPINT lpErrno)
{
    PIO_STATUS_BLOCK        IOSB;
    IO_STATUS_BLOCK         DummyIOSB;
    AFD_RECV_INFO           RecvInfo;
    NTSTATUS                Status;
    PVOID                   APCContext;
    PVOID                   APCFunction;
    HANDLE                  Event = NULL;
    HANDLE                  SockEvent;
    PSOCKET_INFORMATION     Socket;

    AFD_DbgPrint(MID_TRACE,("Called (%x)\n", Handle));

    /* Get the Socket Structure associate to this Socket*/
    Socket = GetSocketStructure(Handle);
    if (!Socket)
    {
        *lpErrno = WSAENOTSOCK;
        return SOCKET_ERROR;
    }

    Status = NtCreateEvent( &SockEvent, EVENT_ALL_ACCESS,
                            NULL, 1, FALSE );

    if( !NT_SUCCESS(Status) )
        return -1;

    /* Set up the Receive Structure */
    RecvInfo.BufferArray = (PAFD_WSABUF)lpBuffers;
    RecvInfo.BufferCount = dwBufferCount;
    RecvInfo.TdiFlags = 0;
    RecvInfo.AfdFlags = Socket->SharedData.NonBlocking ? AFD_IMMEDIATE : 0;

    /* Set the TDI Flags */
    if (*ReceiveFlags == 0)
    {
        RecvInfo.TdiFlags |= TDI_RECEIVE_NORMAL;
    }
    else
    {
        if (*ReceiveFlags & MSG_OOB)
        {
            RecvInfo.TdiFlags |= TDI_RECEIVE_EXPEDITED;
        }

        if (*ReceiveFlags & MSG_PEEK)
        {
            RecvInfo.TdiFlags |= TDI_RECEIVE_PEEK;
        }

        if (*ReceiveFlags & MSG_PARTIAL)
        {
            RecvInfo.TdiFlags |= TDI_RECEIVE_PARTIAL;
        }
    }

    /* Verifiy if we should use APC */

    if (lpOverlapped == NULL)
    {
        /* Not using Overlapped structure, so use normal blocking on event */
        APCContext = NULL;
        APCFunction = NULL;
        Event = SockEvent;
        IOSB = &DummyIOSB;
    }
    else
    {
        if (lpCompletionRoutine == NULL)
        {
            /* Using Overlapped Structure, but no Completition Routine, so no need for APC */
            APCContext = lpOverlapped;
            APCFunction = NULL;
            Event = lpOverlapped->hEvent;
        }
        else
        {
            /* Using Overlapped Structure and a Completition Routine, so use an APC */
            APCFunction = NULL; // should be a private io completition function inside us
            APCContext = lpCompletionRoutine;
            RecvInfo.AfdFlags |= AFD_SKIP_FIO;
        }

        IOSB = (PIO_STATUS_BLOCK)&lpOverlapped->Internal;
        RecvInfo.AfdFlags |= AFD_OVERLAPPED;
    }

    IOSB->Status = STATUS_PENDING;

    /* Send IOCTL */
    Status = NtDeviceIoControlFile((HANDLE)Handle,
                                   Event,
                                   APCFunction,
                                   APCContext,
                                   IOSB,
                                   IOCTL_AFD_RECV,
                                   &RecvInfo,
                                   sizeof(RecvInfo),
                                   NULL,
                                   0);

    /* Wait for completition of not overlapped */
    if (Status == STATUS_PENDING && lpOverlapped == NULL)
    {
        /* It's up to the protocol to time out recv.  We must wait
         * until the protocol decides it's had enough.
         */
        WaitForSingleObject(SockEvent, INFINITE);
        Status = IOSB->Status;
    }

    NtClose( SockEvent );

    AFD_DbgPrint(MID_TRACE,("Status %x Information %d\n", Status, IOSB->Information));

    /* Return the Flags */
    *ReceiveFlags = 0;

    switch (Status)
    {
    case STATUS_RECEIVE_EXPEDITED:
        *ReceiveFlags = MSG_OOB;
        break;
    case STATUS_RECEIVE_PARTIAL_EXPEDITED:
        *ReceiveFlags = MSG_PARTIAL | MSG_OOB;
        break;
    case STATUS_RECEIVE_PARTIAL:
        *ReceiveFlags = MSG_PARTIAL;
        break;
    }

    /* Re-enable Async Event */
    if (*ReceiveFlags & MSG_OOB)
    {
        SockReenableAsyncSelectEvent(Socket, FD_OOB);
    }
    else
    {
        SockReenableAsyncSelectEvent(Socket, FD_READ);
    }

    return MsafdReturnWithErrno ( Status, lpErrno, IOSB->Information, lpNumberOfBytesRead );
}
示例#15
0
void
main(
    int argc,
    char *argv[]
    )
{
    NTSTATUS status;
    OBJECT_ATTRIBUTES ObjectAttributes;
    HANDLE          BaseHandle;
    HANDLE          EventHandle;
    PIO_APC_ROUTINE ApcRoutine;

    //
    // Process args
    //

    KeyName.MaximumLength = WORK_SIZE;
    KeyName.Length = 0L;
    KeyName.Buffer = &(workbuffer[0]);

    processargs(argc, argv);

    //
    // Set up and open KeyPath
    //

    printf("rtnotify: starting\n");

    InitializeObjectAttributes(
        &ObjectAttributes,
        &KeyName,
        0,
        (HANDLE)NULL,
        NULL
        );
    ObjectAttributes.Attributes |= OBJ_CASE_INSENSITIVE;

    status = NtOpenKey(
                &BaseHandle,
                KEY_NOTIFY,
                &ObjectAttributes
                );
    if (!NT_SUCCESS(status)) {
        printf("rtnotify: t0: %08lx\n", status);
        exit(1);
    }

    EventHandle = (HANDLE)NULL;
    if (UseEvent == TRUE) {
        status = NtCreateEvent(
                    &EventHandle,
                    GENERIC_READ | GENERIC_WRITE  | SYNCHRONIZE,
                    NULL,
                    NotificationEvent,
                    FALSE
                    );
        if (!NT_SUCCESS(status)) {
            printf("rtnotify: t1: %08lx\n", status);
            exit(1);
        }
    }

    ApcRoutine = NULL;
    if (UseApc) {
        ApcRoutine = ApcTest;
    }

    printf("rtnotify:\n");
    printf("\tUseEvent = %08lx\n", UseEvent);
    printf("\tApcRoutine = %08lx\n", ApcRoutine);
    printf("\tHold = %08lx\n", Hold);
    printf("\tFilter = %08lx\n", Filter);
    printf("\tWatchTree = %08lx\n", WatchTree);

    while (TRUE) {
        ApcSeen = FALSE;
        printf("\nCallCount = %dt\n", CallCount);
        CallCount++;
        status = NtNotifyChangeKey(
                    BaseHandle,
                    EventHandle,
                    ApcRoutine,
                    (PVOID)1992,           // arbitrary context value
                    &RtIoStatusBlock,
                    Filter,
                    WatchTree,
                    NULL,
                    0,
                    ! Hold
                    );

        exit(0);

        if ( ! NT_SUCCESS(status)) {
            printf("rtnotify: t2: %08lx\n", status);
            exit(1);
        }

        if (Hold) {
            printf("rtnotify: Synchronous Status = %08lx\n", RtIoStatusBlock.Status);
        }

        if (UseEvent) {
            status = NtWaitForSingleObject(
                        EventHandle,
                        TRUE,
                        NULL
                        );
            if (!NT_SUCCESS(status)) {
                printf("rtnotify: t3: status = %08lx\n", status);
                exit(1);
            }
            printf("rtnotify: Event Status = %08lx\n", RtIoStatusBlock.Status);
        }

        if (UseApc) {
            while ((volatile)ApcSeen == FALSE) {
                NtTestAlert();
            }
        }
    }

    NtClose(BaseHandle);
    exit(0);
}
示例#16
0
int
WSPAPI
WSPSend(SOCKET Handle,
        LPWSABUF lpBuffers,
        DWORD dwBufferCount,
        LPDWORD lpNumberOfBytesSent,
        DWORD iFlags,
        LPWSAOVERLAPPED lpOverlapped,
        LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
        LPWSATHREADID lpThreadId,
        LPINT lpErrno)
{
    PIO_STATUS_BLOCK        IOSB;
    IO_STATUS_BLOCK         DummyIOSB;
    AFD_SEND_INFO           SendInfo;
    NTSTATUS                Status;
    PVOID                   APCContext;
    PVOID                   APCFunction;
    HANDLE                  Event = NULL;
    HANDLE                  SockEvent;
    PSOCKET_INFORMATION     Socket;

    /* Get the Socket Structure associate to this Socket*/
    Socket = GetSocketStructure(Handle);
    if (!Socket)
    {
        *lpErrno = WSAENOTSOCK;
        return SOCKET_ERROR;
    }

    Status = NtCreateEvent( &SockEvent, EVENT_ALL_ACCESS,
                            NULL, 1, FALSE );

    if( !NT_SUCCESS(Status) )
        return -1;

    AFD_DbgPrint(MID_TRACE,("Called\n"));

    /* Set up the Send Structure */
    SendInfo.BufferArray = (PAFD_WSABUF)lpBuffers;
    SendInfo.BufferCount = dwBufferCount;
    SendInfo.TdiFlags = 0;
    SendInfo.AfdFlags = Socket->SharedData.NonBlocking ? AFD_IMMEDIATE : 0;

    /* Set the TDI Flags */
    if (iFlags)
    {
        if (iFlags & MSG_OOB)
        {
            SendInfo.TdiFlags |= TDI_SEND_EXPEDITED;
        }
        if (iFlags & MSG_PARTIAL)
        {
            SendInfo.TdiFlags |= TDI_SEND_PARTIAL;
        }
    }

    /* Verifiy if we should use APC */
    if (lpOverlapped == NULL)
    {
        /* Not using Overlapped structure, so use normal blocking on event */
        APCContext = NULL;
        APCFunction = NULL;
        Event = SockEvent;
        IOSB = &DummyIOSB;
    }
    else
    {
        if (lpCompletionRoutine == NULL)
        {
            /* Using Overlapped Structure, but no Completition Routine, so no need for APC */
            APCContext = lpOverlapped;
            APCFunction = NULL;
            Event = lpOverlapped->hEvent;
        }
        else
        {
            /* Using Overlapped Structure and a Completition Routine, so use an APC */
            APCFunction = NULL; // should be a private io completition function inside us
            APCContext = lpCompletionRoutine;
            SendInfo.AfdFlags |= AFD_SKIP_FIO;
        }

        IOSB = (PIO_STATUS_BLOCK)&lpOverlapped->Internal;
        SendInfo.AfdFlags |= AFD_OVERLAPPED;
    }

    IOSB->Status = STATUS_PENDING;

    /* Send IOCTL */
    Status = NtDeviceIoControlFile((HANDLE)Handle,
                                   Event,
                                   APCFunction,
                                   APCContext,
                                   IOSB,
                                   IOCTL_AFD_SEND,
                                   &SendInfo,
                                   sizeof(SendInfo),
                                   NULL,
                                   0);

    /* Wait for completition of not overlapped */
    if (Status == STATUS_PENDING && lpOverlapped == NULL)
    {
        WaitForSingleObject(SockEvent, INFINITE); // BUGBUG, shouldn wait infintely for send...
        Status = IOSB->Status;
    }

    NtClose( SockEvent );

    if (Status == STATUS_PENDING)
    {
        AFD_DbgPrint(MID_TRACE,("Leaving (Pending)\n"));
        return MsafdReturnWithErrno(Status, lpErrno, IOSB->Information, lpNumberOfBytesSent);
    }

    /* Re-enable Async Event */
    SockReenableAsyncSelectEvent(Socket, FD_WRITE);

    AFD_DbgPrint(MID_TRACE,("Leaving (Success, %d)\n", IOSB->Information));

    return MsafdReturnWithErrno( Status, lpErrno, IOSB->Information, lpNumberOfBytesSent );
}
示例#17
0
int
WSPAPI
WSPSendTo(SOCKET Handle,
          LPWSABUF lpBuffers,
          DWORD dwBufferCount,
          LPDWORD lpNumberOfBytesSent,
          DWORD iFlags,
          const struct sockaddr *SocketAddress,
          int SocketAddressLength,
          LPWSAOVERLAPPED lpOverlapped,
          LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
          LPWSATHREADID lpThreadId,
          LPINT lpErrno)
{
    PIO_STATUS_BLOCK        IOSB;
    IO_STATUS_BLOCK         DummyIOSB;
    AFD_SEND_INFO_UDP       SendInfo;
    NTSTATUS                Status;
    PVOID                   APCContext;
    PVOID                   APCFunction;
    HANDLE                  Event = NULL;
    PTRANSPORT_ADDRESS      RemoteAddress;
    PSOCKADDR               BindAddress = NULL;
    INT                     BindAddressLength;
    HANDLE                  SockEvent;
    PSOCKET_INFORMATION     Socket;

    /* Get the Socket Structure associate to this Socket */
    Socket = GetSocketStructure(Handle);
    if (!Socket)
    {
        *lpErrno = WSAENOTSOCK;
        return SOCKET_ERROR;
    }

    if (!(Socket->SharedData.ServiceFlags1 & XP1_CONNECTIONLESS))
    {
        /* Use WSPSend for connection-oriented sockets */
        return WSPSend(Handle,
                       lpBuffers,
                       dwBufferCount,
                       lpNumberOfBytesSent,
                       iFlags,
                       lpOverlapped,
                       lpCompletionRoutine,
                       lpThreadId,
                       lpErrno);
    }

    /* Bind us First */
    if (Socket->SharedData.State == SocketOpen)
    {
        /* Get the Wildcard Address */
        BindAddressLength = Socket->HelperData->MaxWSAddressLength;
        BindAddress = HeapAlloc(GlobalHeap, 0, BindAddressLength);
        if (!BindAddress)
        {
            MsafdReturnWithErrno(STATUS_INSUFFICIENT_RESOURCES, lpErrno, 0, NULL);
            return INVALID_SOCKET;
        }

        Socket->HelperData->WSHGetWildcardSockaddr(Socket->HelperContext,
                BindAddress,
                &BindAddressLength);
        /* Bind it */
        if (WSPBind(Handle, BindAddress, BindAddressLength, lpErrno) == SOCKET_ERROR)
            return SOCKET_ERROR;
    }

    RemoteAddress = HeapAlloc(GlobalHeap, 0, 0x6 + SocketAddressLength);
    if (!RemoteAddress)
    {
        if (BindAddress != NULL)
        {
            HeapFree(GlobalHeap, 0, BindAddress);
        }
        return MsafdReturnWithErrno(STATUS_INSUFFICIENT_RESOURCES, lpErrno, 0, NULL);
    }

    Status = NtCreateEvent(&SockEvent,
                           EVENT_ALL_ACCESS,
                           NULL, 1, FALSE);

    if (!NT_SUCCESS(Status))
    {
        HeapFree(GlobalHeap, 0, RemoteAddress);
        if (BindAddress != NULL)
        {
            HeapFree(GlobalHeap, 0, BindAddress);
        }
        return SOCKET_ERROR;
    }

    /* Set up Address in TDI Format */
    RemoteAddress->TAAddressCount = 1;
    RemoteAddress->Address[0].AddressLength = SocketAddressLength - sizeof(SocketAddress->sa_family);
    RtlCopyMemory(&RemoteAddress->Address[0].AddressType, SocketAddress, SocketAddressLength);

    /* Set up Structure */
    SendInfo.BufferArray = (PAFD_WSABUF)lpBuffers;
    SendInfo.AfdFlags = Socket->SharedData.NonBlocking ? AFD_IMMEDIATE : 0;
    SendInfo.BufferCount = dwBufferCount;
    SendInfo.TdiConnection.RemoteAddress = RemoteAddress;
    SendInfo.TdiConnection.RemoteAddressLength = Socket->HelperData->MaxTDIAddressLength;

    /* Verifiy if we should use APC */
    if (lpOverlapped == NULL)
    {
        /* Not using Overlapped structure, so use normal blocking on event */
        APCContext = NULL;
        APCFunction = NULL;
        Event = SockEvent;
        IOSB = &DummyIOSB;
    }
    else
    {
        if (lpCompletionRoutine == NULL)
        {
            /* Using Overlapped Structure, but no Completition Routine, so no need for APC */
            APCContext = lpOverlapped;
            APCFunction = NULL;
            Event = lpOverlapped->hEvent;
        }
        else
        {
            /* Using Overlapped Structure and a Completition Routine, so use an APC */
            /* Should be a private io completition function inside us */
            APCFunction = NULL;
            APCContext = lpCompletionRoutine;
            SendInfo.AfdFlags |= AFD_SKIP_FIO;
        }

        IOSB = (PIO_STATUS_BLOCK)&lpOverlapped->Internal;
        SendInfo.AfdFlags |= AFD_OVERLAPPED;
    }

    /* Send IOCTL */
    Status = NtDeviceIoControlFile((HANDLE)Handle,
                                   Event,
                                   APCFunction,
                                   APCContext,
                                   IOSB,
                                   IOCTL_AFD_SEND_DATAGRAM,
                                   &SendInfo,
                                   sizeof(SendInfo),
                                   NULL,
                                   0);

    /* Wait for completition of not overlapped */
    if (Status == STATUS_PENDING && lpOverlapped == NULL)
    {
        /* BUGBUG, shouldn't wait infintely for send... */
        WaitForSingleObject(SockEvent, INFINITE);
        Status = IOSB->Status;
    }

    NtClose(SockEvent);
    HeapFree(GlobalHeap, 0, RemoteAddress);
    if (BindAddress != NULL)
    {
        HeapFree(GlobalHeap, 0, BindAddress);
    }

    SockReenableAsyncSelectEvent(Socket, FD_WRITE);

    return MsafdReturnWithErrno(Status, lpErrno, IOSB->Information, lpNumberOfBytesSent);
}
示例#18
0
/*++
 * @name CsrServerInitialization
 * @implemented NT4
 *
 * The CsrServerInitialization routine is the native (not Server) entrypoint
 * of this Server DLL. It serves as the entrypoint for CSRSS.
 *
 * @param ArgumentCount
 *        Number of arguments on the command line.
 *
 * @param Arguments
 *        Array of arguments from the command line.
 *
 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
 *
 * @remarks None.
 *
 *--*/
NTSTATUS
NTAPI
CsrServerInitialization(IN ULONG ArgumentCount,
                        IN PCHAR Arguments[])
{
    NTSTATUS Status = STATUS_SUCCESS;

    /* Create the Init Event */
    Status = NtCreateEvent(&CsrInitializationEvent,
                           EVENT_ALL_ACCESS,
                           NULL,
                           SynchronizationEvent,
                           FALSE);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: NtCreateEvent failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Cache System Basic Information so we don't always request it */
    Status = NtQuerySystemInformation(SystemBasicInformation,
                                      &CsrNtSysInfo,
                                      sizeof(SYSTEM_BASIC_INFORMATION),
                                      NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: NtQuerySystemInformation failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Save our Heap */
    CsrHeap = RtlGetProcessHeap();

    /* Set our Security Descriptor to protect the process */
    Status = CsrSetProcessSecurity();
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: CsrSetProcessSecurity failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Set up Session Support */
    Status = CsrInitializeNtSessionList();
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: CsrInitializeSessions failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Set up Process Support and allocate the CSR Root Process */
    Status = CsrInitializeProcessStructure();
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: CsrInitializeProcessStructure failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Parse the command line */
    Status = CsrParseServerCommandLine(ArgumentCount, Arguments);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: CsrParseServerCommandLine failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Finish to initialize the CSR Root Process */
    Status = CsrInitCsrRootProcess();
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: CsrInitCsrRootProcess failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Now initialize our API Port */
    Status = CsrApiPortInitialize();
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: CsrApiPortInitialize failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Initialize the API Port for SM communication */
    Status = CsrSbApiPortInitialize();
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: CsrSbApiPortInitialize failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* We're all set! Connect to SM! */
    Status = SmConnectToSm(&CsrSbApiPortName,
                           CsrSbApiPort,
                           IMAGE_SUBSYSTEM_WINDOWS_GUI,
                           &CsrSmApiPort);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: SmConnectToSm failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Finito! Signal the event */
    Status = NtSetEvent(CsrInitializationEvent, NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: NtSetEvent failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Close the event handle now */
    NtClose(CsrInitializationEvent);

    /* Have us handle Hard Errors */
    Status = NtSetDefaultHardErrorPort(CsrApiPort);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("CSRSRV:%s: NtSetDefaultHardErrorPort failed (Status=%08lx)\n",
                __FUNCTION__, Status);
        return Status;
    }

    /* Return status */
    return Status;
}
示例#19
0
BOOLEAN WepCreateServerObjects(
    VOID
    )
{
    OBJECT_ATTRIBUTES objectAttributes;
    WCHAR buffer[256];
    UNICODE_STRING objectName;

    if (!WeServerSharedSection)
    {
        LARGE_INTEGER maximumSize;

        WeFormatLocalObjectName(WE_SERVER_SHARED_SECTION_NAME, buffer, &objectName);
        InitializeObjectAttributes(&objectAttributes, &objectName, OBJ_CASE_INSENSITIVE, NULL, NULL);
        maximumSize.QuadPart = sizeof(WE_HOOK_SHARED_DATA);

        if (!NT_SUCCESS(NtCreateSection(
            &WeServerSharedSection,
            SECTION_ALL_ACCESS,
            &objectAttributes,
            &maximumSize,
            PAGE_READWRITE,
            SEC_COMMIT,
            NULL
            )))
        {
            return FALSE;
        }
    }

    if (!WeServerSharedData)
    {
        PVOID viewBase;
        SIZE_T viewSize;

        viewBase = NULL;
        viewSize = sizeof(WE_HOOK_SHARED_DATA);

        if (!NT_SUCCESS(NtMapViewOfSection(
            WeServerSharedSection,
            NtCurrentProcess(),
            &viewBase,
            0,
            0,
            NULL,
            &viewSize,
            ViewShare,
            0,
            PAGE_READWRITE
            )))
        {
            WepCloseServerObjects();
            return FALSE;
        }

        WeServerSharedData = viewBase;
    }

    if (!WeServerSharedSectionLock)
    {
        WeFormatLocalObjectName(WE_SERVER_SHARED_SECTION_LOCK_NAME, buffer, &objectName);
        InitializeObjectAttributes(&objectAttributes, &objectName, OBJ_CASE_INSENSITIVE, NULL, NULL);

        if (!NT_SUCCESS(NtCreateMutant(
            &WeServerSharedSectionLock,
            MUTANT_ALL_ACCESS,
            &objectAttributes,
            FALSE
            )))
        {
            WepCloseServerObjects();
            return FALSE;
        }
    }

    if (!WeServerSharedSectionEvent)
    {
        WeFormatLocalObjectName(WE_SERVER_SHARED_SECTION_EVENT_NAME, buffer, &objectName);
        InitializeObjectAttributes(&objectAttributes, &objectName, OBJ_CASE_INSENSITIVE, NULL, NULL);

        if (!NT_SUCCESS(NtCreateEvent(
            &WeServerSharedSectionEvent,
            EVENT_ALL_ACCESS,
            &objectAttributes,
            NotificationEvent,
            FALSE
            )))
        {
            WepCloseServerObjects();
            return FALSE;
        }
    }

    return TRUE;
}
示例#20
0
文件: synch.c 项目: shuowen/OpenNT
HANDLE
APIENTRY
CreateEventW(
    LPSECURITY_ATTRIBUTES lpEventAttributes,
    BOOL bManualReset,
    BOOL bInitialState,
    LPCWSTR lpName
)

/*++

Routine Description:

    An event object is created and a handle opened for access to the
    object with the CreateEvent function.

    The CreateEvent function creates an event object with the specified
    initial state.  If an event is in the Signaled state (TRUE), a wait
    operation on the event does not block.  If the event is in the Not-
    Signaled state (FALSE), a wait operation on the event blocks until
    the specified event attains a state of Signaled, or the timeout
    value is exceeded.

    In addition to the STANDARD_RIGHTS_REQUIRED access flags, the following
    object type specific access flags are valid for event objects:

        - EVENT_MODIFY_STATE - Modify state access (set and reset) to
          the event is desired.

        - SYNCHRONIZE - Synchronization access (wait) to the event is
          desired.

        - EVENT_ALL_ACCESS - This set of access flags specifies all of
          the possible access flags for an event object.


Arguments:

    lpEventAttributes - An optional parameter that may be used to
        specify the attributes of the new event.  If the parameter is
        not specified, then the event is created without a security
        descriptor, and the resulting handle is not inherited on process
        creation.

    bManualReset - Supplies a flag which if TRUE specifies that the
        event must be manually reset.  If the value is FALSE, then after
        releasing a single waiter, the system automaticaly resets the
        event.

    bInitialState - The initial state of the event object, one of TRUE
        or FALSE.  If the InitialState is specified as TRUE, the event's
        current state value is set to one, otherwise it is set to zero.

    lpName - Optional unicode name of event

Return Value:

    NON-NULL - Returns a handle to the new event.  The handle has full
        access to the new event and may be used in any API that requires
        a handle to an event object.

    FALSE/NULL - The operation failed. Extended error status is available
        using GetLastError.

--*/

{
    NTSTATUS Status;
    OBJECT_ATTRIBUTES Obja;
    POBJECT_ATTRIBUTES pObja;
    HANDLE Handle;
    UNICODE_STRING ObjectName;

    if ( ARGUMENT_PRESENT(lpName) ) {
        RtlInitUnicodeString(&ObjectName,lpName);
        pObja = BaseFormatObjectAttributes(&Obja,lpEventAttributes,&ObjectName);
    }
    else {
        pObja = BaseFormatObjectAttributes(&Obja,lpEventAttributes,NULL);
    }

    Status = NtCreateEvent(
                 &Handle,
                 EVENT_ALL_ACCESS,
                 pObja,
                 bManualReset ? NotificationEvent : SynchronizationEvent,
                 (BOOLEAN)bInitialState
             );
    if ( NT_SUCCESS(Status) ) {
        if ( Status == STATUS_OBJECT_NAME_EXISTS ) {
            SetLastError(ERROR_ALREADY_EXISTS);
        }
        else {
            SetLastError(0);
        }
        return Handle;
    }
    else {
        BaseSetLastNTError(Status);
        return NULL;
    }
}
示例#21
0
文件: push.c 项目: Volkanite/Push
INT32 __stdcall start( )
{
    HANDLE sectionHandle, *hMutex;
    HANDLE eventHandle;
    HANDLE threadHandle;
    DWORD sectionSize;
    MSG messages;
    OBJECT_ATTRIBUTES objAttrib = {0};
    PTEB threadEnvironmentBlock;
    UNICODE_STRING eventSource;
    LDR_DATA_TABLE_ENTRY *module;
    SECTION_BASIC_INFORMATION sectionInfo;
    LARGE_INTEGER newSectionSize;

    InitializeCRT();

    threadEnvironmentBlock = NtCurrentTeb();

    PushProcessId = threadEnvironmentBlock->ClientId.UniqueProcess;
    PushHeapHandle = threadEnvironmentBlock->ProcessEnvironmentBlock->ProcessHeap;
    PushSessionId = threadEnvironmentBlock->ProcessEnvironmentBlock->SessionId;

    // Check if already running
    hMutex = CreateMutexW(0, FALSE, L"PushOneInstance");

    if (threadEnvironmentBlock->LastErrorValue == ERROR_ALREADY_EXISTS
        || threadEnvironmentBlock->LastErrorValue == ERROR_ACCESS_DENIED)
    {
        MessageBoxW(0, L"Only one instance!", 0,0);
        ExitProcess(0);
    }


    //create image event
    eventHandle = NULL;

    UnicodeString_Init(&eventSource, L"Global\\" PUSH_IMAGE_EVENT_NAME);

    objAttrib.Length = sizeof(OBJECT_ATTRIBUTES);
    objAttrib.RootDirectory = BaseGetNamedObjectDirectory();
    objAttrib.ObjectName = &eventSource;
    objAttrib.Attributes = OBJ_OPENIF;
    objAttrib.SecurityDescriptor = NULL;
    objAttrib.SecurityQualityOfService = NULL;

    NtCreateEvent(&eventHandle, EVENT_ALL_ACCESS, &objAttrib, NotificationEvent, FALSE);

    // populate file name and path
    module = (LDR_DATA_TABLE_ENTRY*)threadEnvironmentBlock->ProcessEnvironmentBlock->Ldr->InLoadOrderModuleList.Flink;

    Memory_Copy(PushFilePath, module->FullDllName.Buffer, module->FullDllName.Length);

    PushFilePath[module->FullDllName.Length] = L'\0';

    // Start Driver.
    Driver_Extract();
    PushDriverLoaded = Driver_Load();

    //initialize instance
    PushInstance = Module_GetHandle(L"Push.exe");

    // Create interface
    MwCreateMainWindow();

    // Create section.
    sectionSize = sizeof(PUSH_SHARED_MEMORY) + OSD_GetSize();

    PushSharedMemory = (PUSH_SHARED_MEMORY*)Memory_MapViewOfSection(PUSH_SECTION_NAME, sectionSize, &sectionHandle);

    if (!PushSharedMemory)
    {
        Log(L"Could not create shared memory");
        return 0;
    }

    Log(L"Created section of size %i bytes", sectionSize);

    //zero struct
    Memory_Clear(PushSharedMemory, sizeof(PUSH_SHARED_MEMORY));

    //initialize window handle used by overlay
    //PushSharedMemory->WindowHandle = PushMainWindow->Handle;

    //initialize default font properties for overlay
    String_Copy(PushSharedMemory->FontName, L"Verdana");
    PushSharedMemory->FontBold = TRUE;

    if (File_Exists(PUSH_SETTINGS_FILE))
    {
        wchar_t *buffer;
        wchar_t marker;

        // Check if file is UTF-16LE.
        buffer = (WCHAR*) File_Load(PUSH_SETTINGS_FILE, NULL);
        marker = buffer[0];

        Memory_Free(buffer);

        if (marker == 0xFEFF)
            //is UTF-LE.
        {
            // Init settings from ini file.

            buffer = Memory_Allocate(100 * sizeof(WCHAR));

            Ini_GetString(L"Settings", L"FrameLimit", NULL, buffer, 5, L".\\" PUSH_SETTINGS_FILE);
            PushSharedMemory->FrameLimit = _wtoi(buffer);

            if (Ini_ReadBoolean(L"Settings", L"ThreadOptimization", FALSE, L".\\" PUSH_SETTINGS_FILE))
                PushSharedMemory->ThreadOptimization = TRUE;

            if (Ini_ReadBoolean(L"Settings", L"KeepFps", FALSE, L".\\" PUSH_SETTINGS_FILE))
                PushSharedMemory->KeepFps = TRUE;

            Ini_GetString(L"Settings", L"OverlayInterface", NULL, buffer, 5, L".\\" PUSH_SETTINGS_FILE);

            if (String_Compare(buffer, L"PURE") == 0)
                PushOverlayInterface = OVERLAY_INTERFACE_PURE;
            else if (String_Compare(buffer, L"RTSS") == 0)
                PushOverlayInterface = OVERLAY_INTERFACE_RTSS;

            Ini_GetString(L"Settings", L"KeyboardHookType", L"AUTO", buffer, 10, L".\\" PUSH_SETTINGS_FILE);

            if (String_Compare(buffer, L"AUTO") == 0)
            {
                PushSharedMemory->KeyboardHookType = KEYBOARD_HOOK_AUTO;
            }
            else if (String_Compare(buffer, L"SUBCLASS") == 0)
            {
                PushSharedMemory->KeyboardHookType = KEYBOARD_HOOK_SUBCLASS;
            }
            else if (String_Compare(buffer, L"MESSAGE") == 0)
            {
                PushSharedMemory->KeyboardHookType = KEYBOARD_HOOK_MESSAGE;
            }
            else if (String_Compare(buffer, L"KEYBOARD") == 0)
            {
                PushSharedMemory->KeyboardHookType = KEYBOARD_HOOK_KEYBOARD;
            }
            else if (String_Compare(buffer, L"DETOURS") == 0)
            {
                PushSharedMemory->KeyboardHookType = KEYBOARD_HOOK_DETOURS;
            }
            else if (String_Compare(buffer, L"RAW") == 0)
            {
                PushSharedMemory->KeyboardHookType = KEYBOARD_HOOK_RAW;
            }
            else
            {
                PushSharedMemory->KeyboardHookType = KEYBOARD_HOOK_AUTO;
            }

            Ini_GetString(L"Settings", L"EngineClockMax", NULL, buffer, 5, L".\\" PUSH_SETTINGS_FILE);
            PushSharedMemory->HarwareInformation.DisplayDevice.EngineOverclock = _wtoi(buffer);

            Ini_GetString(L"Settings", L"MemoryClockMax", NULL, buffer, 5, L".\\" PUSH_SETTINGS_FILE);
            PushSharedMemory->HarwareInformation.DisplayDevice.MemoryOverclock = _wtoi(buffer);

            Ini_GetString(L"Settings", L"ControllerTimeout", NULL, buffer, 5, L".\\" PUSH_SETTINGS_FILE);
            PushSharedMemory->ControllerTimeout = _wtoi(buffer);

            Ini_GetString(L"Settings", L"FontName", L"Verdana", buffer, 100, L".\\" PUSH_SETTINGS_FILE);
            String_Copy(PushSharedMemory->FontName, buffer);

            Memory_Free(buffer);

            if (Ini_ReadBoolean(L"Settings", L"FontBold", FALSE, L".\\" PUSH_SETTINGS_FILE))
                PushSharedMemory->FontBold = TRUE;
        }
        else
        {
            MessageBoxW(
                NULL,
                L"Settings file not UTF-16LE! "
                L"Resave the file as \"Unicode\" or Push won't read it!",
                L"Bad Settings file",
                NULL
                );
        }
    }

    if (!PushDriverLoaded)
    {
        wchar_t driverPath[260];

        Resource_Extract(L"DRIVERALT", L"WinRing0x64.sys");
        GetDriverPath(L"WinRing0x64.sys", driverPath);
        Wr0DriverLoaded = Wr0Initialize(driverPath);
    }

    //initialize HWInfo
    GetHardwareInfo();

    //initialize OSD items

    NtQuerySection(
        sectionHandle,
        SectionBasicInformation,
        &sectionInfo,
        sizeof(SECTION_BASIC_INFORMATION),
        NULL
        );

    newSectionSize.QuadPart = OSD_Initialize() + sizeof(PUSH_SHARED_MEMORY);

    if (newSectionSize.QuadPart > sectionInfo.MaximumSize.QuadPart)
    {
        Log(L"Shared memory too small!");
    }

    //Check for controllers/gamepads/bluetooth adapters
    //EnumerateDevices();

    // Check for running games
    Process_EnumProcesses(ProcessEnum);

    // Activate process monitoring
    if (PushDriverLoaded)
    {
        PushToggleProcessMonitoring(TRUE);
    }
    else
    {
        HANDLE overlayLib = NULL;
        void* prcAddress = 0;

        Resource_Extract(L"OVERLAY32", PUSH_LIB_NAME_32);

        overlayLib = Module_Load(L"overlay32.dll");
        prcAddress = Module_GetProcedureAddress(overlayLib, "InstallOverlayHook");

        if (prcAddress)
        {
            InstallOverlayHook = (TYPE_InstallOverlayHook)prcAddress;
            InstallOverlayHook();
        }
    }

    g_szPrevGame[5] = '\0';

    NtCreateThreadEx(
        &PushMonitorThreadHandle,
        THREAD_ALL_ACCESS,
        NULL,
        NtCurrentProcess(),
        &MonitorThread,
        NULL,
        NoThreadFlags,
        0, 0, 0,
        NULL
        );

    NtCreateThreadEx(
        &threadHandle,
        THREAD_ALL_ACCESS,
        NULL,
        NtCurrentProcess(),
        &PipeThread,
        NULL,
        NoThreadFlags,
        0, 0, 0,
        NULL
        );

    // Handle messages

    while(GetMessageW(&messages, 0,0,0))
    {
        TranslateMessage(&messages);

        DispatchMessageW(&messages);
    }

    ExitProcess(0);

    return 0;
}
示例#22
0
VOID NotificationThread(
    PVOID pJunk)
{
    INT         nEvents = ID_MEDIACHANGE;
    INT         nMediaEvents = 0;
    KPRIORITY   Priority;
    NTSTATUS    Status;
    HANDLE      hEvent[ MAXIMUM_WAIT_OBJECTS ];

    try {

        /*
         * Set the priority of the RIT to 3.
         */
        Priority = LOW_PRIORITY + 3;
        NtSetInformationThread(hThreadNotification, ThreadPriority, &Priority,
                sizeof(KPRIORITY));

        /*
         * Setup the NLS event
         */
        NtCreateEvent(&ghNlsEvent, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE);
        UserAssert( ghNlsEvent != NULL );
        hEvent[ID_NLS] = ghNlsEvent;

        /*
         * Setup the MediaChangeEvent
         */
        RtlZeroMemory(wcDriveCache, sizeof(wcDriveCache));
        Status = NtUserGetMediaChangeEvents(MAXIMUM_WAIT_OBJECTS - ID_MEDIACHANGE,
                                            &hEvent[ID_MEDIACHANGE],
                                            &nMediaEvents);
        if (NT_SUCCESS(Status)) {
            nEvents += nMediaEvents;
        }
#ifdef DEBUG
        else {
            KdPrint(("NotificationThread: NtUserGetMediaChangeEvents failed 0x08X\n", Status));
        }
#endif

        StartRegReadRead();

        /*
         * Sit and wait forever.
         */
        while (TRUE) {
            Status = NtWaitForMultipleObjects(nEvents,
                                              hEvent,
                                              WaitAny,
                                              TRUE,
                                              NULL);


            if (Status == ID_NLS + WAIT_OBJECT_0) {

                /*
                 * Handle the NLS event
                 */
                if (gfLogon) {
                    gfLogon = FALSE;
                    BaseSrvNlsUpdateRegistryCache(NULL, NULL);
                }

            }
            else if (Status >= ID_MEDIACHANGE + WAIT_OBJECT_0 &&
                     Status < (ID_MEDIACHANGE + nMediaEvents + WAIT_OBJECT_0)) {
                /*
                 * Handle the CD-ROM \Device\MediaChangeEventX event
                 */

                NtResetEvent( hEvent[Status - WAIT_OBJECT_0], NULL );
                HandleMediaChangeEvent( Status - WAIT_OBJECT_0 - ID_MEDIACHANGE );
            }

        } // While (TRUE)

    } except (CsrUnhandledExceptionFilter(GetExceptionInformation())) {
        KdPrint(("Registry notification thread is dead, sorry.\n"));
    }
}
示例#23
0
文件: repl.c 项目: mingpen/OpenNT
NTSTATUS
ReplicationInit ( )

/*++

Routine Description:


Arguments: 


Return Value:

--*/

{
   DWORD Ignore;
   HANDLE Thread;
   NTSTATUS Status;
   DWORD Time;

#if DBG
   if (TraceFlags & (TRACE_FUNCTION_TRACE | TRACE_REPLICATION))
      dprintf(TEXT("LLS TRACE: ReplicationInit\n"));
#endif

   //
   // Open up our RPC DLL and init our function references.
   //
   LlsRPCHandle = LoadLibrary(TEXT("LLSRPC.DLL"));
   ASSERT(LlsRPCHandle != NULL);

   if (LlsRPCHandle != NULL) {
      pLlsReplConnect = GetProcAddress(LlsRPCHandle, ("LlsReplConnectW"));
      pLlsReplClose = GetProcAddress(LlsRPCHandle, ("LlsReplClose"));
      pLlsFreeMemory = GetProcAddress(LlsRPCHandle, ("LlsFreeMemory"));
      pLlsReplicationRequestW = GetProcAddress(LlsRPCHandle, ("LlsReplicationRequestW"));
      pLlsReplicationServerAddW = GetProcAddress(LlsRPCHandle, ("LlsReplicationServerAddW"));
      pLlsReplicationServerServiceAddW = GetProcAddress(LlsRPCHandle, ("LlsReplicationServerServiceAddW"));
      pLlsReplicationServiceAddW = GetProcAddress(LlsRPCHandle, ("LlsReplicationServiceAddW"));
      pLlsReplicationUserAddW = GetProcAddress(LlsRPCHandle, ("LlsReplicationUserAddW"));
      pLlsReplicationCertDbAddW = (PLLS_REPLICATION_CERT_DB_ADD_W) GetProcAddress(LlsRPCHandle, ("LlsReplicationCertDbAddW"));
      pLlsReplicationProductSecurityAddW = (PLLS_REPLICATION_PRODUCT_SECURITY_ADD_W) GetProcAddress(LlsRPCHandle, ("LlsReplicationProductSecurityAddW"));
      pLlsReplicationUserAddExW = (PLLS_REPLICATION_USER_ADD_EX_W) GetProcAddress(LlsRPCHandle, ("LlsReplicationUserAddExW"));
      pLlsCapabilityIsSupported = (PLLS_CAPABILITY_IS_SUPPORTED) GetProcAddress(LlsRPCHandle, ("LlsCapabilityIsSupported"));
      pLlsConnectW = (PLLS_CONNECT_W) GetProcAddress(LlsRPCHandle, ("LlsConnectW"));
      pLlsClose = (PLLS_CLOSE) GetProcAddress(LlsRPCHandle, ("LlsClose"));

      ASSERT (pLlsReplConnect != NULL);
      ASSERT (pLlsReplClose != NULL);
      ASSERT (pLlsFreeMemory != NULL);
      ASSERT (pLlsReplicationRequestW != NULL);
      ASSERT (pLlsReplicationServerAddW != NULL);
      ASSERT (pLlsReplicationServerServiceAddW != NULL);
      ASSERT (pLlsReplicationServiceAddW != NULL);
      ASSERT (pLlsReplicationUserAddW != NULL);
      ASSERT (pLlsReplicationCertDbAddW != NULL);
      ASSERT (pLlsReplicationProductSecurityAddW != NULL);
      ASSERT (pLlsReplicationUserAddExW != NULL);
      ASSERT (pLlsCapabilityIsSupported != NULL);
      ASSERT (pLlsConnectW != NULL);
      ASSERT (pLlsClose != NULL);

      if ((pLlsReplConnect != NULL) && (pLlsReplClose != NULL) &&
          (pLlsFreeMemory != NULL) && (pLlsReplicationRequestW != NULL) &&
          (pLlsReplicationServerAddW != NULL) && (pLlsReplicationServiceAddW != NULL) &&
          (pLlsReplicationServerServiceAddW != NULL) && (pLlsReplicationUserAddW != NULL) &&
          (pLlsReplicationCertDbAddW != NULL) && (pLlsReplicationProductSecurityAddW != NULL) &&
          (pLlsReplicationUserAddExW != NULL) && (pLlsCapabilityIsSupported != NULL) &&
          (pLlsConnectW != NULL) && (pLlsClose != NULL)
          ) {

         //
         // Create the Replication Management event
         //
         Status = NtCreateEvent(
                      &ReplicationEvent,
                      EVENT_QUERY_STATE | EVENT_MODIFY_STATE | SYNCHRONIZE,
                      NULL,
                      SynchronizationEvent,
                      FALSE
                      );

         ASSERT(NT_SUCCESS(Status));                    

         //
         // Fire off the thread to watch for replication.
         //
         Thread = CreateThread(
                      NULL,
                      0L,
                      (LPTHREAD_START_ROUTINE) ReplicationManager,
                      0L,
                      0L,
                      &Ignore
                      );

      }
   }

   return STATUS_SUCCESS;
} // ReplicationInit
示例#24
0
文件: task.c 项目: Barrell/wine
/***********************************************************************
 *           TASK_Create
 *
 * NOTE: This routine might be called by a Win32 thread. Thus, we need
 *       to be careful to protect global data structures. We do this
 *       by entering the Win16Lock while linking the task into the
 *       global task list.
 */
static TDB *TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, LPCSTR cmdline, BYTE len )
{
    HTASK16 hTask;
    TDB *pTask;
    FARPROC16 proc;
    char curdir[MAX_PATH];
    HMODULE16 hModule = pModule ? pModule->self : 0;

      /* Allocate the task structure */

    hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
    if (!hTask) return NULL;
    pTask = TASK_GetPtr( hTask );
    FarSetOwner16( hTask, hModule );

    /* Fill the task structure */

    pTask->hSelf = hTask;

    pTask->version       = pModule ? pModule->ne_expver : 0x0400;
    pTask->hModule       = hModule;
    pTask->hParent       = GetCurrentTask();
    pTask->magic         = TDB_MAGIC;
    pTask->nCmdShow      = cmdShow;

    GetCurrentDirectoryA( sizeof(curdir), curdir );
    GetShortPathNameA( curdir, curdir, sizeof(curdir) );
    pTask->curdrive = (curdir[0] - 'A') | 0x80;
    lstrcpynA( pTask->curdir, curdir + 2, sizeof(pTask->curdir) );

      /* Create the thunks block */

    TASK_CreateThunks( hTask, (char *)pTask->thunks - (char *)pTask, 7 );

      /* Copy the module name */

    if (hModule)
    {
        char name[sizeof(pTask->module_name)+1];
        size_t len;
        GetModuleName16( hModule, name, sizeof(name) );
        len = strlen(name) + 1;
        memcpy(pTask->module_name, name, min(len,sizeof(pTask->module_name)));
        pTask->compat_flags = GetProfileIntA( "Compatibility", name, 0 );
    }

      /* Allocate a selector for the PDB */

    pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
                                      hModule, WINE_LDT_FLAGS_DATA );

      /* Fill the PDB */

    pTask->pdb.int20 = 0x20cd;
    pTask->pdb.dispatcher[0] = 0x9a;  /* ljmp */
    proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DOS3Call" );
    memcpy( &pTask->pdb.dispatcher[1], &proc, sizeof(proc) );
    pTask->pdb.savedint22 = 0;
    pTask->pdb.savedint23 = 0;
    pTask->pdb.savedint24 = 0;
    pTask->pdb.fileHandlesPtr =
        MAKESEGPTR( GlobalHandleToSel16(pTask->hPDB), FIELD_OFFSET( PDB16, fileHandles ));
    pTask->pdb.hFileHandles = 0;
    memset( pTask->pdb.fileHandles, 0xff, sizeof(pTask->pdb.fileHandles) );
    /* FIXME: should we make a copy of the environment? */
    pTask->pdb.environment    = SELECTOROF(GetDOSEnvironment16());
    pTask->pdb.nbFiles        = 20;

    /* Fill the command line */

    if (!cmdline)
    {
        cmdline = GetCommandLineA();
        /* remove the first word (program name) */
        if (*cmdline == '"')
            if (!(cmdline = strchr( cmdline+1, '"' ))) cmdline = GetCommandLineA();
        while (*cmdline && (*cmdline != ' ') && (*cmdline != '\t')) cmdline++;
        while ((*cmdline == ' ') || (*cmdline == '\t')) cmdline++;
        len = strlen(cmdline);
    }
    if (len >= sizeof(pTask->pdb.cmdLine)) len = sizeof(pTask->pdb.cmdLine)-1;
    pTask->pdb.cmdLine[0] = len;
    memcpy( pTask->pdb.cmdLine + 1, cmdline, len );
    /* pTask->pdb.cmdLine[len+1] = 0; */

    TRACE("cmdline='%.*s' task=%04x\n", len, cmdline, hTask );

      /* Allocate a code segment alias for the TDB */

    pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, pTask, sizeof(TDB),
                                          pTask->hPDB, WINE_LDT_FLAGS_CODE );

      /* Default DTA overwrites command line */

    pTask->dta = MAKESEGPTR( pTask->hPDB, FIELD_OFFSET( PDB16, cmdLine ));

    /* Create scheduler event for 16-bit tasks */

    if ( !(pTask->flags & TDBF_WIN32) )
        NtCreateEvent( &pTask->hEvent, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE );

    if (!initial_task) initial_task = hTask;

    return pTask;
}
示例#25
0
/*page*******************************************************
       d o _ t d i _ a c t i o n

       Generate a TDI_ACTION down to the streams
       driver.

       Arguments - fd     = Handle to send on
            cmd    = Command to send down
            optbuf = Ptr to options buffer
            optlen = Ptr to options length
            addrflag = TRUE  = This is for DG/STREAM socket on addr handle
                       FALSE = This is for conn handle

       Returns - A WinSock error code (NO_ERROR = OK)
************************************************************/
INT do_tdi_action(HANDLE fd, ULONG cmd, PUCHAR optbuf, INT optlen, BOOLEAN addrflag, PHANDLE eventhandle OPTIONAL)
{
    NTSTATUS status;
    PSTREAMS_TDI_ACTION tdibuf;
    ULONG           tdilen;
    IO_STATUS_BLOCK iostat;
    HANDLE          event;


    /** If the eventhandle is passed, it also means that the **/
    /** NWLINK_ACTION header is pre-allocated in the buffer, **/
    /** although we still have to fill the header in here.   **/

    if (eventhandle == NULL) {

        /** Get the length of the buffer we need to allocate **/

        tdilen = FIELD_OFFSET(STREAMS_TDI_ACTION,Buffer) + sizeof(ULONG) + optlen;

        /** Allocate a buffer to use for the action **/

        tdibuf = RtlAllocateHeap(RtlProcessHeap(), 0, tdilen);
        if (tdibuf == NULL) {
           return WSAENOBUFS;
        }

    } else {

        tdilen = optlen;
        tdibuf = (PSTREAMS_TDI_ACTION)optbuf;

    }

    /** Set the datagram option **/

    RtlMoveMemory(&tdibuf->Header.TransportId, "MISN", 4);
    tdibuf->DatagramOption = addrflag;

    /**
       Fill out the buffer, the buffer looks like this:

       ULONG cmd
       data passed.
    **/

    memcpy(tdibuf->Buffer, &cmd, sizeof(ULONG));

    if (eventhandle == NULL) {

        tdibuf->BufferLength = sizeof(ULONG) + optlen;

        RtlMoveMemory(tdibuf->Buffer + sizeof(ULONG), optbuf, optlen);

        /** Create an event to wait on **/

        status = NtCreateEvent(
           &event,
           EVENT_ALL_ACCESS,
           NULL,
           SynchronizationEvent,
           FALSE);

        /** If no event - then return error **/

        if (!NT_SUCCESS(status)) {
           RtlFreeHeap(RtlProcessHeap(), 0, tdibuf);
           return WSAENOBUFS;
        }

    } else {

        tdibuf->BufferLength = sizeof(ULONG) + optlen - FIELD_OFFSET (NWLINK_ACTION, Data[0]);

        /** Use the event handle passed in **/

        event = *eventhandle;

    }

    /** **/

    status = NtDeviceIoControlFile(
       fd,
       event,
       NULL,
       NULL,
       &iostat,
       IOCTL_TDI_ACTION,
       NULL,
       0,
       tdibuf,
       tdilen);


    if (eventhandle == NULL) {

        /** If pending - wait for it to finish **/

        if (status == STATUS_PENDING) {
           status = NtWaitForSingleObject(event, FALSE, NULL);
           ASSERT(status == 0);
           status = iostat.Status;
        }

        /** Close the event **/

        NtClose(event);

    }

    /** If we get an error - return it **/

    if (!NT_SUCCESS(status)) {
       if (eventhandle == NULL) {
           RtlFreeHeap(RtlProcessHeap(), 0, tdibuf);
       }
       return WSAEINVAL;
    }

    if (eventhandle == NULL) {

        /** Copy the returned back to optbuf if needed */

        if (optlen) {
            RtlMoveMemory (optbuf, tdibuf->Buffer + sizeof(ULONG), optlen);
        }

        RtlFreeHeap(RtlProcessHeap(), 0, tdibuf);

    }

    /** Return OK **/

    return NO_ERROR;
}
示例#26
0
文件: event.c 项目: RPG-7/reactos
INT
WSPAPI
WSPEnumNetworkEvents(
  IN  SOCKET Handle,
  IN  WSAEVENT hEventObject,
  OUT LPWSANETWORKEVENTS lpNetworkEvents,
  OUT LPINT lpErrno)
{
    AFD_ENUM_NETWORK_EVENTS_INFO EnumReq;
    IO_STATUS_BLOCK				IOSB;
    PSOCKET_INFORMATION			Socket = NULL;
    NTSTATUS					Status;
    HANDLE                                  SockEvent;

    TRACE("Called (lpNetworkEvents %x)\n", lpNetworkEvents);

    Status = NtCreateEvent( &SockEvent, EVENT_ALL_ACCESS,
			    NULL, 1, FALSE );

    if( !NT_SUCCESS(Status) ) {
        ERR("Could not make an event %x\n", Status);
        return -1;
    }

    /* Get the Socket Structure associate to this Socket*/
    Socket = GetSocketStructure(Handle);
    if (!Socket)
    {
       NtClose(SockEvent);
       *lpErrno = WSAENOTSOCK;
       return SOCKET_ERROR;
    }

    EnumReq.Event = hEventObject;

    /* Send IOCTL */
    Status = NtDeviceIoControlFile((HANDLE)Handle,
				   SockEvent,
				   NULL,
				   NULL,
				   &IOSB,
				   IOCTL_AFD_ENUM_NETWORK_EVENTS,
				   &EnumReq,
				   sizeof(EnumReq),
				   NULL,
				   0);

    TRACE("AFD: %x\n", Status);

    /* Wait for return */
    if (Status == STATUS_PENDING) {
        WaitForSingleObject(SockEvent, INFINITE);
        Status = IOSB.Status;
    }

    TRACE("Waited\n");

    NtClose( SockEvent );

    if (Status != STATUS_SUCCESS)
    {
        ERR("Status 0x%08x", Status);
        return MsafdReturnWithErrno(Status, lpErrno, 0, NULL);
    }

    TRACE("Closed event\n");
    TRACE("About to touch struct at %x (%d)\n", lpNetworkEvents, sizeof(*lpNetworkEvents));

    lpNetworkEvents->lNetworkEvents = 0;

    /* Set Events to wait for */
    if (EnumReq.PollEvents & AFD_EVENT_RECEIVE) {
        lpNetworkEvents->lNetworkEvents |= FD_READ;
        lpNetworkEvents->iErrorCode[FD_READ_BIT] = TranslateNtStatusError(EnumReq.EventStatus[FD_READ_BIT]);
    }

    if (EnumReq.PollEvents & AFD_EVENT_SEND) {
        lpNetworkEvents->lNetworkEvents |= FD_WRITE;
        lpNetworkEvents->iErrorCode[FD_WRITE_BIT] = TranslateNtStatusError(EnumReq.EventStatus[FD_WRITE_BIT]);
    }

    if (EnumReq.PollEvents & AFD_EVENT_OOB_RECEIVE) {
        lpNetworkEvents->lNetworkEvents |= FD_OOB;
        lpNetworkEvents->iErrorCode[FD_OOB_BIT] = TranslateNtStatusError(EnumReq.EventStatus[FD_OOB_BIT]);
    }

    if (EnumReq.PollEvents & AFD_EVENT_ACCEPT) {
        lpNetworkEvents->lNetworkEvents |= FD_ACCEPT;
        lpNetworkEvents->iErrorCode[FD_ACCEPT_BIT] = TranslateNtStatusError(EnumReq.EventStatus[FD_ACCEPT_BIT]);
    }

    if (EnumReq.PollEvents &
            (AFD_EVENT_CONNECT | AFD_EVENT_CONNECT_FAIL)) {
        lpNetworkEvents->lNetworkEvents |= FD_CONNECT;
        lpNetworkEvents->iErrorCode[FD_CONNECT_BIT] = TranslateNtStatusError(EnumReq.EventStatus[FD_CONNECT_BIT]);
    }

    if (EnumReq.PollEvents &
	(AFD_EVENT_DISCONNECT | AFD_EVENT_ABORT | AFD_EVENT_CLOSE)) {
        lpNetworkEvents->lNetworkEvents |= FD_CLOSE;
        lpNetworkEvents->iErrorCode[FD_CLOSE_BIT] = TranslateNtStatusError(EnumReq.EventStatus[FD_CLOSE_BIT]);
    }

    if (EnumReq.PollEvents & AFD_EVENT_QOS) {
	lpNetworkEvents->lNetworkEvents |= FD_QOS;
	lpNetworkEvents->iErrorCode[FD_QOS_BIT] = TranslateNtStatusError(EnumReq.EventStatus[FD_QOS_BIT]);
    }

    if (EnumReq.PollEvents & AFD_EVENT_GROUP_QOS) {
        lpNetworkEvents->lNetworkEvents |= FD_GROUP_QOS;
        lpNetworkEvents->iErrorCode[FD_GROUP_QOS_BIT] = TranslateNtStatusError(EnumReq.EventStatus[FD_GROUP_QOS_BIT]);
    }

    TRACE("Leaving\n");

    return MsafdReturnWithErrno(STATUS_SUCCESS, lpErrno, 0, NULL);
}
示例#27
0
NTSTATUS PhpServiceNonPollThreadStart(
    _In_ PVOID Parameter
    )
{
    ULONG result;
    SC_HANDLE scManagerHandle;
    LPENUM_SERVICE_STATUS_PROCESS services;
    ULONG numberOfServices;
    ULONG i;
    PLIST_ENTRY listEntry;
    PPHP_SERVICE_NOTIFY_CONTEXT notifyContext;

    if (!NT_SUCCESS(NtCreateEvent(&PhpNonPollEventHandle, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE)))
    {
        PhpNonPollActive = FALSE;
        PhpNonPollGate = 1;
        return STATUS_UNSUCCESSFUL;
    }

    while (TRUE)
    {
        scManagerHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE);

        if (!scManagerHandle)
            goto ErrorExit;

        InitializeListHead(&PhpNonPollServiceListHead);
        InitializeListHead(&PhpNonPollServicePendingListHead);

        if (!(services = PhEnumServices(scManagerHandle, 0, 0, &numberOfServices)))
            goto ErrorExit;

        for (i = 0; i < numberOfServices; i++)
        {
            SC_HANDLE serviceHandle;

            if (serviceHandle = OpenService(scManagerHandle, services[i].lpServiceName, SERVICE_QUERY_STATUS))
            {
                notifyContext = PhAllocate(sizeof(PHP_SERVICE_NOTIFY_CONTEXT));
                memset(notifyContext, 0, sizeof(PHP_SERVICE_NOTIFY_CONTEXT));
                notifyContext->ServiceHandle = serviceHandle;
                notifyContext->State = SnNotify;
                InsertTailList(&PhpNonPollServicePendingListHead, &notifyContext->ListEntry);
            }
        }

        PhFree(services);

        notifyContext = PhAllocate(sizeof(PHP_SERVICE_NOTIFY_CONTEXT));
        memset(notifyContext, 0, sizeof(PHP_SERVICE_NOTIFY_CONTEXT));
        notifyContext->ServiceHandle = scManagerHandle;
        notifyContext->IsServiceManager = TRUE;
        notifyContext->State = SnNotify;
        InsertTailList(&PhpNonPollServicePendingListHead, &notifyContext->ListEntry);

        while (TRUE)
        {
            BOOLEAN lagging = FALSE;

            listEntry = PhpNonPollServicePendingListHead.Flink;

            while (listEntry != &PhpNonPollServicePendingListHead)
            {
                notifyContext = CONTAINING_RECORD(listEntry, PHP_SERVICE_NOTIFY_CONTEXT, ListEntry);
                listEntry = listEntry->Flink;

                switch (notifyContext->State)
                {
                case SnNone:
                    break;
                case SnAdding:
                    notifyContext->ServiceHandle =
                        OpenService(scManagerHandle, notifyContext->ServiceName->Buffer, SERVICE_QUERY_STATUS);

                    if (!notifyContext->ServiceHandle)
                    {
                        RemoveEntryList(&notifyContext->ListEntry);
                        PhpDestroyServiceNotifyContext(notifyContext);
                        continue;
                    }

                    PhClearReference(&notifyContext->ServiceName);
                    notifyContext->State = SnNotify;
                    goto NotifyCase;
                case SnRemoving:
                    RemoveEntryList(&notifyContext->ListEntry);
                    PhpDestroyServiceNotifyContext(notifyContext);
                    break;
                case SnNotify:
NotifyCase:
                    memset(&notifyContext->Buffer, 0, sizeof(SERVICE_NOTIFY));
                    notifyContext->Buffer.dwVersion = SERVICE_NOTIFY_STATUS_CHANGE;
                    notifyContext->Buffer.pfnNotifyCallback = PhpServiceNonPollScNotifyCallback;
                    notifyContext->Buffer.pContext = notifyContext;
                    result = NotifyServiceStatusChangeW_I(
                        notifyContext->ServiceHandle,
                        notifyContext->IsServiceManager
                        ? (SERVICE_NOTIFY_CREATED | SERVICE_NOTIFY_DELETED)
                        : (SERVICE_NOTIFY_STOPPED | SERVICE_NOTIFY_START_PENDING | SERVICE_NOTIFY_STOP_PENDING |
                        SERVICE_NOTIFY_RUNNING | SERVICE_NOTIFY_CONTINUE_PENDING | SERVICE_NOTIFY_PAUSE_PENDING |
                        SERVICE_NOTIFY_PAUSED | SERVICE_NOTIFY_DELETE_PENDING),
                        &notifyContext->Buffer
                        );

                    switch (result)
                    {
                    case ERROR_SUCCESS:
                        notifyContext->State = SnNone;
                        RemoveEntryList(&notifyContext->ListEntry);
                        InsertTailList(&PhpNonPollServiceListHead, &notifyContext->ListEntry);
                        break;
                    case ERROR_SERVICE_NOTIFY_CLIENT_LAGGING:
                        // We are lagging behind. Re-open the handle to the SCM as soon as possible.
                        lagging = TRUE;
                        break;
                    case ERROR_SERVICE_MARKED_FOR_DELETE:
                    default:
                        RemoveEntryList(&notifyContext->ListEntry);
                        PhpDestroyServiceNotifyContext(notifyContext);
                        break;
                    }

                    break;
                }
            }

            while (NtWaitForSingleObject(PhpNonPollEventHandle, TRUE, NULL) != STATUS_WAIT_0)
                NOTHING;

            if (lagging)
                break;
        }

        // Execute all pending callbacks.
        NtTestAlert();

        listEntry = PhpNonPollServiceListHead.Flink;

        while (listEntry != &PhpNonPollServiceListHead)
        {
            notifyContext = CONTAINING_RECORD(listEntry, PHP_SERVICE_NOTIFY_CONTEXT, ListEntry);
            listEntry = listEntry->Flink;
            PhpDestroyServiceNotifyContext(notifyContext);
        }

        listEntry = PhpNonPollServicePendingListHead.Flink;

        while (listEntry != &PhpNonPollServicePendingListHead)
        {
            notifyContext = CONTAINING_RECORD(listEntry, PHP_SERVICE_NOTIFY_CONTEXT, ListEntry);
            listEntry = listEntry->Flink;
            PhpDestroyServiceNotifyContext(notifyContext);
        }

        CloseServiceHandle(scManagerHandle);
    }

    NtClose(PhpNonPollEventHandle);

    return STATUS_SUCCESS;

ErrorExit:
    PhpNonPollActive = FALSE;
    PhpNonPollGate = 1;
    NtClose(PhpNonPollEventHandle);
    return STATUS_UNSUCCESSFUL;
}
示例#28
0
文件: file.c 项目: aaam/NativeShell
/*++
 * @name RtlCliListDirectory
 *
 * The RtlCliListDirectory routine lists the current directory contents.
 *
 * @param None.
 *
 * @return NTSTATUS
 *
 * @remarks Documentation for this routine needs to be completed.
 *
 *--*/
NTSTATUS
RtlCliListDirectory(VOID)
{
    UNICODE_STRING DirectoryString;
    OBJECT_ATTRIBUTES ObjectAttributes;
    HANDLE DirectoryHandle;
    NTSTATUS Status;
    IO_STATUS_BLOCK IoStatusBlock;
    BOOLEAN FirstQuery = TRUE;
    WCHAR CurrentDirectory[MAX_PATH];
    PFILE_BOTH_DIR_INFORMATION DirectoryInfo, Entry;
    HANDLE EventHandle;
    CHAR i, c;

    //
    // For now, we only support the current directory (ie: you can't dir e:\
    // without CDing into it first
    //
    RtlCliGetCurrentDirectory(CurrentDirectory);

    //
    // Convert it to NT Format
    //
    if (!RtlDosPathNameToNtPathName_U(CurrentDirectory,
                                      &DirectoryString,
                                      NULL,
                                      NULL))
    {
        //
        // Fail
        //
        return STATUS_UNSUCCESSFUL;
    }

    //
    // Initialize the object attributes
    //
    RtlCliDisplayString(" Directory of %S\n\n", CurrentDirectory);
    InitializeObjectAttributes(&ObjectAttributes,
                               &DirectoryString,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    //
    // Open the directory
    //
    Status = ZwCreateFile(&DirectoryHandle,
                          FILE_LIST_DIRECTORY,
                          &ObjectAttributes,
                          &IoStatusBlock,
                          NULL,
                          0,
                          FILE_SHARE_READ | FILE_SHARE_WRITE,
                          FILE_OPEN,
                          FILE_DIRECTORY_FILE,
                          NULL,
                          0);

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

    //
    // Allocate space for directory entry information
    //
    DirectoryInfo = RtlAllocateHeap(RtlGetProcessHeap(), 0, 4096);
    
    if (!DirectoryInfo) 
    {
      return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    // Create the event to wait on
    //
    InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL);
    Status = NtCreateEvent(&EventHandle,
                           EVENT_ALL_ACCESS,
                           &ObjectAttributes,
                           SynchronizationEvent,
                           FALSE);

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

    //
    // Start loop
    //
    i = 0;
    for (;;)
    {
        //
        // Get the contents of the directory, adding up the size as we go
        //
        Status = ZwQueryDirectoryFile(DirectoryHandle,
                                      EventHandle,
                                      NULL,
                                      0,
                                      &IoStatusBlock,
                                      DirectoryInfo,
                                      4096,
                                      FileBothDirectoryInformation,
                                      FALSE,
                                      NULL,
                                      FirstQuery);
        if (Status == STATUS_PENDING)
        {
            //
            // Wait on the event
            //
            NtWaitForSingleObject(EventHandle, FALSE, NULL);
            Status = IoStatusBlock.Status;
        }

        //
        // Check for success
        //
        if (!NT_SUCCESS(Status))
        {
            //
            // Nothing left to enumerate. Close handles and free memory
            //
            ZwClose(DirectoryHandle);
            RtlFreeHeap(RtlGetProcessHeap(), 0, DirectoryInfo);
            return STATUS_SUCCESS;
        }

        //
        // Loop every directory
        //
        Entry = DirectoryInfo;

        
        while(Entry)
        {            
            //
            // List the file
            //
            RtlCliDumpFileInfo(Entry);

            if (++i > 20)
            {
              i = 0;
              RtlCliDisplayString("Continue listing (Y/N):");         
              while (TRUE)
              {
                c = RtlCliGetChar(hKeyboard);
                if (c == 'n' || c == 'N')
                {
                  RtlCliDisplayString("\n");
                  return STATUS_SUCCESS;
                }
                if (c == 'y' || c == 'Y')
                {                  
                  break;
                }
              }     
              RtlCliDisplayString("\n");
            }

            //
            // Make sure we still have a file
            //
            if (!Entry->NextEntryOffset) break;

            //
            // Move to the next one
            //
            Entry = (PFILE_BOTH_DIR_INFORMATION)((ULONG_PTR)Entry +
                                                 Entry->NextEntryOffset);          
        }

        //
        // This isn't the first scan anymore
        //
        FirstQuery = FALSE;
    }
}
示例#29
0
NTSTATUS
StartAuthenticationPort(VOID)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING PortName;
    DWORD ThreadId;
    UNICODE_STRING EventName;
    HANDLE EventHandle;
    NTSTATUS Status;

    TRACE("StartAuthenticationPort()\n");

    /* Initialize the logon context list */
    InitializeListHead(&LsapLogonContextList);

    RtlInitUnicodeString(&PortName,
                         L"\\LsaAuthenticationPort");

    InitializeObjectAttributes(&ObjectAttributes,
                               &PortName,
                               0,
                               NULL,
                               NULL);

    Status = NtCreatePort(&AuthPortHandle,
                          &ObjectAttributes,
                          sizeof(LSA_CONNECTION_INFO),
                          sizeof(LSA_API_MSG),
                          sizeof(LSA_API_MSG) * 32);
    if (!NT_SUCCESS(Status))
    {
        WARN("NtCreatePort() failed (Status %lx)\n", Status);
        return Status;
    }

    RtlInitUnicodeString(&EventName,
                         L"\\SECURITY\\LSA_AUTHENTICATION_INITIALIZED");
    InitializeObjectAttributes(&ObjectAttributes,
                               &EventName,
                               OBJ_CASE_INSENSITIVE | OBJ_PERMANENT,
                               NULL,
                               NULL);
    Status = NtOpenEvent(&EventHandle,
                         EVENT_MODIFY_STATE,
                         &ObjectAttributes);
    if (!NT_SUCCESS(Status))
    {
        TRACE("NtOpenEvent failed (Status 0x%08lx)\n", Status);

        Status = NtCreateEvent(&EventHandle,
                               EVENT_MODIFY_STATE,
                               &ObjectAttributes,
                               NotificationEvent,
                               FALSE);
        if (!NT_SUCCESS(Status))
        {
            WARN("NtCreateEvent failed (Status 0x%08lx)\n", Status);
            return Status;
        }
    }

    Status = NtSetEvent(EventHandle, NULL);
    NtClose(EventHandle);
    if (!NT_SUCCESS(Status))
    {
        WARN("NtSetEvent failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    PortThreadHandle = CreateThread(NULL,
                                    0x1000,
                                    (LPTHREAD_START_ROUTINE)AuthPortThreadRoutine,
                                    NULL,
                                    0,
                                    &ThreadId);


    return STATUS_SUCCESS;
}
示例#30
0
NTSTATUS UserServerDllInitialization(
    PCSR_SERVER_DLL psrvdll)
{
    CLIENT_ID ClientId;
    DWORD cbAllocated;
    NTSTATUS Status;
    int i;

    /*
     * Initialize a critical section structure that will be used to protect
     * all of the User Server's critical sections (except a few special
     * cases like the RIT -- see below).
     */
    RtlInitializeCriticalSection(&gcsUserSrv);
    EnterCrit(); // synchronize heap calls

    /*
     * Remember WINSRV.DLL's hmodule so we can grab resources from it later.
     */
    hModuleWin = psrvdll->ModuleHandle;

    psrvdll->ApiNumberBase = USERK_FIRST_API_NUMBER;
    psrvdll->MaxApiNumber = UserpMaxApiNumber;
    psrvdll->ApiDispatchTable = UserServerApiDispatchTable;
    psrvdll->ApiServerValidTable = UserServerApiServerValidTable;
#if DBG
    psrvdll->ApiNameTable = UserServerApiNameTable;
#else
    psrvdll->ApiNameTable = NULL;
#endif
    psrvdll->PerProcessDataLength   = CHANDLES * sizeof(HANDLE);
    psrvdll->PerThreadDataLength    = 0;
    psrvdll->ConnectRoutine         = UserClientConnect;
    psrvdll->DisconnectRoutine      = UserClientDisconnect;
    psrvdll->HardErrorRoutine       = UserHardError;
    psrvdll->ShutdownProcessRoutine = UserClientShutdown;

    /*
     * Create these events used by shutdown
     */
    NtCreateEvent(&heventCancel, EVENT_ALL_ACCESS, NULL,
                  NotificationEvent, FALSE);
    NtCreateEvent(&heventCancelled, EVENT_ALL_ACCESS, NULL,
                  NotificationEvent, FALSE);

    /*
     * Tell the base what user address to call when it is creating a process
     * (but before the process starts running).
     */
    BaseSetProcessCreateNotify(NtUserNotifyProcessCreate);

    /*
     * Set up translation tables.
     */
    InitOemXlateTables();

    /*
     * Get timeout values from registry
     */
    GetTimeouts();

    /*
     * Load some strings.
     */
    pszaSUCCESS            = (LPSTR)RtlLoadStringOrError(hModuleWin,
                                STR_SUCCESS, NULL, &cbAllocated, TRUE);
    pszaSYSTEM_INFORMATION = (LPSTR)RtlLoadStringOrError(hModuleWin,
                                STR_SYSTEM_INFORMATION, NULL, &cbAllocated, TRUE);
    pszaSYSTEM_WARNING     = (LPSTR)RtlLoadStringOrError(hModuleWin,
                                STR_SYSTEM_WARNING, NULL, &cbAllocated, TRUE);
    pszaSYSTEM_ERROR       = (LPSTR)RtlLoadStringOrError(hModuleWin,
                                STR_SYSTEM_ERROR, NULL, &cbAllocated, TRUE);

    /*
     * Add marlett font and make it permanent
     */
    i = GdiAddFontResourceW(L"marlett.ttf", AFRW_ADD_LOCAL_FONT);

    /*
     * Initialize USER
     */
    {
        HANDLE hModBase;

        LeaveCrit();
        hModBase = GetModuleHandle(TEXT("kernel32"));
        EnterCrit();
        UserAssert(hModBase);
        gpfnAttachRoutine = GetProcAddress(hModBase,"BaseAttachCompleteThunk");
        UserAssert(gpfnAttachRoutine);

        Status = NtUserInitialize(USERCURRENTVERSION, gpfnAttachRoutine);
        if (!NT_SUCCESS(Status)) {
            goto ExitUserInit;
        }
    }

    /*
     * Start registry notification thread
     */
    Status = RtlCreateUserThread(NtCurrentProcess(), NULL, FALSE, 0, 0, 4*0x1000,
            (PUSER_THREAD_START_ROUTINE)NotificationThread, NULL, &hThreadNotification,
            &ClientId);
    CsrAddStaticServerThread(hThreadNotification, &ClientId, 0);

ExitUserInit:
    LeaveCrit();
    return Status;
}