Exemple #1
0
NTSTATUS WINAPI HID_Device_create(DEVICE_OBJECT *device, IRP *irp)
{
    BASE_DEVICE_EXTENSION *ext = device->DeviceExtension;

    TRACE("Open handle on device %p\n", device);
    irp->Tail.Overlay.OriginalFileObject->FsContext = UlongToPtr(RingBuffer_AddPointer(ext->ring_buffer));
    irp->IoStatus.u.Status = STATUS_SUCCESS;
    IoCompleteRequest( irp, IO_NO_INCREMENT );
    return STATUS_SUCCESS;
}
Exemple #2
0
/*
 * @implemented
 */
VOID
EXPORT
NdisImmediateReadPortUshort(
    IN  NDIS_HANDLE WrapperConfigurationContext,
    IN  ULONG       Port,
    OUT PUSHORT     Data)
{
  NDIS_DbgPrint(MAX_TRACE, ("Called.\n"));
  *Data = READ_PORT_USHORT(UlongToPtr(Port)); // FIXME: What to do with WrapperConfigurationContext?
}
Exemple #3
0
/*
 * @implemented
 */
VOID
EXPORT
NdisImmediateWritePortUshort(
    IN  NDIS_HANDLE WrapperConfigurationContext,
    IN  ULONG       Port,
    IN  USHORT      Data)
{
  NDIS_DbgPrint(MAX_TRACE, ("Called.\n"));
  WRITE_PORT_USHORT(UlongToPtr(Port), Data); // FIXME: What to do with WrapperConfigurationContext?
}
Exemple #4
0
/*
 * @implemented
 */
HANDLE
WSAAPI
WSAAsyncGetProtoByNumber(IN HWND hWnd,
                         IN UINT wMsg,
                         IN INT Number,
                         OUT CHAR FAR* Buffer,
                         IN INT BufferLength)
{
    HANDLE TaskHandle;
    PWSPROCESS Process;
    PWSTHREAD Thread;
    PWSASYNCBLOCK AsyncBlock;
    INT ErrorCode;
    DPRINT("WSAAsyncGetProtoByNumber: %lx, %lx, %lx\n", hWnd, wMsg, Number);
    
    /* Enter prolog */
    if ((ErrorCode = WsApiProlog(&Process, &Thread)) != ERROR_SUCCESS)
    {
        /* Leave now */
        SetLastError(ErrorCode);
        return NULL;
    }

    /* Initialize the Async Thread */
    if (!WsAsyncCheckAndInitThread())
    {
        /* Fail */
        SetLastError(WSAENOBUFS);
        return NULL;
    }

    /* Allocate an async block */
    if (!(AsyncBlock = WsAsyncAllocateBlock(0)))
    {
        /* Fail */
        SetLastError(WSAENOBUFS);
        return NULL;
    }

    /* Initialize the Async Block */
    AsyncBlock->Operation = WsAsyncGetProtoByNumber;
    AsyncBlock->GetProto.hWnd = hWnd;
    AsyncBlock->GetProto.wMsg = wMsg;
    AsyncBlock->GetProto.ByWhat = UlongToPtr(Number);
    AsyncBlock->GetProto.Buffer = Buffer;
    AsyncBlock->GetProto.BufferLength = BufferLength;

    /* Save the task handle and queue the request */
    TaskHandle = AsyncBlock->TaskHandle;
    WsAsyncQueueRequest(AsyncBlock);

    /* Return the task handle */
    return TaskHandle;
}
static void Test_MouseSpeed()
{
    ULONG ulMouseSpeed, temp;
    BOOL ret;

    ret = SystemParametersInfo(SPI_GETMOUSESPEED, 0, &ulMouseSpeed, 0);
    ok(ret, "SystemParametersInfo failed\n");
    ok(ulMouseSpeed >= 1 && ulMouseSpeed <=20, "Wrong mouse speed (%d)\n", (int)ulMouseSpeed);

    temp = 1;
    ret = SystemParametersInfo(SPI_SETMOUSESPEED, 0, UlongToPtr(temp), SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);
    ok(ret, "SystemParametersInfo failed\n");
    ret = SystemParametersInfo(SPI_GETMOUSESPEED, 0, &temp, 0);
    ok(ret, "SystemParametersInfo failed\n");
    ok(temp == 1, "SPI_GETMOUSESPEED did not get value set by SPI_SETMOUSESPEED (%d instead of 1)\n", (int)temp);

    temp = 20;
    ret = SystemParametersInfo(SPI_SETMOUSESPEED, 0, UlongToPtr(temp), SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);
    ok(ret, "SystemParametersInfo failed\n");
    ret = SystemParametersInfo(SPI_GETMOUSESPEED, 0, &temp, 0);
    ok(ret, "SystemParametersInfo failed\n");
    ok(temp == 20, "SPI_GETMOUSESPEED did not get value set by SPI_SETMOUSESPEED (%d instead of 20)\n", (int)temp);

    temp = 21;
    ret = SystemParametersInfo(SPI_SETMOUSESPEED, 0, UlongToPtr(temp), SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);
    ok(!ret, "expected SystemParametersInfo to fail\n");
    ret = SystemParametersInfo(SPI_GETMOUSESPEED, 0, &temp, 0);
    ok(ret, "SystemParametersInfo failed\n");
    ok(temp == 20, "SPI_GETMOUSESPEED got unexpected value (%d instead of 20)\n", (int)temp);

    temp = 0;
    ret = SystemParametersInfo(SPI_SETMOUSESPEED, 0, UlongToPtr(temp), SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);
    ok(!ret, "expected SystemParametersInfo to fail\n");
    ret = SystemParametersInfo(SPI_GETMOUSESPEED, 0, &temp, 0);
    ok(ret, "SystemParametersInfo failed\n");
    ok(temp == 20, "SPI_GETMOUSESPEED got unexpected value (%d instead of 20)\n", (int)temp);

    ret = SystemParametersInfo(SPI_SETMOUSESPEED, 0, UlongToPtr(ulMouseSpeed), SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);
    ok(ret, "SystemParametersInfo failed\n");
}
Exemple #6
0
LRESULT CALLBACK GDisplayWndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
	if (Msg == WM_CREATE)
	{
		// Pointer to a value to be passed to the window through 
		// the CREATESTRUCT structure is out window object instance.
		LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam;
		GDisplay* pGDisplay = static_cast<GDisplay*>(pcs->lpCreateParams);
		// Store the pointer as private data of the window
		::SetWindowLongPtr(hWnd, GWLP_USERDATA, PtrToUlong(pGDisplay)); 
		pGDisplay->Attach(hWnd);
		pGDisplay->OnCreate();
		return 0;
	}

	// Extract the pointer to out window object
	GDisplay* pGDisplay = static_cast<GDisplay*>(UlongToPtr(::GetWindowLongPtr(hWnd, GWLP_USERDATA)));

	if (pGDisplay)
	{
		PAINTSTRUCT ps;
		switch (Msg)
		{
		case WM_SIZE:
			pGDisplay->OnSize(wParam, lParam);
			return 0;

		case WM_ERASEBKGND:
			return 0;

		case WM_DISPLAYCHANGE:
		case WM_PAINT:
			{
				BeginPaint(hWnd, &ps);
				pGDisplay->OnPaint(ps.hdc);
				EndPaint(hWnd, &ps);
			}
			return 0;

		case WM_DESTROY:
			pGDisplay->OnDestroy();
			break;

		default:
			return DefWindowProc(hWnd, Msg, wParam, lParam);
		}
	}

	return DefWindowProc(hWnd, Msg, wParam, lParam);
}
Exemple #7
0
VOID DriveMapInstallInt13Handler(PDRIVE_MAP_LIST DriveMap)
{
    ULONG*  RealModeIVT = (ULONG*)UlongToPtr(0x00000000);
    USHORT* BiosLowMemorySize = (USHORT*)ULongToPtr(0x00000413);

    if (!DriveMapInstalled)
    {
        // Get the old INT 13h handler address from the vector table
        OldInt13HandlerAddress = RealModeIVT[0x13];

        // Decrease the size of low memory
        (*BiosLowMemorySize)--;

        // Get linear address for drive map handler
        DriveMapHandlerAddress = (ULONG)(*BiosLowMemorySize) << 10;

        // Convert to segment:offset style address
        DriveMapHandlerSegOff = (DriveMapHandlerAddress << 12) & 0xffff0000;
    }

    // Copy the drive map structure to the proper place
    RtlCopyMemory(&DriveMapInt13HandlerMapList, DriveMap, sizeof(DRIVE_MAP_LIST));

    // Set the address of the BIOS INT 13h handler
    DriveMapOldInt13HandlerAddress = OldInt13HandlerAddress;

    // Copy the code to our reserved area
    RtlCopyMemory(UlongToPtr(DriveMapHandlerAddress),
                  &DriveMapInt13HandlerStart,
                  ((PUCHAR)&DriveMapInt13HandlerEnd - (PUCHAR)&DriveMapInt13HandlerStart));

    // Update the IVT
    RealModeIVT[0x13] = DriveMapHandlerSegOff;

    CacheInvalidateCacheData();
    DriveMapInstalled = TRUE;
}
Exemple #8
0
VOID UnHookD3DFunction(DWORD dwRVA)
{
	HMODULE hD3D9;
	PBYTE pbFuncAddress;
	DWORD dwOldProtect;

	hD3D9 = GetModuleHandle("d3d9.dll");
	if(hD3D9)
	{
		pbFuncAddress = (PBYTE)UlongToPtr(PtrToUlong(hD3D9) + dwRVA);
		VirtualProtect(pbFuncAddress, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
		memcpy(pbFuncAddress, "\x8B\xFF\x55\x8B\xEC", 5);
		VirtualProtect(pbFuncAddress, 5, dwOldProtect, &dwOldProtect);
	}
}
Exemple #9
0
NTSTATUS
IoctlToLanscsiBusByWorker(
	IN PDEVICE_OBJECT	WorkerDeviceObject,
	IN ULONG			IoControlCode,
    IN PVOID			InputBuffer  OPTIONAL,
    IN ULONG			InputBufferLength
) {
	NDSC_WORKITEM_INIT	WorkitemCtx;
	NTSTATUS			status;

	NDSC_INIT_WORKITEM(	&WorkitemCtx,
							IoctlToLanscsiBus_Worker,
							(PCCB)UlongToPtr(IoControlCode),
							InputBuffer,
							UlongToPtr(InputBufferLength),
							NULL);
	status = MiniQueueWorkItem(&NdasMiniGlobalData, WorkerDeviceObject, &WorkitemCtx);
	if(!NT_SUCCESS(status)) {
		if(InputBufferLength && InputBuffer)
			ExFreePoolWithTag(InputBuffer, NDSC_PTAG_IOCTL);
	}

	return status;
}
Exemple #10
0
PWSASYNCBLOCK
WSAAPI
WsAsyncAllocateBlock(IN SIZE_T ExtraLength)
{
    PWSASYNCBLOCK AsyncBlock;

    /* Add the size of the block */
    ExtraLength += sizeof(WSASYNCBLOCK);

    /* Allocate it */
    AsyncBlock = HeapAlloc(WsSockHeap, 0, ExtraLength);

    /* Get a handle to it */
    AsyncBlock->TaskHandle = UlongToPtr(InterlockedIncrement(&WsAsyncTaskHandle));

    /* Return it */
    return AsyncBlock;
}
Exemple #11
0
PBL_BLOCK_DESCRIPTOR
MmBapFindBlockInformation (
    ULONG BlockId
    )
{
    ULONG EntryId;

    /* Find the block that matches */
    EntryId = BlockId;
    return BlTblFindEntry(MmBlockAllocatorTable,
                          MmBlockAllocatorTableEntries,
                          &EntryId,
                          MmBapCompareBlockAllocatorTableEntry,
                          UlongToPtr(EntryId),
                          NULL,
                          NULL,
                          NULL);
}
Exemple #12
0
static int wine_pthread_join(pthread_t thread, void **value_ptr)
{
  THREAD_BASIC_INFORMATION info;
  CLIENT_ID cid;
  NTSTATUS status;
  HANDLE handle;

  cid.UniqueProcess = 0;
  cid.UniqueThread = (HANDLE)thread;
  status = NtOpenThread( &handle, THREAD_QUERY_INFORMATION|SYNCHRONIZE, NULL, &cid );
  if (!status)
  {
    NtWaitForMultipleObjects( 1, &handle, FALSE, FALSE, NULL );
    status = NtQueryInformationThread( handle, ThreadBasicInformation, &info, sizeof(info), NULL );
    NtClose( handle );
    if (!status) *value_ptr = UlongToPtr(info.ExitStatus);
  }
  if (status) return EINVAL; /* FIXME: make this more correctly match windows errors */
  return 0;
}
Exemple #13
0
static
void
TestRecursiveInterThreadMessages(
    _In_ BOOL KillThread1,
    _In_ BOOL KillThread2)
{
    PVOID Parameter;
    HANDLE Handles[2];
    BOOL Ret;
    DWORD ExitCode;

    Parameter = UlongToPtr((KillThread1 ? KILL_THREAD1_FLAG : 0) |
                           (KillThread2 ? KILL_THREAD2_FLAG : 0));
    hThread1 = CreateThread(NULL, 0, Thread1, Parameter, CREATE_SUSPENDED, &dwThread1);
    hThread2 = CreateThread(NULL, 0, Thread2, Parameter, CREATE_SUSPENDED, &dwThread2);

    ResumeThread(hThread1);

    Handles[0] = hThread1;
    Handles[1] = hThread2;
    WaitForMultipleObjects(2, Handles, TRUE, INFINITE);

    Ret = GetExitCodeThread(hThread1, &ExitCode);
    ok(Ret == TRUE, "GetExitCodeThread failed with %lu\n", GetLastError());
    if (KillThread1)
        ok(ExitCode == 456, "Thread1 exit code is %lu\n", ExitCode);
    else
        ok(ExitCode == 6, "Thread1 exit code is %lu\n", ExitCode);

    Ret = GetExitCodeThread(hThread2, &ExitCode);
    ok(Ret == TRUE, "GetExitCodeThread failed with %lu\n", GetLastError());
    if (KillThread2)
        ok(ExitCode == 123, "Thread2 exit code is %lu\n", ExitCode);
    else
        ok(ExitCode == 7, "Thread2 exit code is %lu\n", ExitCode);

    CloseHandle(hThread2);
    CloseHandle(hThread1);

    //TRACE_CACHE();
}
Exemple #14
0
NTSTATUS
NTAPI
KdpPortInitialize(IN ULONG ComPortNumber,
                  IN ULONG ComPortBaudRate)
{
    NTSTATUS Status;

    KDDBGPRINT("KdpPortInitialize, Port = COM%ld\n", ComPortNumber);

    Status = CpInitialize(&KdDebugComPort,
                          UlongToPtr(BaseArray[ComPortNumber]),
                          ComPortBaudRate);
    if (!NT_SUCCESS(Status))
    {
        return STATUS_INVALID_PARAMETER;
    }
    else
    {
        KdComPortInUse = KdDebugComPort.Address;
        return STATUS_SUCCESS;
    }
}
Exemple #15
0
BOOL HookD3DFunction(DWORD dwRVA, PVOID pvStub)
{
	HMODULE hD3D9;
	PBYTE pbFuncAddress;
	DWORD dwOldProtect;
	BOOL bRet = FALSE;

	hD3D9 = GetModuleHandle("d3d9.dll");
	if(hD3D9)
	{
		pbFuncAddress = (PBYTE)UlongToPtr(PtrToUlong(hD3D9) + dwRVA);
		if(VirtualProtect(pbFuncAddress, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect))
		{
			if(memcmp(pbFuncAddress, "\x8B\xFF\x55\x8B\xEC", 5) == 0)
			{
				*pbFuncAddress = 0xE8;
				*((PDWORD)&pbFuncAddress[1]) = PtrToUlong(pvStub) - (PtrToUlong(pbFuncAddress) + 5);
				bRet = TRUE;
			}
			VirtualProtect(pbFuncAddress, 5, dwOldProtect, &dwOldProtect);
		}
	}
	return bRet;
}
Exemple #16
0
//-----------------------------------------------------------------------------
// Name: BackBufferFormatChanged
// Desc: Respond to a change of selected back buffer format by rebuilding
//       the depth/stencil format list, multisample type list, and vertex
//       processing type list.
//-----------------------------------------------------------------------------
void CD3DSettingsDialog::BackBufferFormatChanged( void )
{
    D3DDeviceInfo* pDeviceInfo = (D3DDeviceInfo*)ComboBoxSelected( IDC_DEVICE_COMBO );
    D3DFORMAT adapterFormat = (D3DFORMAT)PtrToUlong( ComboBoxSelected( IDC_ADAPTERFORMAT_COMBO ) );
    D3DFORMAT backBufferFormat = (D3DFORMAT)PtrToUlong( ComboBoxSelected( IDC_BACKBUFFERFORMAT_COMBO ) );
    if( pDeviceInfo == NULL )
        return;

    for( UINT idc = 0; idc < pDeviceInfo->pDeviceComboList->Count(); idc++ )
    {
        D3DDeviceCombo* pDeviceCombo = (D3DDeviceCombo*)pDeviceInfo->pDeviceComboList->GetPtr(idc);
        if (pDeviceCombo->IsWindowed == m_d3dSettings.IsWindowed &&
            pDeviceCombo->AdapterFormat == adapterFormat &&
            pDeviceCombo->BackBufferFormat == backBufferFormat)
        {
            if( m_d3dSettings.IsWindowed )
                m_d3dSettings.pWindowed_DeviceCombo = pDeviceCombo;
            else
                m_d3dSettings.pFullscreen_DeviceCombo = pDeviceCombo;

            ComboBoxClear( IDC_DEPTHSTENCILBUFFERFORMAT_COMBO );
            if( m_pEnumeration->AppUsesDepthBuffer )
            {
                for( UINT ifmt = 0; ifmt < pDeviceCombo->pDepthStencilFormatList->Count(); ifmt++ )
                {
                    D3DFORMAT fmt = *(D3DFORMAT*)pDeviceCombo->pDepthStencilFormatList->GetPtr(ifmt);
                    ComboBoxAdd( IDC_DEPTHSTENCILBUFFERFORMAT_COMBO, (void*)fmt, 
                        D3DUtil_D3DFormatToString(fmt) );
                    if( fmt == m_d3dSettings.DepthStencilBufferFormat() )
                        ComboBoxSelect( IDC_DEPTHSTENCILBUFFERFORMAT_COMBO, (void*)fmt );
                }
                if (!ComboBoxSomethingSelected( IDC_DEPTHSTENCILBUFFERFORMAT_COMBO ) && 
                    ComboBoxCount( IDC_DEPTHSTENCILBUFFERFORMAT_COMBO ) > 0)
                {
                    ComboBoxSelectIndex( IDC_DEPTHSTENCILBUFFERFORMAT_COMBO, 0 );
                }
            }
            else
            {
                EnableWindow( GetDlgItem( m_hDlg, IDC_DEPTHSTENCILBUFFERFORMAT_COMBO ), false );
                ComboBoxAdd( IDC_DEPTHSTENCILBUFFERFORMAT_COMBO, NULL, TEXT("(not used)") );
                ComboBoxSelectIndex( IDC_DEPTHSTENCILBUFFERFORMAT_COMBO, 0 );
            }

            ComboBoxClear( IDC_VERTEXPROCESSING_COMBO );
            for( UINT ivpt = 0; ivpt < pDeviceCombo->pVertexProcessingTypeList->Count(); ivpt++ )
            {
                VertexProcessingType vpt = *(VertexProcessingType*)pDeviceCombo->pVertexProcessingTypeList->GetPtr(ivpt);
                ComboBoxAdd( IDC_VERTEXPROCESSING_COMBO, (void*)vpt, VertexProcessingTypeToString(vpt) );
                if( vpt == m_d3dSettings.GetVertexProcessingType() )
                    ComboBoxSelect( IDC_VERTEXPROCESSING_COMBO, (void*)vpt );
            }
            if (!ComboBoxSomethingSelected( IDC_VERTEXPROCESSING_COMBO ) && 
                ComboBoxCount( IDC_VERTEXPROCESSING_COMBO ) > 0)
            {
                ComboBoxSelectIndex( IDC_VERTEXPROCESSING_COMBO, 0 );
            }

            ComboBoxClear( IDC_PRESENTINTERVAL_COMBO );
            for( UINT ipi = 0; ipi < pDeviceCombo->pPresentIntervalList->Count(); ipi++ )
            {
                UINT pi = *(UINT*)pDeviceCombo->pPresentIntervalList->GetPtr(ipi);
                ComboBoxAdd( IDC_PRESENTINTERVAL_COMBO, UlongToPtr( pi ), PresentIntervalToString(pi) );
                if( pi == m_d3dSettings.PresentInterval() )
                    ComboBoxSelect( IDC_PRESENTINTERVAL_COMBO, UlongToPtr( pi ) );
            }
            if (!ComboBoxSomethingSelected( IDC_PRESENTINTERVAL_COMBO ) && 
                ComboBoxCount( IDC_PRESENTINTERVAL_COMBO ) > 0)
            {
                ComboBoxSelectIndex( IDC_PRESENTINTERVAL_COMBO, 0 );
            }

            break;
        }
    }
}
Exemple #17
0
/*++
 * @name ExpCreateWorkerThread
 *
 *     The ExpCreateWorkerThread routine creates a new worker thread for the
 *     specified queue.
 **
 * @param QueueType
 *        Type of the queue to use for this thread. Valid values are:
 *          - DelayedWorkQueue
 *          - CriticalWorkQueue
 *          - HyperCriticalWorkQueue
 *
 * @param Dynamic
 *        Specifies whether or not this thread is a dynamic thread.
 *
 * @return None.
 *
 * @remarks HyperCritical work threads run at priority 7; Critical work threads
 *          run at priority 5, and delayed work threads run at priority 4.
 *
 *          This, worker threads cannot pre-empty a normal user-mode thread.
 *
 *--*/
VOID
NTAPI
ExpCreateWorkerThread(WORK_QUEUE_TYPE WorkQueueType,
                      IN BOOLEAN Dynamic)
{
    PETHREAD Thread;
    HANDLE hThread;
    ULONG Context;
    KPRIORITY Priority;

    /* Check if this is going to be a dynamic thread */
    Context = WorkQueueType;

    /* Add the dynamic mask */
    if (Dynamic) Context |= EX_DYNAMIC_WORK_THREAD;

    /* Create the System Thread */
    PsCreateSystemThread(&hThread,
                         THREAD_ALL_ACCESS,
                         NULL,
                         NULL,
                         NULL,
                         ExpWorkerThreadEntryPoint,
                         UlongToPtr(Context));

    /* If the thread is dynamic */
    if (Dynamic)
    {
        /* Increase the count */
        InterlockedIncrement(&ExWorkerQueue[WorkQueueType].DynamicThreadCount);
    }

    /* Set the priority */
    if (WorkQueueType == DelayedWorkQueue)
    {
        /* Priority == 4 */
        Priority = EX_DELAYED_QUEUE_PRIORITY_INCREMENT;
    }
    else if (WorkQueueType == CriticalWorkQueue)
    {
        /* Priority == 5 */
        Priority = EX_CRITICAL_QUEUE_PRIORITY_INCREMENT;
    }
    else
    {
        /* Priority == 7 */
        Priority = EX_HYPERCRITICAL_QUEUE_PRIORITY_INCREMENT;
    }

    /* Get the Thread */
    ObReferenceObjectByHandle(hThread,
                              THREAD_SET_INFORMATION,
                              PsThreadType,
                              KernelMode,
                              (PVOID*)&Thread,
                              NULL);

    /* Set the Priority */
    KeSetBasePriorityThread(&Thread->Tcb, Priority);

    /* Dereference and close handle */
    ObDereferenceObject(Thread);
    ObCloseHandle(hThread, KernelMode);
}
Exemple #18
0
NTSTATUS
NTAPI
RtlAddAttributeActionToRXact(
    PRXACT_CONTEXT Context,
    ULONG ActionType,
    PUNICODE_STRING KeyName,
    HANDLE KeyHandle,
    PUNICODE_STRING ValueName,
    ULONG ValueType,
    PVOID ValueData,
    ULONG ValueDataSize)
{
    ULONG ActionSize;
    ULONG RequiredSize;
    ULONG BufferSize;
    ULONG CurrentOffset;
    PRXACT_DATA NewData;
    PRXACT_ACTION Action;

    /* Validate ActionType parameter */
    if ((ActionType != RXactDeleteKey) && (ActionType != RXactSetValueKey))
    {
        return STATUS_INVALID_PARAMETER;
    }

    /* Calculate the size of the new action record */
    ActionSize = ALIGN_UP_BY(ValueName->Length, sizeof(ULONG)) +
                 ALIGN_UP_BY(ValueDataSize, sizeof(ULONG)) +
                 ALIGN_UP_BY(KeyName->Length, sizeof(ULONG)) +
                 ALIGN_UP_BY(sizeof(RXACT_ACTION), sizeof(ULONG));

    /* Calculate the new buffer size we need */
    RequiredSize = ActionSize + Context->Data->CurrentSize;

    /* Check for integer overflow */
    if (RequiredSize < ActionSize)
    {
        return STATUS_NO_MEMORY;
    }

    /* Check if the buffer is large enough */
    BufferSize = Context->Data->BufferSize;
    if (RequiredSize > BufferSize)
    {
        /* Increase by a factor of 2, until it is large enough */
        while (BufferSize < RequiredSize)
        {
            BufferSize *= 2;
        }

        /* Allocate a new buffer from the heap */
        NewData = RtlAllocateHeap(RtlGetProcessHeap(), 0, BufferSize);
        if (NewData == NULL)
        {
            return STATUS_NO_MEMORY;
        }

        /* Copy the old buffer to the new one */
        RtlCopyMemory(NewData, Context->Data, Context->Data->CurrentSize);

        /* Free the old buffer and use the new one */
        RtlFreeHeap(RtlGetProcessHeap(), 0, Context->Data);
        Context->Data = NewData;
        NewData->BufferSize = BufferSize;
    }

    /* Get the next action record */
    Action = (RXACT_ACTION *)((PUCHAR)Context->Data + Context->Data->CurrentSize);

    /* Fill in the fields */
    Action->Size = ActionSize;
    Action->Type = ActionType;
    Action->KeyName = *KeyName;
    Action->ValueName = *ValueName;
    Action->ValueType = ValueType;
    Action->ValueDataSize = ValueDataSize;
    Action->KeyHandle = KeyHandle;

    /* Copy the key name (and convert the pointer to a buffer offset) */
    CurrentOffset = Context->Data->CurrentSize + sizeof(RXACT_ACTION);
    Action->KeyName.Buffer = UlongToPtr(CurrentOffset);
    RtlCopyMemory((PUCHAR)Context->Data + CurrentOffset,
                  KeyName->Buffer,
                  KeyName->Length);

    /* Copy the value name (and convert the pointer to a buffer offset) */
    CurrentOffset += ALIGN_UP_BY(KeyName->Length, sizeof(ULONG));
    Action->ValueName.Buffer = UlongToPtr(CurrentOffset);
    RtlCopyMemory((PUCHAR)Context->Data + CurrentOffset,
                  ValueName->Buffer,
                  ValueName->Length);

    /* Update the offset */
    CurrentOffset += ALIGN_UP_BY(ValueName->Length, sizeof(ULONG));

    /* Is this a set action? */
    if (ActionType == RXactSetValueKey)
    {
        /* Copy the key value data as well */
        Action->ValueData = UlongToPtr(CurrentOffset);
        RtlCopyMemory((PUCHAR)Context->Data + CurrentOffset,
                      ValueData,
                      ValueDataSize);
        CurrentOffset += ALIGN_UP_BY(ValueDataSize, sizeof(ULONG));
    }

    /* Update data site and action count */
    Context->Data->CurrentSize = CurrentOffset;
    Context->Data->ActionCount++;

    return STATUS_SUCCESS;
}
Exemple #19
0
static void test_foregroundwindow(void)
{
    HWND hwnd, hwnd_test, partners[2], hwnds[2];
    HDESK hdesks[2];
    int thread_desk_id, input_desk_id, hwnd_id;
    WNDCLASSA wclass;
    wnd_param param;
    DWORD ret, timeout, timeout_old;
    char win_text[1024];

#define DESKTOPS 2

    memset( &wclass, 0, sizeof(wclass) );
    wclass.lpszClassName = "test_class";
    wclass.lpfnWndProc   = WndProc;
    RegisterClassA(&wclass);
    param.wnd_name = "win_name";

    hdesks[0] = GetThreadDesktop(GetCurrentThreadId());
    ok(hdesks[0] != NULL, "OpenDesktop failed!\n");
    SetLastError(0xdeadbeef);
    hdesks[1] = CreateDesktopA("desk2", NULL, NULL, 0, DESKTOP_ALL_ACCESS, NULL);
    ret = GetLastError();
    ok(hdesks[1] != NULL || ret == ERROR_ACCESS_DENIED, "CreateDesktop failed (%u)\n", ret);
    if(!hdesks[1])
    {
        win_skip("Not enough privileges for CreateDesktop\n");
        return;
    }

    ret = SystemParametersInfoA(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &timeout_old, 0);
    if(!ret)
    {
        win_skip("Skip tests on NT4\n");
        CloseDesktop(hdesks[1]);
        return;
    }
    trace("old timeout %d\n", timeout_old);
    timeout = 0;
    ret = SystemParametersInfoA(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);
    ok(ret, "set foreground lock timeout failed!\n");
    ret = SystemParametersInfoA(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &timeout, 0);
    ok(ret, "get foreground lock timeout failed!\n");
    ok(timeout == 0, "unexpected timeout %d\n", timeout);

    for (thread_desk_id = 0; thread_desk_id < DESKTOPS; thread_desk_id++)
    {
        param.hdesk = hdesks[thread_desk_id];
        param.hevent = CreateEventA(NULL, TRUE, FALSE, NULL);
        CreateThread(NULL, 0, create_window, &param, 0, NULL);
        ret = WaitForSingleObject(param.hevent, INFINITE);
        ok(ret == WAIT_OBJECT_0, "wait failed!\n");
        hwnds[thread_desk_id] = param.hwnd;
    }

    for (thread_desk_id = 0; thread_desk_id < DESKTOPS; thread_desk_id++)
    {
        param.hdesk = hdesks[thread_desk_id];
        param.hevent = CreateEventA(NULL, TRUE, FALSE, NULL);
        CreateThread(NULL, 0, create_window, &param, 0, NULL);
        ret = WaitForSingleObject(param.hevent, INFINITE);
        ok(ret == WAIT_OBJECT_0, "wait failed!\n");
        partners[thread_desk_id] = param.hwnd;
    }

    trace("hwnd0 %p hwnd1 %p partner0 %p partner1 %p\n", hwnds[0], hwnds[1], partners[0], partners[1]);

    for (hwnd_id = 0; hwnd_id < DESKTOPS; hwnd_id++)
        for (thread_desk_id = 0; thread_desk_id < DESKTOPS; thread_desk_id++)
            for (input_desk_id = 0; input_desk_id < DESKTOPS; input_desk_id++)
            {
                trace("testing thread_desk %d input_desk %d hwnd %d\n",
                        thread_desk_id, input_desk_id, hwnd_id);
                hwnd_test = hwnds[hwnd_id];
                ret = SetThreadDesktop(hdesks[thread_desk_id]);
                ok(ret, "set thread desktop failed!\n");
                ret = SwitchDesktop(hdesks[input_desk_id]);
                ok(ret, "switch desktop failed!\n");
                set_foreground(partners[0]);
                set_foreground(partners[1]);
                hwnd = GetForegroundWindow();
                ok(hwnd != hwnd_test, "unexpected foreground window %p\n", hwnd);
                ret = set_foreground(hwnd_test);
                hwnd = GetForegroundWindow();
                GetWindowTextA(hwnd, win_text, 1024);
                trace("hwnd %p name %s\n", hwnd, win_text);
                if (input_desk_id == hwnd_id)
                {
                    if (input_desk_id == thread_desk_id)
                    {
                        ok(ret, "SetForegroundWindow failed!\n");
                        ok(hwnd == hwnd_test , "unexpected foreground window %p\n", hwnd);
                    }
                    else
                    {
                        todo_wine ok(ret, "SetForegroundWindow failed!\n");
                        todo_wine ok(hwnd == 0, "unexpected foreground window %p\n", hwnd);
                    }
                }
                else
                {
                    if (input_desk_id == thread_desk_id)
                    {
                        ok(!ret, "SetForegroundWindow should fail!\n");
                        ok(hwnd == partners[input_desk_id] , "unexpected foreground window %p\n", hwnd);
                    }
                    else
                    {
                        todo_wine ok(!ret, "SetForegroundWindow should fail!\n");
                        todo_wine ok(hwnd == 0, "unexpected foreground window %p\n", hwnd);
                    }
                }
            }

    /* Clean up */

    for (thread_desk_id = DESKTOPS - 1; thread_desk_id >= 0; thread_desk_id--)
    {
        ret = SetThreadDesktop(hdesks[thread_desk_id]);
        ok(ret, "set thread desktop failed!\n");
        SendMessageA(hwnds[thread_desk_id], WM_DESTROY, 0, 0);
        SendMessageA(partners[thread_desk_id], WM_DESTROY, 0, 0);
    }

    ret = SwitchDesktop(hdesks[0]);
    ok(ret, "switch desktop failed!\n");
    CloseDesktop(hdesks[1]);

    ret = SystemParametersInfoA(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, UlongToPtr(timeout_old), SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);
    ok(ret, "set foreground lock timeout failed!\n");
    ret = SystemParametersInfoA(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &timeout, 0);
    ok(ret, "get foreground lock timeout failed!\n");
    ok(timeout == timeout_old, "unexpected timeout %d\n", timeout);
}
Exemple #20
0
BOOLEAN
NTAPI
KdPortInitializeEx(
    IN PCPPORT PortInformation,
    IN ULONG ComPortNumber)
{
    NTSTATUS Status;
    CHAR buffer[80];

#if 0 // Deactivated because never used in fact (was in KdPortInitialize but we use KdPortInitializeEx)
    /*
     * Find the port if needed
     */
    SIZE_T i;

    if (!PortInitialized)
    {
        DefaultPort.BaudRate = PortInformation->BaudRate;

        if (ComPortNumber == 0)
        {
            /*
             * Start enumerating COM ports from the last one to the first one,
             * and break when we find a valid port.
             * If we reach the first element of the list, the invalid COM port,
             * then it means that no valid port was found.
             */
            for (i = sizeof(BaseArray) / sizeof(BaseArray[0]) - 1; i > 0; i--)
            {
                if (CpDoesPortExist(UlongToPtr(BaseArray[i])))
                {
                    PortInformation->Address = DefaultPort.Address = BaseArray[i];
                    ComPortNumber = (ULONG)i;
                    break;
                }
            }
            if (ComPortNumber == 0)
            {
                sprintf(buffer,
                        "\nKernel Debugger: No COM port found!\n\n");
                HalDisplayString(buffer);
                return FALSE;
            }
        }

        PortInitialized = TRUE;
    }
#endif

    /*
     * Initialize the port
     */
    Status = CpInitialize(PortInformation,
                          (ComPortNumber == 0 ? PortInformation->Address
                                              : UlongToPtr(BaseArray[ComPortNumber])),
                          (PortInformation->BaudRate == 0 ? DEFAULT_BAUD_RATE
                                                          : PortInformation->BaudRate));
    if (!NT_SUCCESS(Status))
    {
        sprintf(buffer,
                "\nKernel Debugger: Serial port not found!\n\n");
        HalDisplayString(buffer);
        return FALSE;
    }
    else
    {
#ifndef NDEBUG
        /* Print message to blue screen */
        sprintf(buffer,
                "\nKernel Debugger: Serial port found: COM%ld (Port 0x%lx) BaudRate %ld\n\n",
                ComPortNumber,
                PortInformation->Address,
                PortInformation->BaudRate);
        HalDisplayString(buffer);
#endif /* NDEBUG */

#if 0
        /* Set global info */
        KdComPortInUse = DefaultPort.Address;
#endif
        return TRUE;
    }
}
Exemple #21
0
HRESULT protocol_continue(Protocol *protocol, PROTOCOLDATA *data)
{
    BOOL is_start;
    HRESULT hres;

    is_start = !data || data->pData == UlongToPtr(BINDSTATUS_DOWNLOADINGDATA);

    if(!protocol->request) {
        WARN("Expected request to be non-NULL\n");
        return S_OK;
    }

    if(!protocol->protocol_sink) {
        WARN("Expected IInternetProtocolSink pointer to be non-NULL\n");
        return S_OK;
    }

    if(protocol->flags & FLAG_ERROR) {
        protocol->flags &= ~FLAG_ERROR;
        protocol->vtbl->on_error(protocol, PtrToUlong(data->pData));
        return S_OK;
    }

    if(protocol->post_stream)
        return write_post_stream(protocol);

    if(is_start) {
        hres = start_downloading(protocol);
        if(FAILED(hres))
            return S_OK;
    }

    if(!data || data->pData >= UlongToPtr(BINDSTATUS_DOWNLOADINGDATA)) {
        if(!protocol->available_bytes) {
            if(protocol->query_available) {
                protocol->available_bytes = protocol->query_available;
            }else {
                BOOL res;

                /* InternetQueryDataAvailable may immediately fork and perform its asynchronous
                 * read, so clear the flag _before_ calling so it does not incorrectly get cleared
                 * after the status callback is called */
                protocol->flags &= ~FLAG_REQUEST_COMPLETE;
                res = InternetQueryDataAvailable(protocol->request, &protocol->query_available, 0, 0);
                if(res) {
                    TRACE("available %u bytes\n", protocol->query_available);
                    if(!protocol->query_available) {
                        if(is_start) {
                            TRACE("empty file\n");
                            all_data_read(protocol);
                        }else {
                            WARN("unexpected end of file?\n");
                            report_result(protocol, INET_E_DOWNLOAD_FAILURE);
                        }
                        return S_OK;
                    }
                    protocol->available_bytes = protocol->query_available;
                }else if(GetLastError() != ERROR_IO_PENDING) {
                    protocol->flags |= FLAG_REQUEST_COMPLETE;
                    WARN("InternetQueryDataAvailable failed: %d\n", GetLastError());
                    report_result(protocol, INET_E_DATA_NOT_AVAILABLE);
                    return S_OK;
                }
            }

            protocol->flags |= FLAG_REQUEST_COMPLETE;
        }

        report_data(protocol);
    }

    return S_OK;
}
Exemple #22
0
/*
 * @implemented
 */
NTSTATUS
NTAPI
PsSetContextThread(IN PETHREAD Thread,
                   IN OUT PCONTEXT ThreadContext,
                   IN KPROCESSOR_MODE PreviousMode)
{
    GET_SET_CTX_CONTEXT GetSetContext;
    ULONG Size = 0, Flags = 0;
    NTSTATUS Status;

    /* Enter SEH */
    _SEH2_TRY
    {
        /* Set default length */
        Size = sizeof(CONTEXT);

        /* Read the flags */
        Flags = ProbeForReadUlong(&ThreadContext->ContextFlags);

#ifdef _M_IX86
        /* Check if the caller wanted extended registers */
        if ((Flags & CONTEXT_EXTENDED_REGISTERS) !=
            CONTEXT_EXTENDED_REGISTERS)
        {
            /* Cut them out of the size */
            Size = FIELD_OFFSET(CONTEXT, ExtendedRegisters);
        }
#endif

        /* Check if we came from user mode */
        if (PreviousMode != KernelMode)
        {
            /* Probe the context */
            ProbeForRead(ThreadContext, Size, sizeof(ULONG));
        }

        /* Copy the context */
        RtlCopyMemory(&GetSetContext.Context, ThreadContext, Size);
    }
    _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
    {
        /* Return the exception code */
        _SEH2_YIELD(return _SEH2_GetExceptionCode());
    }
    _SEH2_END;

    /* Initialize the wait event */
    KeInitializeEvent(&GetSetContext.Event, NotificationEvent, FALSE);

    /* Set the flags and previous mode */
    GetSetContext.Context.ContextFlags = Flags;
    GetSetContext.Mode = PreviousMode;

    /* Check if we're running in the same thread */
    if (Thread == PsGetCurrentThread())
    {
        /* Setup APC parameters manually */
        GetSetContext.Apc.SystemArgument1 = UlongToPtr(1);
        GetSetContext.Apc.SystemArgument2 = Thread;

        /* Enter a guarded region to simulate APC_LEVEL */
        KeEnterGuardedRegion();

        /* Manually call the APC */
        PspGetOrSetContextKernelRoutine(&GetSetContext.Apc,
                                        NULL,
                                        NULL,
                                        &GetSetContext.Apc.SystemArgument1,
                                        &GetSetContext.Apc.SystemArgument2);

        /* Leave the guarded region */
        KeLeaveGuardedRegion();

        /* We are done */
        Status = STATUS_SUCCESS;
    }
    else
    {
        /* Initialize the APC */
        KeInitializeApc(&GetSetContext.Apc,
                        &Thread->Tcb,
                        OriginalApcEnvironment,
                        PspGetOrSetContextKernelRoutine,
                        NULL,
                        NULL,
                        KernelMode,
                        NULL);

        /* Queue it as a Get APC */
        if (!KeInsertQueueApc(&GetSetContext.Apc, UlongToPtr(1), Thread, 2))
        {
            /* It was already queued, so fail */
            Status = STATUS_UNSUCCESSFUL;
        }
        else
        {
            /* Wait for the APC to complete */
            Status = KeWaitForSingleObject(&GetSetContext.Event,
                                           0,
                                           KernelMode,
                                           FALSE,
                                           NULL);
        }
    }

    /* Return status */
    return Status;
}
Exemple #23
0
void MemMgr_OnListAdd (PMEMCHUNK pCopy)
{
   HWND hList = GetDlgItem (l.hManager, IDC_LIST);

   TCHAR szTime[256];
   FormatTime (szTime, pCopy->dwTick);

   TCHAR szFlags[256];
   LPTSTR pszFlags = szFlags;
   *pszFlags++ = (pCopy->fCPP) ? TEXT('C') : TEXT(' ');
   *pszFlags++ = TEXT(' ');
   *pszFlags++ = (pCopy->fFreed) ? TEXT('F') : TEXT(' ');
   *pszFlags++ = 0;

   TCHAR szExpr[256];
   lstrcpy (szExpr, (pCopy->pszExpr) ? pCopy->pszExpr : TEXT("unknown"));

   LPTSTR pszFile = pCopy->pszFile;
   for (LPTSTR psz = pCopy->pszFile; *psz; ++psz)
      {
      if ((*psz == TEXT(':')) || (*psz == TEXT('\\')))
         pszFile = &psz[1];
      }
   TCHAR szLocation[256];
   if (!pszFile || !pCopy->dwLine)
      lstrcpy (szLocation, TEXT("unknown"));
   else
      wsprintf (szLocation, TEXT("%s, %ld"), pszFile, pCopy->dwLine);

   TCHAR szBytes[256];
   FormatBytes (szBytes, (double)pCopy->cbData);

   TCHAR szAddress[256];
   wsprintf (szAddress, TEXT("0x%08p"), pCopy->pData);

   LPTSTR pszKey = NULL;
   switch (lr.iColSort)
      {
      case 0:  pszKey = (LPTSTR)UlongToPtr(pCopy->dwTick);  break;
      case 1:  pszKey = (LPTSTR)szFlags;        break;
      case 2:  pszKey = (LPTSTR)szExpr;         break;
      case 3:  pszKey = (LPTSTR)szLocation;     break;
      case 4:  pszKey = (LPTSTR)pCopy->cbData;  break;
      case 5:  pszKey = (LPTSTR)pCopy->pData;   break;
      }

   LV_ITEM Item;
   memset (&Item, 0x00, sizeof(Item));
   Item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_STATE | LVIF_IMAGE;
   Item.iItem = MemMgr_PickListInsertionPoint (hList, pszKey);
   Item.iSubItem = 0;
   Item.cchTextMax = 256;
   Item.lParam = (LPARAM)pCopy->pData;

   Item.pszText = szTime;
   DWORD iItem = ListView_InsertItem (hList, &Item);
   ListView_SetItemText (hList, iItem, 1, szFlags);
   ListView_SetItemText (hList, iItem, 2, szExpr);
   ListView_SetItemText (hList, iItem, 3, szLocation);
   ListView_SetItemText (hList, iItem, 4, szBytes);
   ListView_SetItemText (hList, iItem, 5, szAddress);

   delete pCopy;
}
Exemple #24
0
void test_CShellMenu_params()
{
    HRESULT hResult;
    IShellMenu* shellMenu;
    IDockingWindow* dockingMenu;
    IObjectWithSite* menuWithSite;

    IShellMenuCallback *psmc;
    UINT uId;
    UINT uIdAncestor;
    DWORD dwFlags;
    HWND hwndToolbar;
    HMENU hmenu;
    HWND hwndOwner;
    DWORD menuFlagss;
    IShellFolder *shellFolder;
    
    if (!CreateCShellMenu(&shellMenu, &dockingMenu, &menuWithSite))
    {
        skip("failed to create CShellMenuObject\n");
        return;
    }

    hResult = shellMenu->Initialize(NULL, 11, 22, 0xdeadbeef);
    test_S_OK(hResult, "Initialize failed");

    hResult = shellMenu->GetMenuInfo(&psmc, &uId, &uIdAncestor, &dwFlags);
    test_S_OK(hResult, "GetMenuInfo failed");
    ok (psmc == NULL, "wrong psmc\n");
    ok (uId == 11, "wrong uid\n");
    ok (uIdAncestor == 22, "wrong uIdAncestor\n");
    ok (dwFlags == 0xdeadbeef, "wrong dwFlags\n");

    hResult = shellMenu->Initialize(NULL, 0, ANCESTORDEFAULT, SMINIT_TOPLEVEL|SMINIT_VERTICAL);
    test_S_OK(hResult, "Initialize failed");

    hResult = dockingMenu->GetWindow(&hwndToolbar);
    test_HRES(hResult, E_FAIL, "GetWindow should fail");

    hResult = shellMenu->GetMenu(&hmenu, &hwndOwner, &menuFlagss);  
    test_HRES(hResult, E_FAIL, "GetMenu should fail");

    hmenu = CreatePopupMenu();
    hResult = shellMenu->SetMenu(hmenu, NULL, 0);
    test_S_OK(hResult, "SetMenu failed");

    hwndToolbar = (HWND)UlongToPtr(0xdeadbeef);
    hResult = dockingMenu->GetWindow(&hwndToolbar);
    test_S_OK(hResult, "GetWindow failed");
    ok (hwndToolbar == NULL, "Expected NULL window\n");

    hResult = shellMenu->SetMenu(NULL, NULL, 0);
    test_S_OK(hResult, "SetMenu failed");

    hResult = shellMenu->GetMenu(&hmenu, &hwndOwner, &menuFlagss);  
    test_S_OK(hResult, "GetMenu failed");
    ok (hmenu == NULL, "Got a menu\n");

    hResult = dockingMenu->GetWindow(&hwndToolbar);
    test_S_OK(hResult, "GetWindow failed");

    hResult = SHGetDesktopFolder(&shellFolder);
    test_S_OK(hResult, "SHGetDesktopFolder failed");

    hResult = shellMenu->SetShellFolder(shellFolder, NULL, 0, 0);
    test_S_OK(hResult, "SetShellFolder failed");
 
    hResult = shellMenu->SetShellFolder(NULL, NULL, 0, 0);
    test_HRES(hResult, E_INVALIDARG, "SetShellFolder should fail");

    hwndToolbar = (HWND)UlongToHandle(0xdeadbeef);
    hResult = dockingMenu->GetWindow(&hwndToolbar);
    test_S_OK(hResult, "GetWindow failed");
    ok (hwndToolbar == NULL, "Expected NULL window\n");

    hResult = dockingMenu->ShowDW(TRUE);
    test_HRES(hResult, S_FALSE, "ShowDW should fail");

    menuWithSite->Release();
    dockingMenu->Release();
    shellMenu->Release();
}
Exemple #25
0
VOID
FASTCALL
KiTimerListExpire(IN PLIST_ENTRY ExpiredListHead,
                  IN KIRQL OldIrql)
{
    ULARGE_INTEGER SystemTime;
    LARGE_INTEGER Interval;
    LONG i;
    ULONG DpcCalls = 0;
    PKTIMER Timer;
    PKDPC TimerDpc;
    ULONG Period;
    DPC_QUEUE_ENTRY DpcEntry[MAX_TIMER_DPCS];
#ifdef CONFIG_SMP
    PKPRCB Prcb = KeGetCurrentPrcb();
#endif

    /* Query system */
    KeQuerySystemTime((PLARGE_INTEGER)&SystemTime);
    
    /* Loop expired list */
    while (ExpiredListHead->Flink != ExpiredListHead)
    {
        /* Get the current timer */
        Timer = CONTAINING_RECORD(ExpiredListHead->Flink, KTIMER, TimerListEntry);
        
        /* Remove it */
        RemoveEntryList(&Timer->TimerListEntry);
        
        /* Not inserted */
        Timer->Header.Inserted = FALSE;
        
        /* Signal it */
        Timer->Header.SignalState = 1;
        
        /* Get the DPC and period */
        TimerDpc = Timer->Dpc;
        Period = Timer->Period;
        
        /* Check if there's any waiters */
        if (!IsListEmpty(&Timer->Header.WaitListHead))
        {
            /* Check the type of event */
            if (Timer->Header.Type == TimerNotificationObject)
            {
                /* Unwait the thread */
                KxUnwaitThread(&Timer->Header, IO_NO_INCREMENT);
            }
            else
            {
                /* Otherwise unwait the thread and signal the timer */
                KxUnwaitThreadForEvent((PKEVENT)Timer, IO_NO_INCREMENT);
            }
        }
        
        /* Check if we have a period */
        if (Period)
        {
            /* Calculate the interval and insert the timer */
            Interval.QuadPart = Int32x32To64(Period, -10000);
            while (!KiInsertTreeTimer(Timer, Interval));
        }

        /* Check if we have a DPC */
        if (TimerDpc)
        {
#ifdef CONFIG_SMP
            /* 
             * If the DPC is targeted to another processor,
             * then insert it into that processor's DPC queue
             * instead of delivering it now.
             * If the DPC is a threaded DPC, and the current CPU
             * has threaded DPCs enabled (KiExecuteDpc is actively parsing DPCs),
             * then also insert it into the DPC queue for threaded delivery,
             * instead of doing it here.
             */
            if (((TimerDpc->Number >= MAXIMUM_PROCESSORS) &&
                ((TimerDpc->Number - MAXIMUM_PROCESSORS) != Prcb->Number)) ||
                ((TimerDpc->Type == ThreadedDpcObject) && (Prcb->ThreadDpcEnable)))
            {
                /* Queue it */
                KeInsertQueueDpc(TimerDpc,
                                 UlongToPtr(SystemTime.LowPart),
                                 UlongToPtr(SystemTime.HighPart));
            }
            else
#endif
            {
                /* Setup the DPC Entry */
                DpcEntry[DpcCalls].Dpc = TimerDpc;
                DpcEntry[DpcCalls].Routine = TimerDpc->DeferredRoutine;
                DpcEntry[DpcCalls].Context = TimerDpc->DeferredContext;
                DpcCalls++;
                ASSERT(DpcCalls < MAX_TIMER_DPCS);
            }
        }
    }
    
    /* Check if we still have DPC entries */
    if (DpcCalls)
    {
        /* Release the dispatcher while doing DPCs */
        KiReleaseDispatcherLock(DISPATCH_LEVEL);
        
        /* Start looping all DPC Entries */
        for (i = 0; DpcCalls; DpcCalls--, i++)
        {
            /* Call the DPC */
            DpcEntry[i].Routine(DpcEntry[i].Dpc,
                                DpcEntry[i].Context,
                                UlongToPtr(SystemTime.LowPart),
                                UlongToPtr(SystemTime.HighPart));
        }
        
        /* Lower IRQL */
        KeLowerIrql(OldIrql);
    }
    else
    {
        /* Unlock the dispatcher */
        KiReleaseDispatcherLock(OldIrql);
    }
}
Exemple #26
0
VOID
NTAPI
KiTimerExpiration(IN PKDPC Dpc,
                  IN PVOID DeferredContext,
                  IN PVOID SystemArgument1,
                  IN PVOID SystemArgument2)
{
    ULARGE_INTEGER SystemTime, InterruptTime;
    LARGE_INTEGER Interval;
    LONG Limit, Index, i;
    ULONG Timers, ActiveTimers, DpcCalls;
    PLIST_ENTRY ListHead, NextEntry;
    KIRQL OldIrql;
    PKTIMER Timer;
    PKDPC TimerDpc;
    ULONG Period;
    DPC_QUEUE_ENTRY DpcEntry[MAX_TIMER_DPCS];
    PKSPIN_LOCK_QUEUE LockQueue;
#ifdef CONFIG_SMP
    PKPRCB Prcb = KeGetCurrentPrcb();
#endif

    /* Disable interrupts */
    _disable();

    /* Query system and interrupt time */
    KeQuerySystemTime((PLARGE_INTEGER)&SystemTime);
    InterruptTime.QuadPart = KeQueryInterruptTime();
    Limit = KeTickCount.LowPart;

    /* Bring interrupts back */
    _enable();

    /* Get the index of the timer and normalize it */
    Index = PtrToLong(SystemArgument1);
    if ((Limit - Index) >= TIMER_TABLE_SIZE)
    {
        /* Normalize it */
        Limit = Index + TIMER_TABLE_SIZE - 1;
    }

    /* Setup index and actual limit */
    Index--;
    Limit &= (TIMER_TABLE_SIZE - 1);

    /* Setup accounting data */
    DpcCalls = 0;
    Timers = 24;
    ActiveTimers = 4;

    /* Lock the Database and Raise IRQL */
    OldIrql = KiAcquireDispatcherLock();

    /* Start expiration loop */
    do
    {
        /* Get the current index */
        Index = (Index + 1) & (TIMER_TABLE_SIZE - 1);

        /* Get list pointers and loop the list */
        ListHead = &KiTimerTableListHead[Index].Entry;
        while (ListHead != ListHead->Flink)
        {
            /* Lock the timer and go to the next entry */
            LockQueue = KiAcquireTimerLock(Index);
            NextEntry = ListHead->Flink;

            /* Get the current timer and check its due time */
            Timers--;
            Timer = CONTAINING_RECORD(NextEntry, KTIMER, TimerListEntry);
            if ((NextEntry != ListHead) &&
                (Timer->DueTime.QuadPart <= InterruptTime.QuadPart))
            {
                /* It's expired, remove it */
                ActiveTimers--;
                KiRemoveEntryTimer(Timer);

                /* Make it non-inserted, unlock it, and signal it */
                Timer->Header.Inserted = FALSE;
                KiReleaseTimerLock(LockQueue);
                Timer->Header.SignalState = 1;

                /* Get the DPC and period */
                TimerDpc = Timer->Dpc;
                Period = Timer->Period;

                /* Check if there's any waiters */
                if (!IsListEmpty(&Timer->Header.WaitListHead))
                {
                    /* Check the type of event */
                    if (Timer->Header.Type == TimerNotificationObject)
                    {
                        /* Unwait the thread */
                        KxUnwaitThread(&Timer->Header, IO_NO_INCREMENT);
                    }
                    else
                    {
                        /* Otherwise unwait the thread and signal the timer */
                        KxUnwaitThreadForEvent((PKEVENT)Timer, IO_NO_INCREMENT);
                    }
                }

                /* Check if we have a period */
                if (Period)
                {
                    /* Calculate the interval and insert the timer */
                    Interval.QuadPart = Int32x32To64(Period, -10000);
                    while (!KiInsertTreeTimer(Timer, Interval));
                }

                /* Check if we have a DPC */
                if (TimerDpc)
                {
#ifdef CONFIG_SMP
                    /* 
                     * If the DPC is targeted to another processor,
                     * then insert it into that processor's DPC queue
                     * instead of delivering it now.
                     * If the DPC is a threaded DPC, and the current CPU
                     * has threaded DPCs enabled (KiExecuteDpc is actively parsing DPCs),
                     * then also insert it into the DPC queue for threaded delivery,
                     * instead of doing it here.
                     */
                    if (((TimerDpc->Number >= MAXIMUM_PROCESSORS) &&
                        ((TimerDpc->Number - MAXIMUM_PROCESSORS) != Prcb->Number)) ||
                        ((TimerDpc->Type == ThreadedDpcObject) && (Prcb->ThreadDpcEnable)))
                    {
                        /* Queue it */
                        KeInsertQueueDpc(TimerDpc,
                                         UlongToPtr(SystemTime.LowPart),
                                         UlongToPtr(SystemTime.HighPart));
                    }
                    else
#endif
                    {
                        /* Setup the DPC Entry */
                        DpcEntry[DpcCalls].Dpc = TimerDpc;
                        DpcEntry[DpcCalls].Routine = TimerDpc->DeferredRoutine;
                        DpcEntry[DpcCalls].Context = TimerDpc->DeferredContext;
                        DpcCalls++;
                        ASSERT(DpcCalls < MAX_TIMER_DPCS);
                    }
                }

                /* Check if we're done processing */
                if (!(ActiveTimers) || !(Timers))
                {
                    /* Release the dispatcher while doing DPCs */
                    KiReleaseDispatcherLock(DISPATCH_LEVEL);

                    /* Start looping all DPC Entries */
                    for (i = 0; DpcCalls; DpcCalls--, i++)
                    {
                        /* Call the DPC */
                        DpcEntry[i].Routine(DpcEntry[i].Dpc,
                                            DpcEntry[i].Context,
                                            UlongToPtr(SystemTime.LowPart),
                                            UlongToPtr(SystemTime.HighPart));
                    }

                    /* Reset accounting */
                    Timers = 24;
                    ActiveTimers = 4;

                    /* Lock the dispatcher database */
                    KiAcquireDispatcherLock();
                }
            }
            else
            {
                /* Check if the timer list is empty */
                if (NextEntry != ListHead)
                {
                    /* Sanity check */
                    ASSERT(KiTimerTableListHead[Index].Time.QuadPart <=
                           Timer->DueTime.QuadPart);

                    /* Update the time */
                    _disable();
                    KiTimerTableListHead[Index].Time.QuadPart =
                        Timer->DueTime.QuadPart;
                    _enable();
                }

                /* Release the lock */
                KiReleaseTimerLock(LockQueue);

                /* Check if we've scanned all the timers we could */
                if (!Timers)
                {
                    /* Release the dispatcher while doing DPCs */
                    KiReleaseDispatcherLock(DISPATCH_LEVEL);

                    /* Start looping all DPC Entries */
                    for (i = 0; DpcCalls; DpcCalls--, i++)
                    {
                        /* Call the DPC */
                        DpcEntry[i].Routine(DpcEntry[i].Dpc,
                                            DpcEntry[i].Context,
                                            UlongToPtr(SystemTime.LowPart),
                                            UlongToPtr(SystemTime.HighPart));
                    }

                    /* Reset accounting */
                    Timers = 24;
                    ActiveTimers = 4;

                    /* Lock the dispatcher database */
                    KiAcquireDispatcherLock();
                }

                /* Done looping */
                break;
            }
        }
    } while (Index != Limit);

    /* Verify the timer table, on debug builds */
    if (KeNumberProcessors == 1) KiCheckTimerTable(InterruptTime);

    /* Check if we still have DPC entries */
    if (DpcCalls)
    {
        /* Release the dispatcher while doing DPCs */
        KiReleaseDispatcherLock(DISPATCH_LEVEL);

        /* Start looping all DPC Entries */
        for (i = 0; DpcCalls; DpcCalls--, i++)
        {
            /* Call the DPC */
            DpcEntry[i].Routine(DpcEntry[i].Dpc,
                                DpcEntry[i].Context,
                                UlongToPtr(SystemTime.LowPart),
                                UlongToPtr(SystemTime.HighPart));
        }

        /* Lower IRQL if we need to */
        if (OldIrql != DISPATCH_LEVEL) KeLowerIrql(OldIrql);
    }
    else
    {
        /* Unlock the dispatcher */
        KiReleaseDispatcherLock(OldIrql);
    }
}
Exemple #27
0
INT_PTR CALLBACK PhpRunAsDlgProc(
    _In_ HWND hwndDlg,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam
    )
{
    PRUNAS_DIALOG_CONTEXT context;

    if (uMsg != WM_INITDIALOG)
    {
        context = (PRUNAS_DIALOG_CONTEXT)GetProp(hwndDlg, PhMakeContextAtom());
    }
    else
    {
        context = (PRUNAS_DIALOG_CONTEXT)lParam;
        SetProp(hwndDlg, PhMakeContextAtom(), (HANDLE)context);
    }

    if (!context)
        return FALSE;

    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            HWND typeComboBoxHandle = GetDlgItem(hwndDlg, IDC_TYPE);
            HWND userNameComboBoxHandle = GetDlgItem(hwndDlg, IDC_USERNAME);
            ULONG sessionId;

            PhCenterWindow(hwndDlg, GetParent(hwndDlg));

            if (SHAutoComplete_I)
            {
                SHAutoComplete_I(
                    GetDlgItem(hwndDlg, IDC_PROGRAM),
                    SHACF_AUTOAPPEND_FORCE_ON | SHACF_AUTOSUGGEST_FORCE_ON | SHACF_FILESYS_ONLY
                    );
            }

            ComboBox_AddString(typeComboBoxHandle, L"Batch");
            ComboBox_AddString(typeComboBoxHandle, L"Interactive");
            ComboBox_AddString(typeComboBoxHandle, L"Network");
            ComboBox_AddString(typeComboBoxHandle, L"New credentials");
            ComboBox_AddString(typeComboBoxHandle, L"Service");
            PhSelectComboBoxString(typeComboBoxHandle, L"Interactive", FALSE);

            ComboBox_AddString(userNameComboBoxHandle, L"NT AUTHORITY\\SYSTEM");
            ComboBox_AddString(userNameComboBoxHandle, L"NT AUTHORITY\\LOCAL SERVICE");
            ComboBox_AddString(userNameComboBoxHandle, L"NT AUTHORITY\\NETWORK SERVICE");

            PhpAddAccountsToComboBox(userNameComboBoxHandle);

            if (NT_SUCCESS(PhGetProcessSessionId(NtCurrentProcess(), &sessionId)))
                SetDlgItemInt(hwndDlg, IDC_SESSIONID, sessionId, FALSE);

            SetDlgItemText(hwndDlg, IDC_DESKTOP, L"WinSta0\\Default");
            SetDlgItemText(hwndDlg, IDC_PROGRAM, PhaGetStringSetting(L"RunAsProgram")->Buffer);

            if (!context->ProcessId)
            {
                SetDlgItemText(hwndDlg, IDC_USERNAME,
                    PH_AUTO_T(PH_STRING, PhGetStringSetting(L"RunAsUserName"))->Buffer);

                // Fire the user name changed event so we can fix the logon type.
                SendMessage(hwndDlg, WM_COMMAND, MAKEWPARAM(IDC_USERNAME, CBN_EDITCHANGE), 0);
            }
            else
            {
                HANDLE processHandle;
                HANDLE tokenHandle;
                PTOKEN_USER user;
                PPH_STRING userName;

                if (NT_SUCCESS(PhOpenProcess(
                    &processHandle,
                    ProcessQueryAccess,
                    context->ProcessId
                    )))
                {
                    if (NT_SUCCESS(PhOpenProcessToken(
                        processHandle,
                        TOKEN_QUERY,
                        &tokenHandle
                        )))
                    {
                        if (NT_SUCCESS(PhGetTokenUser(tokenHandle, &user)))
                        {
                            if (userName = PhGetSidFullName(user->User.Sid, TRUE, NULL))
                            {
                                SetDlgItemText(hwndDlg, IDC_USERNAME, userName->Buffer);
                                PhDereferenceObject(userName);
                            }

                            PhFree(user);
                        }

                        NtClose(tokenHandle);
                    }

                    NtClose(processHandle);
                }

                EnableWindow(GetDlgItem(hwndDlg, IDC_USERNAME), FALSE);
                EnableWindow(GetDlgItem(hwndDlg, IDC_PASSWORD), FALSE);
                EnableWindow(GetDlgItem(hwndDlg, IDC_TYPE), FALSE);
            }

            SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(hwndDlg, IDC_PROGRAM), TRUE);
            Edit_SetSel(GetDlgItem(hwndDlg, IDC_PROGRAM), 0, -1);

            //if (!PhGetOwnTokenAttributes().Elevated)
            //    SendMessage(GetDlgItem(hwndDlg, IDOK), BCM_SETSHIELD, 0, TRUE);

            if (!WINDOWS_HAS_UAC)
                ShowWindow(GetDlgItem(hwndDlg, IDC_TOGGLEELEVATION), SW_HIDE);
        }
        break;
    case WM_DESTROY:
        {
            if (context->DesktopList)
                PhDereferenceObject(context->DesktopList);

            RemoveProp(hwndDlg, PhMakeContextAtom());
        }
        break;
    case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
            case IDCANCEL:
                EndDialog(hwndDlg, IDCANCEL);
                break;
            case IDOK:
                {
                    NTSTATUS status;
                    PPH_STRING program;
                    PPH_STRING userName;
                    PPH_STRING password;
                    PPH_STRING logonTypeString;
                    ULONG logonType;
                    ULONG sessionId;
                    PPH_STRING desktopName;
                    BOOLEAN useLinkedToken;

                    program = PhaGetDlgItemText(hwndDlg, IDC_PROGRAM);
                    userName = PhaGetDlgItemText(hwndDlg, IDC_USERNAME);
                    logonTypeString = PhaGetDlgItemText(hwndDlg, IDC_TYPE);

                    // Fix up the user name if it doesn't have a domain.
                    if (PhFindCharInString(userName, 0, '\\') == -1)
                    {
                        PSID sid;
                        PPH_STRING newUserName;

                        if (NT_SUCCESS(PhLookupName(&userName->sr, &sid, NULL, NULL)))
                        {
                            if (newUserName = PH_AUTO(PhGetSidFullName(sid, TRUE, NULL)))
                                userName = newUserName;

                            PhFree(sid);
                        }
                    }

                    if (!IsServiceAccount(userName))
                        password = PhGetWindowText(GetDlgItem(hwndDlg, IDC_PASSWORD));
                    else
                        password = NULL;

                    sessionId = GetDlgItemInt(hwndDlg, IDC_SESSIONID, NULL, FALSE);
                    desktopName = PhaGetDlgItemText(hwndDlg, IDC_DESKTOP);

                    if (WINDOWS_HAS_UAC)
                        useLinkedToken = Button_GetCheck(GetDlgItem(hwndDlg, IDC_TOGGLEELEVATION)) == BST_CHECKED;
                    else
                        useLinkedToken = FALSE;

                    if (PhFindIntegerSiKeyValuePairs(
                        PhpLogonTypePairs,
                        sizeof(PhpLogonTypePairs),
                        logonTypeString->Buffer,
                        &logonType
                        ))
                    {
                        if (
                            logonType == LOGON32_LOGON_INTERACTIVE &&
                            !context->ProcessId &&
                            sessionId == NtCurrentPeb()->SessionId &&
                            !useLinkedToken
                            )
                        {
                            // We are eligible to load the user profile.
                            // This must be done here, not in the service, because
                            // we need to be in the target session.

                            PH_CREATE_PROCESS_AS_USER_INFO createInfo;
                            PPH_STRING domainPart;
                            PPH_STRING userPart;

                            PhpSplitUserName(userName->Buffer, &domainPart, &userPart);

                            memset(&createInfo, 0, sizeof(PH_CREATE_PROCESS_AS_USER_INFO));
                            createInfo.CommandLine = program->Buffer;
                            createInfo.UserName = userPart->Buffer;
                            createInfo.DomainName = domainPart->Buffer;
                            createInfo.Password = PhGetStringOrEmpty(password);

                            // Whenever we can, try not to set the desktop name; it breaks a lot of things.
                            // Note that on XP we must set it, otherwise the program doesn't display correctly.
                            if (WindowsVersion < WINDOWS_VISTA || (desktopName->Length != 0 && !PhEqualString2(desktopName, L"WinSta0\\Default", TRUE)))
                                createInfo.DesktopName = desktopName->Buffer;

                            PhSetDesktopWinStaAccess();

                            status = PhCreateProcessAsUser(
                                &createInfo,
                                PH_CREATE_PROCESS_WITH_PROFILE,
                                NULL,
                                NULL,
                                NULL
                                );

                            if (domainPart) PhDereferenceObject(domainPart);
                            if (userPart) PhDereferenceObject(userPart);
                        }
                        else
                        {
                            status = PhExecuteRunAsCommand2(
                                hwndDlg,
                                program->Buffer,
                                userName->Buffer,
                                PhGetStringOrEmpty(password),
                                logonType,
                                context->ProcessId,
                                sessionId,
                                desktopName->Buffer,
                                useLinkedToken
                                );
                        }
                    }
                    else
                    {
                        status = STATUS_INVALID_PARAMETER;
                    }

                    if (password)
                    {
                        RtlSecureZeroMemory(password->Buffer, password->Length);
                        PhDereferenceObject(password);
                    }

                    if (!NT_SUCCESS(status))
                    {
                        if (status != STATUS_CANCELLED)
                            PhShowStatus(hwndDlg, L"Unable to start the program", status, 0);
                    }
                    else if (status != STATUS_TIMEOUT)
                    {
                        PhSetStringSetting2(L"RunAsProgram", &program->sr);
                        PhSetStringSetting2(L"RunAsUserName", &userName->sr);
                        EndDialog(hwndDlg, IDOK);
                    }
                }
                break;
            case IDC_BROWSE:
                {
                    static PH_FILETYPE_FILTER filters[] =
                    {
                        { L"Programs (*.exe;*.pif;*.com;*.bat)", L"*.exe;*.pif;*.com;*.bat" },
                        { L"All files (*.*)", L"*.*" }
                    };
                    PVOID fileDialog;

                    fileDialog = PhCreateOpenFileDialog();
                    PhSetFileDialogFilter(fileDialog, filters, sizeof(filters) / sizeof(PH_FILETYPE_FILTER));
                    PhSetFileDialogFileName(fileDialog, PhaGetDlgItemText(hwndDlg, IDC_PROGRAM)->Buffer);

                    if (PhShowFileDialog(hwndDlg, fileDialog))
                    {
                        PPH_STRING fileName;

                        fileName = PhGetFileDialogFileName(fileDialog);
                        SetDlgItemText(hwndDlg, IDC_PROGRAM, fileName->Buffer);
                        PhDereferenceObject(fileName);
                    }

                    PhFreeFileDialog(fileDialog);
                }
                break;
            case IDC_USERNAME:
                {
                    PPH_STRING userName = NULL;

                    if (!context->ProcessId && HIWORD(wParam) == CBN_SELCHANGE)
                    {
                        userName = PH_AUTO(PhGetComboBoxString(GetDlgItem(hwndDlg, IDC_USERNAME), -1));
                    }
                    else if (!context->ProcessId && (
                        HIWORD(wParam) == CBN_EDITCHANGE ||
                        HIWORD(wParam) == CBN_CLOSEUP
                        ))
                    {
                        userName = PhaGetDlgItemText(hwndDlg, IDC_USERNAME);
                    }

                    if (userName)
                    {
                        if (IsServiceAccount(userName))
                        {
                            EnableWindow(GetDlgItem(hwndDlg, IDC_PASSWORD), FALSE);

                            // Hack for Windows XP
                            if (
                                PhEqualString2(userName, L"NT AUTHORITY\\SYSTEM", TRUE) &&
                                WindowsVersion <= WINDOWS_XP
                                )
                            {
                                PhSelectComboBoxString(GetDlgItem(hwndDlg, IDC_TYPE), L"New credentials", FALSE);
                            }
                            else
                            {
                                PhSelectComboBoxString(GetDlgItem(hwndDlg, IDC_TYPE), L"Service", FALSE);
                            }
                        }
                        else
                        {
                            EnableWindow(GetDlgItem(hwndDlg, IDC_PASSWORD), TRUE);
                            PhSelectComboBoxString(GetDlgItem(hwndDlg, IDC_TYPE), L"Interactive", FALSE);
                        }
                    }
                }
                break;
            case IDC_SESSIONS:
                {
                    PPH_EMENU sessionsMenu;
                    PSESSIONIDW sessions;
                    ULONG numberOfSessions;
                    ULONG i;
                    RECT buttonRect;
                    PPH_EMENU_ITEM selectedItem;

                    sessionsMenu = PhCreateEMenu();

                    if (WinStationEnumerateW(NULL, &sessions, &numberOfSessions))
                    {
                        for (i = 0; i < numberOfSessions; i++)
                        {
                            PPH_STRING menuString;
                            WINSTATIONINFORMATION winStationInfo;
                            ULONG returnLength;

                            if (!WinStationQueryInformationW(
                                NULL,
                                sessions[i].SessionId,
                                WinStationInformation,
                                &winStationInfo,
                                sizeof(WINSTATIONINFORMATION),
                                &returnLength
                                ))
                            {
                                winStationInfo.Domain[0] = 0;
                                winStationInfo.UserName[0] = 0;
                            }

                            if (
                                winStationInfo.UserName[0] != 0 &&
                                sessions[i].WinStationName[0] != 0
                                )
                            {
                                menuString = PhaFormatString(
                                    L"%u: %s (%s\\%s)",
                                    sessions[i].SessionId,
                                    sessions[i].WinStationName,
                                    winStationInfo.Domain,
                                    winStationInfo.UserName
                                    );
                            }
                            else if (winStationInfo.UserName[0] != 0)
                            {
                                menuString = PhaFormatString(
                                    L"%u: %s\\%s",
                                    sessions[i].SessionId,
                                    winStationInfo.Domain,
                                    winStationInfo.UserName
                                    );
                            }
                            else if (sessions[i].WinStationName[0] != 0)
                            {
                                menuString = PhaFormatString(
                                    L"%u: %s",
                                    sessions[i].SessionId,
                                    sessions[i].WinStationName
                                    );
                            }
                            else
                            {
                                menuString = PhaFormatString(L"%u", sessions[i].SessionId);
                            }

                            PhInsertEMenuItem(sessionsMenu,
                                PhCreateEMenuItem(0, 0, menuString->Buffer, NULL, UlongToPtr(sessions[i].SessionId)), -1);
                        }

                        WinStationFreeMemory(sessions);

                        GetWindowRect(GetDlgItem(hwndDlg, IDC_SESSIONS), &buttonRect);

                        selectedItem = PhShowEMenu(
                            sessionsMenu,
                            hwndDlg,
                            PH_EMENU_SHOW_LEFTRIGHT,
                            PH_ALIGN_LEFT | PH_ALIGN_TOP,
                            buttonRect.right,
                            buttonRect.top
                            );

                        if (selectedItem)
                        {
                            SetDlgItemInt(
                                hwndDlg,
                                IDC_SESSIONID,
                                PtrToUlong(selectedItem->Context),
                                FALSE
                                );
                        }

                        PhDestroyEMenu(sessionsMenu);
                    }
                }
                break;
            case IDC_DESKTOPS:
                {
                    PPH_EMENU desktopsMenu;
                    ULONG i;
                    RECT buttonRect;
                    PPH_EMENU_ITEM selectedItem;

                    desktopsMenu = PhCreateEMenu();

                    if (!context->DesktopList)
                        context->DesktopList = PhCreateList(10);

                    context->CurrentWinStaName = GetCurrentWinStaName();

                    EnumDesktops(GetProcessWindowStation(), EnumDesktopsCallback, (LPARAM)context);

                    for (i = 0; i < context->DesktopList->Count; i++)
                    {
                        PhInsertEMenuItem(
                            desktopsMenu,
                            PhCreateEMenuItem(0, 0, ((PPH_STRING)context->DesktopList->Items[i])->Buffer, NULL, NULL),
                            -1
                            );
                    }

                    GetWindowRect(GetDlgItem(hwndDlg, IDC_DESKTOPS), &buttonRect);

                    selectedItem = PhShowEMenu(
                        desktopsMenu,
                        hwndDlg,
                        PH_EMENU_SHOW_LEFTRIGHT,
                        PH_ALIGN_LEFT | PH_ALIGN_TOP,
                        buttonRect.right,
                        buttonRect.top
                        );

                    if (selectedItem)
                    {
                        SetDlgItemText(
                            hwndDlg,
                            IDC_DESKTOP,
                            selectedItem->Text
                            );
                    }

                    for (i = 0; i < context->DesktopList->Count; i++)
                        PhDereferenceObject(context->DesktopList->Items[i]);

                    PhClearList(context->DesktopList);
                    PhDereferenceObject(context->CurrentWinStaName);
                    PhDestroyEMenu(desktopsMenu);
                }
                break;
            }
        }
        break;
    }

    return FALSE;
}
Exemple #28
0
PPH_STRING PhpGetGdiHandleInformation(
    _In_ ULONG Handle
    )
{
    HGDIOBJ handle;

    handle = (HGDIOBJ)UlongToPtr(Handle);

    switch (GDI_CLIENT_TYPE_FROM_HANDLE(Handle))
    {
    case GDI_CLIENT_BITMAP_TYPE:
    case GDI_CLIENT_DIBSECTION_TYPE:
        {
            BITMAP bitmap;

            if (GetObject(handle, sizeof(BITMAP), &bitmap))
            {
                return PhFormatString(
                    L"Width: %u, Height: %u, Depth: %u",
                    bitmap.bmWidth,
                    bitmap.bmHeight,
                    bitmap.bmBitsPixel
                    );
            }
        }
        break;
    case GDI_CLIENT_BRUSH_TYPE:
        {
            LOGBRUSH brush;

            if (GetObject(handle, sizeof(LOGBRUSH), &brush))
            {
                return PhFormatString(
                    L"Style: %u, Color: 0x%08x, Hatch: 0x%Ix",
                    brush.lbStyle,
                    _byteswap_ulong(brush.lbColor),
                    brush.lbHatch
                    );
            }
        }
        break;
    case GDI_CLIENT_EXTPEN_TYPE:
        {
            EXTLOGPEN pen;

            if (GetObject(handle, sizeof(EXTLOGPEN), &pen))
            {
                return PhFormatString(
                    L"Style: 0x%x, Width: %u, Color: 0x%08x",
                    pen.elpPenStyle,
                    pen.elpWidth,
                    _byteswap_ulong(pen.elpColor)
                    );
            }
        }
        break;
    case GDI_CLIENT_FONT_TYPE:
        {
            LOGFONT font;

            if (GetObject(handle, sizeof(LOGFONT), &font))
            {
                return PhFormatString(
                    L"Face: %s, Height: %d",
                    font.lfFaceName,
                    font.lfHeight
                    );
            }
        }
        break;
    case GDI_CLIENT_PALETTE_TYPE:
        {
            USHORT count;

            if (GetObject(handle, sizeof(USHORT), &count))
            {
                return PhFormatString(
                    L"Entries: %u",
                    (ULONG)count
                    );
            }
        }
        break;
    case GDI_CLIENT_PEN_TYPE:
        {
            LOGPEN pen;

            if (GetObject(handle, sizeof(LOGPEN), &pen))
            {
                return PhFormatString(
                    L"Style: %u, Width: %u, Color: 0x%08x",
                    pen.lopnStyle,
                    pen.lopnWidth.x,
                    _byteswap_ulong(pen.lopnColor)
                    );
            }
        }
        break;
    }

    return NULL;
}
Exemple #29
0
VOID PhpRefreshGdiHandles(
    _In_ HWND hwndDlg,
    _In_ PGDI_HANDLES_CONTEXT Context
    )
{
    HWND lvHandle;
    ULONG i;
    PGDI_SHARED_MEMORY gdiShared;
    USHORT processId;
    PGDI_HANDLE_ENTRY handle;
    PPH_GDI_HANDLE_ITEM gdiHandleItem;

    lvHandle = GetDlgItem(hwndDlg, IDC_LIST);

    ExtendedListView_SetRedraw(lvHandle, FALSE);
    ListView_DeleteAllItems(lvHandle);

    for (i = 0; i < Context->List->Count; i++)
    {
        gdiHandleItem = Context->List->Items[i];

        if (gdiHandleItem->Information)
            PhDereferenceObject(gdiHandleItem->Information);

        PhFree(Context->List->Items[i]);
    }

    PhClearList(Context->List);

    gdiShared = (PGDI_SHARED_MEMORY)NtCurrentPeb()->GdiSharedHandleTable;
    processId = (USHORT)Context->ProcessItem->ProcessId;

    for (i = 0; i < GDI_MAX_HANDLE_COUNT; i++)
    {
        PWSTR typeName;
        INT lvItemIndex;
        WCHAR pointer[PH_PTR_STR_LEN_1];

        handle = &gdiShared->Handles[i];

        if (handle->Owner.ProcessId != processId)
            continue;

        typeName = PhpGetGdiHandleTypeName(handle->Unique);

        if (!typeName)
            continue;

        gdiHandleItem = PhAllocate(sizeof(PH_GDI_HANDLE_ITEM));
        gdiHandleItem->Entry = handle;
        gdiHandleItem->Handle = GDI_MAKE_HANDLE(i, handle->Unique);
        gdiHandleItem->Object = handle->Object;
        gdiHandleItem->TypeName = typeName;
        gdiHandleItem->Information = PhpGetGdiHandleInformation(gdiHandleItem->Handle);
        PhAddItemList(Context->List, gdiHandleItem);

        lvItemIndex = PhAddListViewItem(lvHandle, MAXINT, gdiHandleItem->TypeName, gdiHandleItem);
        PhPrintPointer(pointer, UlongToPtr(gdiHandleItem->Handle));
        PhSetListViewSubItem(lvHandle, lvItemIndex, 1, pointer);
        PhPrintPointer(pointer, gdiHandleItem->Object);
        PhSetListViewSubItem(lvHandle, lvItemIndex, 2, pointer);
        PhSetListViewSubItem(lvHandle, lvItemIndex, 3, PhGetString(gdiHandleItem->Information));
    }

    ExtendedListView_SortItems(lvHandle);
    ExtendedListView_SetRedraw(lvHandle, TRUE);
}
Exemple #30
0
NTSTATUS
LpxTdiReceive(
    IN PIRP Irp
    )

/*++

Routine Description:

    This routine performs the TdiReceive request for the transport provider.

Arguments:

    Irp - I/O Request Packet for this request.

Return Value:

    NTSTATUS - status of operation.

--*/

{
	PTP_CONNECTION connection;
	PIO_STACK_LOCATION irpSp;

    //
    // verify that the operation is taking place on a connection. At the same
    // time we do this, we reference the connection. This ensures it does not
    // get removed out from under us. Note also that we do the connection
    // lookup within a try/except clause, thus protecting ourselves against
    // really bogus handles
    //

    irpSp = IoGetCurrentIrpStackLocation (Irp);
    connection = irpSp->FileObject->FsContext;

    IF_LPXDBG (LPX_DEBUG_RCVENG) {
        LpxPrint2 ("LpxTdiReceive: Received IRP %p on connection %p\n", 
                        Irp, connection);
    }

    //
    // Check that this is really a connection.
    //

    if ((irpSp->FileObject->FsContext2 == UlongToPtr(LPX_FILE_TYPE_CONTROL)) ||
        (connection->Size != sizeof (TP_CONNECTION)) ||
        (connection->Type != LPX_CONNECTION_SIGNATURE)) {
#if DBG
        LpxPrint2 ("TdiReceive: Invalid Connection %p Irp %p\n", connection, Irp);
#endif
        return STATUS_INVALID_CONNECTION;
    }

#if __LPX__

	return LpxRecv( connection, Irp );

#endif

} /* TdiReceive */