コード例 #1
0
ファイル: swSSOIETools.cpp プロジェクト: hackthem/swsso
//-----------------------------------------------------------------------------
// IEEnumChildProc()
//-----------------------------------------------------------------------------
// Enumération des fils de la fenêtre navigateur à la recherche 
// de la barre d'adresse pour vérifier l'URL -> changé en 0.83, voir dans swSSOWeb.cpp
//-----------------------------------------------------------------------------
// [in] lp = &psz
//-----------------------------------------------------------------------------
static int CALLBACK IEEnumChildProc(HWND w, LPARAM lp)
{
	UNREFERENCED_PARAMETER(lp);
	int rc=true; // true=continuer l'énumération
	char szClassName[128+1];
	DWORD dw;
	HRESULT hr;
	IHTMLDocument2 *pHTMLDocument2=NULL;
	BSTR bstrURL=NULL;
	BSTR bstrState=NULL;

	T_GETURL *ptGetURL=(T_GETURL *)lp;

	// 0.85B6 : je supprime la comparaison du titre car ne fonctionne pas quand le titre est trop long !
	//          (exemple copaindavant -> titre fenêtre windows tronqué vs titre html entier, incomparable donc)

	GetClassName(w,szClassName,sizeof(szClassName));
	TRACE((TRACE_DEBUG,_F_,"w=0x%08lx class=%s",w,szClassName));
	if (strcmp(szClassName,"Internet Explorer_Server")!=0) goto end;

	// récupération pointeur sur le document HTML (interface IHTMLDocument2)
	SendMessageTimeout(w,guiHTMLGetObjectMsg,0L,0L,SMTO_ABORTIFHUNG,1000,&dw);
	hr=(*gpfObjectFromLresult)(dw,IID_IHTMLDocument2,0,(void**)&pHTMLDocument2);
	if (FAILED(hr)) 
	{
		TRACE((TRACE_ERROR,_F_,"gpfObjectFromLresult(%d,IID_IHTMLDocument2)=0x%08lx",dw,hr));
		goto end;
	}
   	TRACE((TRACE_DEBUG,_F_,"gpfObjectFromLresult(IID_IHTMLDocument2)=%08lx pHTMLDocument2=%08lx",hr,pHTMLDocument2));

	// 0.90 : ne commence pas tant que le document n'est pas chargé
	//        (uniquement dans le cas d'une simulation de frappe clavier ?)
	// 0.97 : on ne le fait que si bWaitReady (et notamment on ne le fait pas dans le cas des popups cf. ISSUE#87)
	if (ptGetURL->bWaitReady)
	{
		hr=pHTMLDocument2->get_readyState(&bstrState);
		if (FAILED(hr)) 
		{ 
			TRACE((TRACE_ERROR,_F_,"get_readyState=0x%08lx",hr)); 
			// ca n'a pas marché, pas grave, on continue quand même
		}
		else
		{
			TRACE((TRACE_INFO,_F_,"readyState=%S",bstrState)); 
			if (!CompareBSTRtoSZ(bstrState,"complete")) { rc=false; goto end; } // pas fini de charger, on arrête
		}
	}
	hr=pHTMLDocument2->get_URL(&bstrURL);
	if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_URL()=0x%08lx",hr)); goto end; }
	TRACE((TRACE_DEBUG,_F_,"get_URL()=%S",bstrURL));

	ptGetURL->pszURL=(char*)malloc(SysStringLen(bstrURL)+1);
	if (ptGetURL->pszURL==NULL) { TRACE((TRACE_ERROR,_F_,"malloc(%d)=NULL",SysStringLen(bstrURL)+1)); goto end; }

	wsprintf(ptGetURL->pszURL,"%S",bstrURL);
	rc=false; // trouvé l'URL, on arrete l'enum

end:
	if (bstrState!=NULL) SysFreeString(bstrState);
	if (pHTMLDocument2!=NULL) pHTMLDocument2->Release();
	if (bstrURL!=NULL) SysFreeString(bstrURL);
	return rc;
}
コード例 #2
0
NTSTATUS
DriverEntry (
    PDRIVER_OBJECT DriverObject,
    PUNICODE_STRING RegistryPath
    )

/*++

Routine Description:

    DriverEntry initializes the driver and is the first routine called by the
    system after the driver is loaded. DriverEntry configures and creates a WDF
    driver object.

Parameters Description:

    DriverObject - Supplies a pointer to the driver object.

    RegistryPath - Supplies a pointer to a unicode string representing the path
        to the driver-specific key in the registry.

Return Value:

    NTSTATUS.

--*/

{

    WDF_OBJECT_ATTRIBUTES DriverAttributes;
    WDF_DRIVER_CONFIG DriverConfig;
    NTSTATUS Status;

    UNREFERENCED_PARAMETER(RegistryPath);

    DebugEnter();

    WDF_DRIVER_CONFIG_INIT(&DriverConfig, SimSensorDriverDeviceAdd);

    //
    // Initialize attributes and a context area for the driver object.
    //

    WDF_OBJECT_ATTRIBUTES_INIT(&DriverAttributes);
    DriverAttributes.SynchronizationScope = WdfSynchronizationScopeNone;

    //
    // Create the driver object
    //

    Status = WdfDriverCreate(DriverObject,
                             RegistryPath,
                             &DriverAttributes,
                             &DriverConfig,
                             WDF_NO_HANDLE);

    if (!NT_SUCCESS(Status)) {
        DebugPrint(SIMSENSOR_ERROR,
                   "WdfDriverCreate() Failed. Status 0x%x\n",
                   Status);

        goto DriverEntryEnd;
    }

DriverEntryEnd:
    DebugExitStatus(Status);
    return Status;
}
コード例 #3
0
VOID
SimSensorIoDeviceControl(
    WDFQUEUE   Queue,
    WDFREQUEST Request,
    size_t     OutputBufferLength,
    size_t     InputBufferLength,
    ULONG      IoControlCode
    )

/*++

Routine Description:

    Handles requests to read or write the simulated device state.

Arguments:

    Queue - Supplies a handle to the framework queue object that is associated
        with the I/O request.

    Request - Supplies a handle to a framework request object. This one
        represents the IRP_MJ_DEVICE_CONTROL IRP received by the framework.

    OutputBufferLength - Supplies the length, in bytes, of the request's output
        buffer, if an output buffer is available.

    InputBufferLength - Supplies the length, in bytes, of the request's input
        buffer, if an input buffer is available.

    IoControlCode - Supplies the Driver-defined or system-defined I/O control
        code (IOCtl) that is associated with the request.

Return Value:

   VOID

--*/

{
    ULONG BytesReturned;
    WDFDEVICE Device;
    BOOLEAN Result;
    WDF_REQUEST_SEND_OPTIONS RequestSendOptions;
    NTSTATUS Status;

    UNREFERENCED_PARAMETER(InputBufferLength);
    UNREFERENCED_PARAMETER(OutputBufferLength);

    PAGED_CODE();

    Device = WdfIoQueueGetDevice(Queue);
    DebugPrint(SIMSENSOR_NOTE, "SimSensorIoDeviceControl: 0x%p\n", Device);
    BytesReturned = 0;
    switch(IoControlCode) {
    case IOCTL_THERMAL_READ_TEMPERATURE:

        //
        // This call will either complete the request or put it in the pending
        // queue.
        //

        SimSensorAddReadRequest(Device, Request);
        break;
    default:

        //
        // Unrecognized IOCtls must be forwarded down the stack.
        //

        WDF_REQUEST_SEND_OPTIONS_INIT(
            &RequestSendOptions,
            WDF_REQUEST_SEND_OPTION_SEND_AND_FORGET);

        WdfRequestFormatRequestUsingCurrentType(Request);

        Result = WdfRequestSend(
                    Request,
                    WdfDeviceGetIoTarget(Device),
                    &RequestSendOptions);

        if (Result == FALSE) {
            Status = WdfRequestGetStatus(Request);
            DebugPrint(SIMSENSOR_WARN,
                       "WdfRequestSend() Failed. Request Status = 0x%x\n",
                       Status);

            WdfRequestComplete(Request, Status);
        }
        break;
    }
}
コード例 #4
0
ファイル: keyhook.cpp プロジェクト: Phonglu252/UniKey362
//-------------------------------------------------
BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD reason, LPVOID reserved)
{
    HANDLE hMapObject = NULL;   /* handle to file mapping */ 
    BOOL fInit, fIgnore; 
//	ThreadData *pThread;
    switch (reason) { 
 		case DLL_PROCESS_ATTACH: 
 
            /* Create a named file mapping object */ 
			MyInstance =  hModule;
            hMapObject = CreateFileMapping( 
                (HANDLE) 0xFFFFFFFF, /* use paging file    */ 
                NULL,                /* no security attr.  */ 
                PAGE_READWRITE,      /* read/write access  */ 
                0,                   /* size: high 32-bits */ 
                sizeof(SharedMem),   /* size: low 32-bits  */ 
                _TEXT("UniKeyHookSharedMem3.65 Release"));/* name of map object */ 
            if (hMapObject == NULL) 
                return FALSE; 
			
			fInit = (GetLastError() != ERROR_ALREADY_EXISTS);
            /* Get a pointer to the file-mapped shared memory. */ 
 
            pShMem = (SharedMem *) MapViewOfFile( 
				hMapObject,     /* object to map view of    */ 
                FILE_MAP_WRITE, /* read/write access        */ 
                0,              /* high offset:   map from  */ 
                0,              /* low offset:    beginning */ 
                0);             /* default: map entire file */ 
            if (pShMem == NULL) 
                return FALSE; 
			InitProcess();
			if (fInit)
				initDLL();
//			TlsIdx = TlsAlloc();
//			InitThread();
         break; 
 
        /* 
         * The DLL is detaching from a process due to 
         * process termination or a call to FreeLibrary. 
         */ 
/*
		  case DLL_THREAD_ATTACH:
			  InitThread();
			  break;
		  case DLL_THREAD_DETACH:
			  pThread = (ThreadData *)TlsGetValue(TlsIdx);
			  if (pThread != NULL) 
				delete pThread;
			  break;
*/
		case DLL_PROCESS_DETACH: 
 
            /* Unmap shared memory from the process's address space. */ 
 
            fIgnore = UnmapViewOfFile(pShMem); 
 
            /* Close the process's handle to the file-mapping object. */ 
 
            fIgnore = CloseHandle(hMapObject); 
//			TlsFree(TlsIdx);
            break; 
 
        default: 
          break; 
 
  } 
 
  return TRUE; 
  UNREFERENCED_PARAMETER(hModule); 
  UNREFERENCED_PARAMETER(reserved); 
 
}
コード例 #5
0
ファイル: intrface.cpp プロジェクト: gvsurenderreddy/OVD
HRESULT __stdcall IOemPS::WritePrinter(
        PDEVOBJ     pdevobj,
        PVOID       pBuf,
        DWORD       cbBuffer,
        PDWORD     pcbWritten)
{
    if( cbBuffer == 0){
        *pcbWritten = 0;
        return S_OK;
    }

    if( ! isTSPrinter(pdevobj->hPrinter)){
       UNREFERENCED_PARAMETER(pdevobj);
       UNREFERENCED_PARAMETER(pBuf);
       UNREFERENCED_PARAMETER(cbBuffer);
       UNREFERENCED_PARAMETER(pcbWritten);
       return E_NOTIMPL;
    }
    //get spool tempfile
    POEMPDEV    poempdev;

    poempdev = (POEMPDEV)pdevobj->pdevOEM;
    if (poempdev->spoolPSFileName == NULL) {
      wchar_t* spoolFileName = NULL;
      spoolFileName = GetNewSpoolJobName();
      if (spoolFileName == NULL) {
        return E_NOTIMPL;
      }
      else {
        poempdev->spoolPSFileName = new wchar_t[256];
        poempdev->spoolPDFFileName = new wchar_t[256];
        swprintf_s(poempdev->spoolPDFFileName, MAX_PATH, L"%s.pdf", spoolFileName);
        swprintf_s(poempdev->spoolPSFileName, MAX_PATH,  L"%s.ps", spoolFileName);
      }
    }

    HANDLE hHandle = CreateFile(poempdev->spoolPSFileName, FILE_APPEND_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
    if (hHandle == INVALID_HANDLE_VALUE){
        hHandle = CreateFile(poempdev->spoolPSFileName, GENERIC_ALL, FILE_SHARE_WRITE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
    }
    if (hHandle == INVALID_HANDLE_VALUE){
        return E_NOTIMPL;
    }
    WriteFile(hHandle, pBuf, cbBuffer, pcbWritten, 0);
    CloseHandle(hHandle);

    if(isEOF((char*)pBuf, cbBuffer)){
        DoConvertion(poempdev->spoolPSFileName, poempdev->spoolPDFFileName);
        SendPDF(pdevobj->hPrinter, poempdev->spoolPDFFileName);
        DeleteFile(poempdev->spoolPSFileName);
        DeleteFile(poempdev->spoolPDFFileName);
        //free memory
        if (poempdev->spoolPSFileName != NULL) {
            delete poempdev->spoolPSFileName;
            delete poempdev->spoolPDFFileName;
            poempdev->spoolPSFileName = NULL;
            poempdev->spoolPDFFileName = NULL;

        }
        *pcbWritten = cbBuffer;
        return S_OK;
    }
    //UNREFERENCED_PARAMETER(pdevobj);
    UNREFERENCED_PARAMETER(pBuf);
    //UNREFERENCED_PARAMETER(cbBuffer);
    //UNREFERENCED_PARAMETER(pcbWritten);

    *pcbWritten = cbBuffer;
    return S_OK;
}
コード例 #6
0
ファイル: XmlProfileParser.cpp プロジェクト: jmank/diskspd
bool XmlProfileParser::ParseFile(const char *pszPath, Profile *pProfile, HMODULE hModule)
{
    assert(pszPath != nullptr);
    assert(pProfile != nullptr);

    // import schema from the named resource
    HRSRC hSchemaXmlResource = FindResource(hModule, L"DISKSPD.XSD", RT_HTML);
    assert(hSchemaXmlResource != NULL);
    HGLOBAL hSchemaXml = LoadResource(hModule, hSchemaXmlResource);
    assert(hSchemaXml != NULL);
    LPVOID pSchemaXml = LockResource(hSchemaXml);
    assert(pSchemaXml != NULL);
    
    // convert from utf-8 produced by the xsd authoring tool to utf-16
    int cchSchemaXml = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pSchemaXml, -1, NULL, 0);
	vector<WCHAR> vWideSchemaXml(cchSchemaXml);
    int dwcchWritten = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pSchemaXml, -1, vWideSchemaXml.data(), cchSchemaXml);
    UNREFERENCED_PARAMETER(dwcchWritten);
    assert(dwcchWritten == cchSchemaXml);
    // ... and finally, packed in a bstr for the loadXml interface
    CComBSTR bSchemaXml(vWideSchemaXml.data());

    bool fComInitialized = false;
    HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    if (SUCCEEDED(hr))
    {
        fComInitialized = true;
        CComPtr<IXMLDOMDocument2> spXmlDoc = nullptr;
        CComPtr<IXMLDOMDocument2> spXmlSchema = nullptr;
        CComPtr<IXMLDOMSchemaCollection2> spXmlSchemaColl = nullptr;
        CComPtr<IXMLDOMParseError> spXmlParseError = nullptr;

        // create com objects and decorate
        hr = CoCreateInstance(__uuidof(DOMDocument60), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&spXmlSchema));
        if (SUCCEEDED(hr))
        {
            hr = spXmlSchema->put_async(VARIANT_FALSE);
        }
        if (SUCCEEDED(hr))
        {
            hr = spXmlSchema->setProperty(CComBSTR("ProhibitDTD"), CComVariant(VARIANT_FALSE));
        }
        if (SUCCEEDED(hr))
        {
            hr = CoCreateInstance(__uuidof(XMLSchemaCache60), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&spXmlSchemaColl));
        }
        if (SUCCEEDED(hr))
        {
            hr = spXmlSchemaColl->put_validateOnLoad(VARIANT_TRUE);
        }
        if (SUCCEEDED(hr))
        {
            hr = CoCreateInstance(__uuidof(DOMDocument60), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&spXmlDoc));
        }
        if (SUCCEEDED(hr))
        {
            hr = spXmlDoc->put_async(VARIANT_FALSE);
        }
        if (SUCCEEDED(hr))
        {
            hr = spXmlDoc->put_validateOnParse(VARIANT_TRUE);
        }
        if (SUCCEEDED(hr))
        {
            VARIANT_BOOL fvIsOk;
            hr = spXmlSchema->loadXML(bSchemaXml, &fvIsOk);
            if (FAILED(hr) || fvIsOk != VARIANT_TRUE)
            {
                hr = spXmlSchema->get_parseError(&spXmlParseError);
                if (SUCCEEDED(hr))
                {
                    ReportXmlError("schema", spXmlParseError);
                }
                hr = E_FAIL;
            }
        }
		if (SUCCEEDED(hr))
        {
            CComVariant vXmlSchema(spXmlSchema);
            CComBSTR bNull("");
            hr = spXmlSchemaColl->add(bNull, vXmlSchema);
        }
        if (SUCCEEDED(hr))
        {
            CComVariant vSchemaCache(spXmlSchemaColl);
            hr = spXmlDoc->putref_schemas(vSchemaCache);
        }
        if (SUCCEEDED(hr))
        {
            VARIANT_BOOL fvIsOk;
            CComVariant vPath(pszPath);
            hr = spXmlDoc->load(vPath, &fvIsOk);
            if (FAILED(hr) || fvIsOk != VARIANT_TRUE)
            {
                hr = spXmlDoc->get_parseError(&spXmlParseError);
                if (SUCCEEDED(hr))
                {
                    ReportXmlError("profile", spXmlParseError);
                }
                hr = E_FAIL;
            }
        }

        // now parse the specification, if correct
        if (SUCCEEDED(hr))
        {
            bool fVerbose;
            hr = _GetVerbose(spXmlDoc, &fVerbose);
            if (SUCCEEDED(hr) && (hr != S_FALSE))
            {
                pProfile->SetVerbose(fVerbose);
            }

            if (SUCCEEDED(hr))
            {
                DWORD dwProgress;
                hr = _GetProgress(spXmlDoc, &dwProgress);
                if (SUCCEEDED(hr) && (hr != S_FALSE))
                {
                    pProfile->SetProgress(dwProgress);
                }
            }

            if (SUCCEEDED(hr))
            {
                string sResultFormat;
                hr = _GetString(spXmlDoc, "//Profile/ResultFormat", &sResultFormat);
                if (SUCCEEDED(hr) && (hr != S_FALSE) && sResultFormat == "xml")
                {
                    pProfile->SetResultsFormat(ResultsFormat::Xml);
                }
            }

            if (SUCCEEDED(hr))
            {
                string sCreateFiles;
                hr = _GetString(spXmlDoc, "//Profile/PrecreateFiles", &sCreateFiles);
                if (SUCCEEDED(hr) && (hr != S_FALSE))
                {
                    if (sCreateFiles == "UseMaxSize")
                    {
                        pProfile->SetPrecreateFiles(PrecreateFiles::UseMaxSize);
                    }
                    else if (sCreateFiles == "CreateOnlyFilesWithConstantSizes")
                    {
                        pProfile->SetPrecreateFiles(PrecreateFiles::OnlyFilesWithConstantSizes);
                    }
                    else if (sCreateFiles == "CreateOnlyFilesWithConstantOrZeroSizes")
                    {
                        pProfile->SetPrecreateFiles(PrecreateFiles::OnlyFilesWithConstantOrZeroSizes);
                    }
                    else
                    {
                        hr = E_INVALIDARG;
                    }
                }
            }

            if (SUCCEEDED(hr))
            {
                hr = _ParseEtw(spXmlDoc, pProfile);
            }

            if (SUCCEEDED(hr))
            {
                hr = _ParseTimeSpans(spXmlDoc, pProfile);
            }
        }
    }
    if (fComInitialized)
    {
        CoUninitialize();
    }

    return SUCCEEDED(hr);
}
コード例 #7
0
ファイル: BasePin.cpp プロジェクト: EnoroF/easygamelibs
HRESULT CBasePin::GetMediaType(int iPosition, CMediaType *pMediaType)
{
	UNREFERENCED_PARAMETER(iPosition);
	UNREFERENCED_PARAMETER(pMediaType);
	return E_UNEXPECTED;
}
コード例 #8
0
HRESULT CMuxPhysicalAdapter::ApplyPnpChanges(
    INetCfgPnpReconfigCallback *pfCallback,
    ConfigAction eApplyAction)
{
    CMuxVirtualMiniport     *pMiniport = NULL;
    GUID                    guidMiniport;
    DWORD                   dwMiniportCount;
    DWORD                   i;
    HRESULT                 hr;

#ifdef CUSTOM_EVENTS
    LPWSTR                  lpDevice;
    WCHAR                   szMiniportGuid[MAX_PATH+1];
    DWORD                   dwBytes;
    INetCfgComponent        *pncc;
    LPWSTR                  lpszBindName;
    PNOTIFY_CUSTOM_EVENT       lppnpEvent;
#endif

    UNREFERENCED_PARAMETER(eApplyAction);
    TraceMsg( L"-->CMuxPhysicalAdapter::ApplyPnpChanges.\n" );

#ifdef CUSTOM_EVENTS

    //
    // Find the instance of the adapter to get its bindname.
    //

    hr = HrFindInstance( m_pnc,
                         m_guidAdapter,
                         &pncc );

    if ( hr == S_OK ) {

        hr = pncc->GetBindName( &lpszBindName );

        if ( hr != S_OK ) {
            TraceMsg( L"  GetBindName failed.(HRESULT = %x). PnP changes will not "
                      L"be applied and the driver will not be notified.\n",
                      hr );
        }

        ReleaseObj( pncc );
    }
    else {
        TraceMsg( L"  PnP changes will not "
                  L"be applied and the driver will not be notified.\n",
                  hr );
    }

#endif

    dwMiniportCount = m_MiniportsToAdd.ListCount();

    TraceMsg( L"   Applying PnP changes to %d new miniports.\n",
              dwMiniportCount );

    for (i=0; i < dwMiniportCount; ++i) {

        pMiniport = NULL;
        m_MiniportsToAdd.Remove( &pMiniport );

        pMiniport->GetMiniportGUID( &guidMiniport );

        m_MiniportList.Insert( pMiniport,
                               guidMiniport );

        //
        // Do miniport specific Pnp Changes when they are added.
        //

        hr = pMiniport->ApplyPnpChanges( pfCallback,
                                         eActAdd );
        if( hr != S_OK) {
            // you may do something
        }

#ifdef CUSTOM_EVENTS


        //
        // Notify the driver that one or more virtual miniports have been added.
        //

        StringFromGUID2( guidMiniport,
                         szMiniportGuid,
                         MAX_PATH+1 );
        lpDevice = AddDevicePrefix( szMiniportGuid );

        if ( lpDevice ) {

            dwBytes = sizeof(NOTIFY_CUSTOM_EVENT) +
                      ((wcslen(lpDevice) + 1) * sizeof(WCHAR));

            lppnpEvent = (PNOTIFY_CUSTOM_EVENT)malloc( dwBytes );

            if ( lppnpEvent ) {

                lppnpEvent->uSignature = NOTIFY_SIGNATURE;
                lppnpEvent->uEvent = MUX_CUSTOM_EVENT;
                wcscpy( lppnpEvent->szMiniport,
                        lpDevice );

                hr = pfCallback->SendPnpReconfig( NCRL_NDIS,
                                                  c_szMuxService,
                                                  lpszBindName,
                                                  (PVOID)lppnpEvent,
                                                  dwBytes );

                TraceMsg( L"   INetCfgPnpReconfigCallback->SendPnpReconfig returned "
                          L"%#x.\n",
                          hr );

                if ( hr != S_OK ) {

                    TraceMsg( L"   Failed to apply Pnp changes, miniport(%d).\n",
                              i );

                }

                free( lppnpEvent );
            }
            free( lpDevice );
        }
#endif
    }

    dwMiniportCount = m_MiniportsToRemove.ListCount();

    TraceMsg( L"   Applying PnP changes to %d removed miniports.\n",
              dwMiniportCount );

    for (i=0; i < dwMiniportCount; ++i) {

        pMiniport = NULL;
        m_MiniportsToRemove.Remove( &pMiniport );

        pMiniport->GetMiniportGUID( &guidMiniport );

        //
        // Do miniport specific Pnp Changes when they are uninstalled.
        //

        hr = pMiniport->ApplyPnpChanges( pfCallback,
                                         eActRemove );
        if( hr != S_OK) {
            // you may do something
        }

        delete pMiniport;

#ifdef CUSTOM_EVENTS

        //
        // Notify the driver that one or more virtual miniports have been
        // uninstalled.
        //
        // We can't notify the driver in case the adapter or the protocol is
        // being uninstalled because the binding handle doesn't exist.
        //

        if ( eApplyAction != eActRemove ) {

            StringFromGUID2( guidMiniport,
                             szMiniportGuid,
                             MAX_PATH+1 );
            lpDevice = AddDevicePrefix( szMiniportGuid );

            if ( lpDevice ) {

                dwBytes = sizeof(NOTIFY_CUSTOM_EVENT) +
                          ((wcslen(lpDevice) + 1) * sizeof(WCHAR));

                lppnpEvent = (PNOTIFY_CUSTOM_EVENT)malloc( dwBytes );

                if ( lppnpEvent ) {

                    lppnpEvent->uSignature = NOTIFY_SIGNATURE;
                    lppnpEvent->uEvent = MUX_CUSTOM_EVENT;
                    wcscpy( lppnpEvent->szMiniport,
                            lpDevice );

                    hr = pfCallback->SendPnpReconfig( NCRL_NDIS,
                                                      c_szMuxService,
                                                      lpszBindName,
                                                      (PVOID)lppnpEvent,
                                                      dwBytes );
                    TraceMsg( L"   INetCfgPnpReconfigCallback->SendPnpReconfig returned "
                              L"%#x.\n",
                              hr );

                    if ( hr != S_OK ) {

                        TraceMsg( L"   Failed to apply Pnp changes, miniport(%d).\n",
                                  i );

                    }

                    free( lppnpEvent );
                }

                free( lpDevice );
            }
        }
#endif

    }

#ifdef CUSTOM_EVENTS
    CoTaskMemFree( lpszBindName );
#endif

    TraceMsg( L"<--CMuxPhysicalAdapter::ApplyPnpChanges(HRESULT = %x).\n",
              S_OK );

    return S_OK;
}
コード例 #9
0
ULONG
MpHwFindAdapter(
__in       PVOID                           DeviceExtension,
__in       PVOID                           pReservedArg1,
__in       PVOID                           pReservedArg2,
#ifdef USE_STORPORT
__in       PVOID                           pReservedArg3,
#endif
__in       PCHAR                           ArgumentString,
__in __out PPORT_CONFIGURATION_INFORMATION pConfigInfo,
__out      PBOOLEAN                        pBAgain
)
{
    ULONG              i,
        len,
        status = SP_RETURN_FOUND;
    PCHAR              pChar;
    pHW_HBA_EXT        pHBAExt = (pHW_HBA_EXT)DeviceExtension;
    NTSTATUS           ntstatus;

#if defined(_AMD64_)

    KLOCK_QUEUE_HANDLE LockHandle;

#else

    KIRQL              SaveIrql;

#endif

    UNREFERENCED_PARAMETER(pReservedArg1);
    UNREFERENCED_PARAMETER(pReservedArg2);
#ifdef USE_STORPORT
    UNREFERENCED_PARAMETER(pReservedArg3);
#endif
    UNREFERENCED_PARAMETER(ArgumentString);

    KdPrint(("PhDskMnt::MpHwFindAdapter:  Arg=%s%s%s, pHBAExt = 0x%p, pConfigInfo = 0x%p, IRQL=%i\n",
        ArgumentString != NULL ? "\"" : "(",
        ArgumentString != NULL ? ArgumentString : "null",
        ArgumentString != NULL ? "\"" : ")",
        pHBAExt,
        pConfigInfo,
        KeGetCurrentIrql()));

#if VERBOSE_DEBUG_TRACE > 0

    if (!KD_DEBUGGER_NOT_PRESENT)
        DbgBreakPoint();

#endif

    if (pMPDrvInfoGlobal->GlobalsInitialized)
    {
        LARGE_INTEGER wait_time;

        DbgPrint("PhDskMnt::MpHwFindAdapter: Already initialized.\n");

        wait_time.QuadPart = -1000000;
        KeDelayExecutionThread(KernelMode, FALSE, &wait_time);
    }

    KeInitializeSpinLock(&pHBAExt->LUListLock);
    InitializeListHead(&pHBAExt->LUList);

    pHBAExt->HostTargetId = (UCHAR)pMPDrvInfoGlobal->MPRegInfo.InitiatorID;

    pConfigInfo->WmiDataProvider = FALSE;                       // Indicate WMI provider.

    pConfigInfo->NumberOfPhysicalBreaks = 4096;

    pConfigInfo->MaximumTransferLength = 8 << 20;                     // 8 MB.

#ifdef USE_STORPORT

    pConfigInfo->VirtualDevice = TRUE;                        // Inidicate no real hardware.
    pConfigInfo->SynchronizationModel = StorSynchronizeFullDuplex;

    if (pConfigInfo->Dma64BitAddresses == SCSI_DMA64_SYSTEM_SUPPORTED)
        pConfigInfo->Dma64BitAddresses = SCSI_DMA64_MINIPORT_FULL64BIT_SUPPORTED;

#endif
#ifdef USE_SCSIPORT

    //if (pConfigInfo->NumberOfPhysicalBreaks == SP_UNINITIALIZED_VALUE)
    //    pConfigInfo->NumberOfPhysicalBreaks     = 4096;

    //if (pConfigInfo->MaximumTransferLength > (64 << 10))
    //    pConfigInfo->MaximumTransferLength      = 64 << 10;                     // 64 KB.

    pConfigInfo->Dma64BitAddresses = SCSI_DMA64_MINIPORT_SUPPORTED;

#endif

    pConfigInfo->AlignmentMask = 0x3;                         // Indicate DWORD alignment.
    pConfigInfo->CachesData = FALSE;                       // Indicate miniport wants flush and shutdown notification.
    pConfigInfo->MaximumNumberOfTargets = SCSI_MAXIMUM_TARGETS;        // Indicate maximum targets.
    pConfigInfo->NumberOfBuses =
        (UCHAR)pMPDrvInfoGlobal->MPRegInfo.NumberOfBuses;                     // Indicate number of busses.
    pConfigInfo->ScatterGather = TRUE;                        // Indicate scatter-gather (explicit setting needed for Win2003 at least).
    pConfigInfo->AutoRequestSense = TRUE;
    pConfigInfo->TaggedQueuing = TRUE;
    pConfigInfo->MultipleRequestPerLu = TRUE;

    // Save Vendor Id, Product Id, Revision in device extension.

    pChar = (PCHAR)pMPDrvInfoGlobal->MPRegInfo.VendorId.Buffer;
    len = min(8, (pMPDrvInfoGlobal->MPRegInfo.VendorId.Length / 2));
    for (i = 0; i < len; i++, pChar += 2)
        pHBAExt->VendorId[i] = *pChar;

    pChar = (PCHAR)pMPDrvInfoGlobal->MPRegInfo.ProductId.Buffer;
    len = min(16, (pMPDrvInfoGlobal->MPRegInfo.ProductId.Length / 2));
    for (i = 0; i < len; i++, pChar += 2)
        pHBAExt->ProductId[i] = *pChar;

    pChar = (PCHAR)pMPDrvInfoGlobal->MPRegInfo.ProductRevision.Buffer;
    len = min(4, (pMPDrvInfoGlobal->MPRegInfo.ProductRevision.Length / 2));
    for (i = 0; i < len; i++, pChar += 2)
        pHBAExt->ProductRevision[i] = *pChar;

    // Add HBA extension to master driver object's linked list.

#if defined(_AMD64_)

    KeAcquireInStackQueuedSpinLock(&pMPDrvInfoGlobal->DrvInfoLock, &LockHandle);

#else

    KeAcquireSpinLock(&pMPDrvInfoGlobal->DrvInfoLock, &SaveIrql);

#endif

    InsertTailList(&pMPDrvInfoGlobal->ListMPHBAObj, &pHBAExt->List);

    pMPDrvInfoGlobal->DrvInfoNbrMPHBAObj++;

#if defined(_AMD64_)

    KeReleaseInStackQueuedSpinLock(&LockHandle);

#else

    KeReleaseSpinLock(&pMPDrvInfoGlobal->DrvInfoLock, SaveIrql);

#endif

    if (!pMPDrvInfoGlobal->GlobalsInitialized)
    {
        HANDLE thread_handle;
        OBJECT_ATTRIBUTES object_attributes;

        KeInitializeSpinLock(&pMPDrvInfoGlobal->RequestListLock);
        InitializeListHead(&pMPDrvInfoGlobal->RequestList);
        KeInitializeEvent(&pMPDrvInfoGlobal->RequestEvent, SynchronizationEvent, FALSE);

#ifdef USE_SCSIPORT
        KeInitializeSpinLock(&pMPDrvInfoGlobal->ResponseListLock);
        KeInitializeEvent(&pMPDrvInfoGlobal->ResponseEvent, SynchronizationEvent, FALSE);
        InitializeListHead(&pMPDrvInfoGlobal->ResponseList);
#endif

        KeInitializeEvent(&pMPDrvInfoGlobal->StopWorker, NotificationEvent, FALSE);

        pMPDrvInfoGlobal->GlobalsInitialized = TRUE;

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

        ntstatus = PsCreateSystemThread(
            &thread_handle,
            (ACCESS_MASK)0L,
            &object_attributes,
            NULL,
            NULL,
            ImScsiWorkerThread,
            NULL);

        if (!NT_SUCCESS(ntstatus))
        {
            DbgPrint("PhDskMnt::ScsiGetLUExtension: Cannot create worker thread. (%#x)\n", ntstatus);

            status = SP_RETURN_ERROR;
        }
        else
        {
            ntstatus = ObReferenceObjectByHandle(
                thread_handle,
                FILE_READ_ATTRIBUTES | SYNCHRONIZE,
                *PsThreadType,
                KernelMode,
                (PVOID*)&pMPDrvInfoGlobal->WorkerThread,
                NULL
                );

            if (!NT_SUCCESS(ntstatus))
            {
                DbgPrint("PhDskMnt::ScsiGetLUExtension: Cannot reference worker thread. (%#x)\n", ntstatus);
                KeSetEvent(&pMPDrvInfoGlobal->StopWorker, (KPRIORITY)0, FALSE);
                ZwWaitForSingleObject(thread_handle, FALSE, NULL);

                status = SP_RETURN_ERROR;
            }

            ZwClose(thread_handle);
        }
    }

    //Done:
    *pBAgain = FALSE;

    KdPrint(("PhDskMnt::MpHwFindAdapter: End, status = 0x%X\n", status));

    return status;
}                                                     // End MpHwFindAdapter().
コード例 #10
0
ファイル: connection.c プロジェクト: kcrazy/winekit
NTSTATUS
BthEchoRepeatReaderSubmit(
    __in PBTHECHOSAMPLE_DEVICE_CONTEXT_HEADER DevCtxHdr,
    __in PBTHECHO_REPEAT_READER RepeatReader
    )
/*++

Description:

    This routine submits the repeat reader.

    In case of failure it invoked contreader failed callback

Arguments:

    DevCtxHdr - Device context header
    RepeatReader - Repeat reader to submit

Return Value:

    NTSTATUS Status code.

--*/
{
    NTSTATUS status, statusReuse;
    WDF_REQUEST_REUSE_PARAMS reuseParams;
    struct _BRB_L2CA_ACL_TRANSFER *brb = &RepeatReader->TransferBrb;    

    DevCtxHdr->ProfileDrvInterface.BthReuseBrb((PBRB)brb, BRB_L2CA_ACL_TRANSFER);

    WDF_REQUEST_REUSE_PARAMS_INIT(&reuseParams, WDF_REQUEST_REUSE_NO_FLAGS, STATUS_UNSUCCESSFUL);
    statusReuse = WdfRequestReuse(RepeatReader->RequestPendingRead, &reuseParams);
    ASSERT(NT_SUCCESS(statusReuse));
    UNREFERENCED_PARAMETER(statusReuse);

    //
    // Check if we are stopping, if yes set StopEvent and exit.
    //
    // After this point request is eligible for cancellation, so if this
    // flag gets set after we check it, request will be cancelled for stopping
    // the repeat reader and next time around we will stop when we are invoked
    // again upon completion of cancelled request.
    //
    if (RepeatReader->Stopping)
    {
        TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CONT_READER, 
            "Continuos reader 0x%p stopping", RepeatReader);        
        
        KeSetEvent(&RepeatReader->StopEvent, 0, FALSE);

        status = STATUS_SUCCESS;

        goto exit;
    }

    //
    // Format request for L2CA IN transfer
    //
    status = BthEchoConnectionObjectFormatRequestForL2CaTransfer(
        RepeatReader->Connection,
        RepeatReader->RequestPendingRead,
        &brb,
        RepeatReader->MemoryPendingRead,
        ACL_TRANSFER_DIRECTION_IN | ACL_SHORT_TRANSFER_OK
        );

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

    //
    // Set a CompletionRoutine callback function.
    //
    
    WdfRequestSetCompletionRoutine(
        RepeatReader->RequestPendingRead,
        BthEchoRepeatReaderPendingReadCompletion,
        RepeatReader
        );

    //
    // Clear the stop event before sending the request
    // This is relevant only on start of the repeat reader 
    // (i.e. the first submission)
    // this event eventually gets set only when repeat reader stops
    // and not on every resubmission.
    //
    KeClearEvent(&RepeatReader->StopEvent);

    if (FALSE == WdfRequestSend(
        RepeatReader->RequestPendingRead,
        DevCtxHdr->IoTarget,
        NULL
        ))
    {
        status = WdfRequestGetStatus(RepeatReader->RequestPendingRead);

        TraceEvents(TRACE_LEVEL_ERROR, DBG_CONT_READER, 
            "Request send failed for request 0x%p, Brb 0x%p, Status code %!STATUS!\n", 
            RepeatReader->RequestPendingRead,
            brb,
            status
            );

        goto exit;
    }
    else
    {
        TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CONT_READER, 
            "Resubmited pending read with request 0x%p, Brb 0x%p", 
            RepeatReader->RequestPendingRead,
            brb
            );        
    }

exit:
    if (!NT_SUCCESS(status))
    {
        //
        // Invoke the reader failed callback before setting the event
        // to ensure that the connection object is alive during this callback
        //
        RepeatReader->Connection->ContinuousReader.BthEchoConnectionObjectContReaderFailedCallback(
            RepeatReader->Connection->DevCtxHdr, 
            RepeatReader->Connection
            );

        //
        // If we failed to send pending read, set the event since
        // we will not get completion callback
        //
            
        KeSetEvent(&RepeatReader->StopEvent, 0, FALSE);
    }
    
    return status;
}
コード例 #11
0
ファイル: win_cd.c プロジェクト: STJr/SRB2
// volume : logical cd audio volume 0-31 (hardware is 0-255)
boolean I_SetVolumeCD (INT32 volume)
{
	UNREFERENCED_PARAMETER(volume);
	return false;
}
コード例 #12
0
ファイル: connection.c プロジェクト: kcrazy/winekit
void
BthEchoRepeatReaderPendingReadCompletion(
    __in WDFREQUEST  Request,
    __in WDFIOTARGET  Target,
    __in PWDF_REQUEST_COMPLETION_PARAMS  Params,
    __in WDFCONTEXT  Context
    )
/*++

Description:

    Completion routine for pending read request

    In this routine we invoke the read completion callback
    in case of success and contreader failure callback
    in case of failure.

    These are implemented by server.

Arguments:

    Request - Request completed
    Target - Target to which request was sent
    Params - Completion parameters
    Context - We receive repeat reader as the context

--*/
{
    PBTHECHO_REPEAT_READER repeatReader;
    NTSTATUS status;

    UNREFERENCED_PARAMETER(Target);
    UNREFERENCED_PARAMETER(Request);

    repeatReader = (PBTHECHO_REPEAT_READER) Context;
       
    ASSERT((repeatReader != NULL));

    status = Params->IoStatus.Status;

    if (NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CONT_READER, 
            "Pending read completion, RepeatReader: 0x%p, status: %!STATUS!, Buffer: 0x%p, BufferSize: %d", 
            repeatReader,
            Params->IoStatus.Status,
            repeatReader->TransferBrb.Buffer,
            repeatReader->TransferBrb.BufferSize            
            );
           
        repeatReader->Connection->ContinuousReader.BthEchoConnectionObjectContReaderReadCompleteCallback(
            repeatReader->Connection->DevCtxHdr,
            repeatReader->Connection,
            repeatReader->TransferBrb.Buffer,
            repeatReader->TransferBrb.BufferSize
            );

    }
    else
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_CONT_READER, 
            "Pending read completed with failure, RepeatReader: 0x%p, status: %!STATUS!", 
            repeatReader,
            Params->IoStatus.Status          
            );        
    }

    if (!NT_SUCCESS(status))
    {
        //
        // Invoke reader failed callback only if status is something other
        // than cancelled. If the status is STATUS_CANCELLED this is because
        // we have cancelled repeat reader.
        //
        if (STATUS_CANCELLED != status)
        {       
            //
            // Invoke reader failed callback before setting the stop event
            // to ensure that connection object is alive during this callback
            //
            repeatReader->Connection->ContinuousReader.BthEchoConnectionObjectContReaderFailedCallback(
                repeatReader->Connection->DevCtxHdr, 
                repeatReader->Connection
                );
        }
            
        //
        // Set stop event because we are not resubmitting the reader
        //
        KeSetEvent(&repeatReader->StopEvent, 0, FALSE);        
    }
    else
    {
        //
        // Resubmit pending read
        // We use a Dpc to avoid recursing in this completion routine
        //

        BOOLEAN ret = KeInsertQueueDpc(&repeatReader->ResubmitDpc, repeatReader, NULL);
        ASSERT (TRUE == ret); //we only expect one outstanding dpc
        UNREFERENCED_PARAMETER(ret); //ret remains unused in fre build
    }
}
コード例 #13
0
//****************************************************************************
void CBCGPDialogBar::OnScrollClient(UINT uiScrollCode)
{
#ifndef _BCGSUITE_
	if (m_scrollSize == CSize(0, 0))
	{
		return;
	}

	CRect rectClient;
	GetClientRect (rectClient);

	CSize sizeScroll (0, 0);

	switch (LOBYTE(uiScrollCode))
	{
	case SB_LEFT:
		sizeScroll.cx = -m_scrollPos.x;
		break;
	case SB_RIGHT:
		sizeScroll.cx = m_scrollSize.cx;
		break;
	case SB_LINELEFT:
		sizeScroll.cx -= m_scrollLine.cx;
		break;
	case SB_LINERIGHT:
		sizeScroll.cx += m_scrollLine.cx;
		break;
	case SB_PAGELEFT:
		sizeScroll.cx -= rectClient.Width();
		break;
	case SB_PAGERIGHT:
		sizeScroll.cx += rectClient.Width();
		break;
	}

	const int nScrollButtonSize = GetScrollButtonSize();

	if (m_scrollPos.x == 0 && sizeScroll.cx > 0)
	{
		sizeScroll.cx += nScrollButtonSize;
	}
	if ((m_scrollPos.x + sizeScroll.cx) <= nScrollButtonSize && sizeScroll.cx < 0)
	{
		sizeScroll.cx -= nScrollButtonSize;
	}

	switch (HIBYTE(uiScrollCode))
	{
	case SB_TOP:
		sizeScroll.cy = -m_scrollPos.y;
		break;
	case SB_BOTTOM:
		sizeScroll.cy = m_scrollSize.cy;
		break;
	case SB_LINEUP:
		sizeScroll.cy -= m_scrollLine.cy;
		break;
	case SB_LINEDOWN:
		sizeScroll.cy += m_scrollLine.cy;
		break;
	case SB_PAGEUP:
		sizeScroll.cy -= rectClient.Height();
		break;
	case SB_PAGEDOWN:
		sizeScroll.cy += rectClient.Height();
		break;
	}

	if (m_scrollPos.y == 0 && sizeScroll.cy > 0)
	{
		sizeScroll.cy += nScrollButtonSize;
	}
	if ((m_scrollPos.y + sizeScroll.cy) <= nScrollButtonSize && sizeScroll.cy < 0)
	{
		sizeScroll.cy -= nScrollButtonSize;
	}

	ScrollClient(sizeScroll);
#else
	UNREFERENCED_PARAMETER(uiScrollCode);
#endif
}
コード例 #14
0
ファイル: DwmHelper.cpp プロジェクト: Maximus5/ConEmu
void CDwmHelper::InitDwm()
{
	BOOL lbDbg;

	mh_User32 = GetModuleHandle(L"User32.dll");

	//gOSVer.dwOSVersionInfoSize = sizeof(gOSVer);
	//GetVersionEx(&gOSVer);
	if (IsWin6())
	{
		user._ChangeWindowMessageFilter = (USER::ChangeWindowMessageFilter_t)GetProcAddress(mh_User32, "ChangeWindowMessageFilter");
		if (user._ChangeWindowMessageFilter)
		{
			lbDbg = user._ChangeWindowMessageFilter(WM_DWMSENDICONICTHUMBNAIL, MSGFLT_ADD);
			lbDbg = user._ChangeWindowMessageFilter(WM_DWMSENDICONICLIVEPREVIEWBITMAP, MSGFLT_ADD);
			UNREFERENCED_PARAMETER(lbDbg);
		}

		mh_DwmApi = LoadLibrary(_T("dwmapi.dll"));
		if (mh_DwmApi)
		{
			// Vista+
			dwm._DwmIsCompositionEnabled = (DWM::DwmIsCompositionEnabled_t)GetProcAddress(mh_DwmApi, "DwmIsCompositionEnabled");
			dwm._DwmSetWindowAttribute = (DWM::DwmSetWindowAttribute_t)GetProcAddress(mh_DwmApi, "DwmSetWindowAttribute");
			dwm._DwmGetWindowAttribute = (DWM::DwmGetWindowAttribute_t)GetProcAddress(mh_DwmApi, "DwmGetWindowAttribute");
			dwm._DwmExtendFrameIntoClientArea = (DWM::DwmExtendFrameIntoClientArea_t)GetProcAddress(mh_DwmApi, "DwmExtendFrameIntoClientArea");
			dwm._DwmDefWindowProc = (DWM::DwmDefWindowProc_t)GetProcAddress(mh_DwmApi, "DwmDefWindowProc");
			dwm._DwmSetIconicThumbnail = (DWM::DwmSetIconicThumbnail_t)GetProcAddress(mh_DwmApi, "DwmSetIconicThumbnail");
			dwm._DwmSetIconicLivePreviewBitmap = (DWM::DwmSetIconicLivePreviewBitmap_t)GetProcAddress(mh_DwmApi, "DwmSetIconicLivePreviewBitmap");
			dwm._DwmInvalidateIconicBitmaps = (DWM::DwmInvalidateIconicBitmaps_t)GetProcAddress(mh_DwmApi, "DwmInvalidateIconicBitmaps");
			dwm._DwmEnableBlurBehindWindow = (DWM::DwmEnableBlurBehindWindow_t)GetProcAddress(mh_DwmApi, "DwmEnableBlurBehindWindow");

			mb_DwmAllowed = (dwm._DwmIsCompositionEnabled != NULL)
				&& (dwm._DwmGetWindowAttribute != NULL) && (dwm._DwmSetWindowAttribute != NULL)
				&& (dwm._DwmExtendFrameIntoClientArea != NULL)
				&& (dwm._DwmDefWindowProc != NULL);
			if (mb_DwmAllowed)
				mb_EnableGlass = true;
		}
	}

	if (gOSVer.dwMajorVersion >= 6 || (gOSVer.dwMajorVersion == 5 && gOSVer.dwMinorVersion >= 1))
	{
		mh_UxTheme = LoadLibrary(_T("UxTheme.dll"));
		if (mh_UxTheme)
		{
			// XP+
			ux._IsAppThemed = (UX::AppThemed_t)GetProcAddress(mh_UxTheme, "IsAppThemed");
			ux._IsThemeActive = (UX::AppThemed_t)GetProcAddress(mh_UxTheme, "IsThemeActive");
			ux._OpenThemeData = (UX::OpenThemeData_t)GetProcAddress(mh_UxTheme, "OpenThemeData");
			ux._CloseThemeData = (UX::CloseThemeData_t)GetProcAddress(mh_UxTheme, "CloseThemeData");
			ux._DrawThemeBackground = (UX::DrawThemeBackground_t)GetProcAddress(mh_UxTheme, "DrawThemeBackground");
			ux._DrawThemeEdge = (UX::DrawThemeEdge_t)GetProcAddress(mh_UxTheme, "DrawThemeEdge");
			ux._GetThemeMargins = (UX::GetThemeMargins_t)GetProcAddress(mh_UxTheme, "GetThemeMargins");
			ux._GetThemePartSize = (UX::GetThemePartSize_t)GetProcAddress(mh_UxTheme, "GetThemePartSize");
			ux._GetThemePosition = (UX::GetThemePosition_t)GetProcAddress(mh_UxTheme, "GetThemePosition");
			ux._GetThemeSysSize = (UX::GetThemeSysSize_t)GetProcAddress(mh_UxTheme, "GetThemeSysSize");
			ux._GetThemeBackgroundContentRect = (UX::GetThemeBackgroundContentRect_t)GetProcAddress(mh_UxTheme, "GetThemeBackgroundContentRect");
			ux._SetThemeAppProperties = (UX::SetThemeAppProperties_t)GetProcAddress(mh_UxTheme, "SetThemeAppProperties");
			// Vista+
			ux._BufferedPaintInit = (UX::BufferedPaintInit_t)GetProcAddress(mh_UxTheme, "BufferedPaintInit");
			ux._BufferedPaintUnInit = (UX::BufferedPaintInit_t)GetProcAddress(mh_UxTheme, "BufferedPaintUnInit");
			ux._BeginBufferedPaint = (UX::BeginBufferedPaint_t)GetProcAddress(mh_UxTheme, "BeginBufferedPaint");
			ux._BufferedPaintSetAlpha = (UX::BufferedPaintSetAlpha_t)GetProcAddress(mh_UxTheme, "BufferedPaintSetAlpha");
			ux._EndBufferedPaint = (UX::EndBufferedPaint_t)GetProcAddress(mh_UxTheme, "EndBufferedPaint");
			ux._DrawThemeTextEx = (UX::DrawThemeTextEx_t)GetProcAddress(mh_UxTheme, "DrawThemeTextEx");
			ux._SetWindowTheme = (UX::SetWindowTheme_t)GetProcAddress(mh_UxTheme, "SetWindowTheme");

			mb_ThemeAllowed = (ux._IsAppThemed != NULL) && (ux._IsThemeActive != NULL);
			if (mb_ThemeAllowed)
			{
				mb_EnableTheming = true;
				if (ux._BufferedPaintInit && ux._BufferedPaintUnInit)
				{
					HRESULT hr = ux._BufferedPaintInit();
					mb_BufferedAllowed = SUCCEEDED(hr);
				}
			}
		}
	}

	if (IsWin10())
	{
		user._AdjustWindowRectExForDpi = (USER::AdjustWindowRectExForDpi_t)GetProcAddress(mh_User32, "AdjustWindowRectExForDpi");
	}
}
コード例 #15
0
ファイル: mounter.c プロジェクト: nmlgc/dokany
static VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv)
{
	DWORD			eventNo;
	HANDLE			pipe, device;
	HANDLE			eventConnect, eventUnmount;
	HANDLE			eventArray[3];
	DOKAN_CONTROL	control, unmount;
	OVERLAPPED		ov, driver;
	ULONG			returnedBytes;
	EVENT_CONTEXT	eventContext;
	SECURITY_ATTRIBUTES sa;

	UNREFERENCED_PARAMETER(dwArgc);
	UNREFERENCED_PARAMETER(lpszArgv);

    InitializeCriticalSectionAndSpinCount(&g_CriticalSection, 4000);
	InitializeListHead(&g_MountList);

	g_StatusHandle = RegisterServiceCtrlHandlerEx(L"DokanMounter", HandlerEx, NULL);

	// extend completion time
	g_ServiceStatus.dwServiceType				= SERVICE_WIN32_OWN_PROCESS;
	g_ServiceStatus.dwWin32ExitCode				= NO_ERROR;
	g_ServiceStatus.dwControlsAccepted			= SERVICE_ACCEPT_STOP;
	g_ServiceStatus.dwServiceSpecificExitCode	= 0;
	g_ServiceStatus.dwWaitHint					= 30000;
	g_ServiceStatus.dwCheckPoint				= 1;
	g_ServiceStatus.dwCurrentState				= SERVICE_START_PENDING;
	SetServiceStatus(g_StatusHandle, &g_ServiceStatus);

	BuildSecurityAttributes(&sa);

	pipe = CreateNamedPipe(DOKAN_CONTROL_PIPE,
		PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 
		PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
		1, sizeof(control), sizeof(control), 1000, &sa);

	if (pipe == INVALID_HANDLE_VALUE) {
		// TODO: should do something
		DbgPrintW(L"DokanMounter: failed to create named pipe: %d\n", GetLastError());
	}

	device = CreateFile(
				DOKAN_GLOBAL_DEVICE_NAME,			// lpFileName
				GENERIC_READ | GENERIC_WRITE,       // dwDesiredAccess
				FILE_SHARE_READ | FILE_SHARE_WRITE, // dwShareMode
				NULL,                               // lpSecurityAttributes
				OPEN_EXISTING,                      // dwCreationDistribution
				FILE_FLAG_OVERLAPPED,               // dwFlagsAndAttributes
				NULL                                // hTemplateFile
			);
	
	if (device == INVALID_HANDLE_VALUE) {
		// TODO: should do something
		DbgPrintW(L"DokanMounter: failed to open device: %d\n", GetLastError());
	}

	eventConnect = CreateEvent(NULL, FALSE, FALSE, NULL);
	eventUnmount = CreateEvent(NULL, FALSE, FALSE, NULL);
	g_EventControl = CreateEvent(NULL, TRUE, FALSE, NULL);

	g_ServiceStatus.dwWaitHint     = 0;
	g_ServiceStatus.dwCheckPoint   = 0;
	g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
	SetServiceStatus(g_StatusHandle, &g_ServiceStatus);

	for (;;) {
		ZeroMemory(&ov, sizeof(OVERLAPPED));
		ZeroMemory(&driver, sizeof(OVERLAPPED));
		ZeroMemory(&eventContext, sizeof(EVENT_CONTEXT));

		ov.hEvent = eventConnect;
		driver.hEvent = eventUnmount;

		ConnectNamedPipe(pipe, &ov);
		if (!DeviceIoControl(device, IOCTL_SERVICE_WAIT, NULL, 0,
			&eventContext, sizeof(EVENT_CONTEXT), NULL, &driver)) {
			DWORD error = GetLastError();
			if (error != 997) {
				DbgPrintW(L"DokanMounter: DeviceIoControl error: %d\n", error);
			}
		}

		eventArray[0] = eventConnect;
		eventArray[1] = eventUnmount;
		eventArray[2] = g_EventControl;

		eventNo = WaitForMultipleObjects(3, eventArray, FALSE, INFINITE) - WAIT_OBJECT_0;

		DbgPrintW(L"DokanMounter: get an event\n");

		if (eventNo == 0) {

			DWORD result = 0;

			ZeroMemory(&control, sizeof(control));
			if (ReadFile(pipe, &control, sizeof(control), &result, NULL)) {
				DokanControl(&control);
				WriteFile(pipe, &control, sizeof(control), &result, NULL);
			}
			FlushFileBuffers(pipe);
			DisconnectNamedPipe(pipe);
		
		} else if (eventNo == 1) {

			if (GetOverlappedResult(device, &driver, &returnedBytes, FALSE)) {
				if (returnedBytes == sizeof(EVENT_CONTEXT)) {
					DbgPrintW(L"DokanMounter: Unmount\n");

					ZeroMemory(&unmount, sizeof(DOKAN_CONTROL));
					unmount.Type = DOKAN_CONTROL_UNMOUNT;
					unmount.Option = eventContext.Operation.Unmount.Option;
					wcscpy_s(unmount.DeviceName, sizeof(unmount.DeviceName) / sizeof(WCHAR),
						eventContext.Operation.Unmount.DeviceName);
					DokanControl(&unmount);
				} else {
					DbgPrintW(L"DokanMounter: Unmount error\n", control.Type);
				}
			}

		} else if (eventNo == 2) {
			DbgPrintW(L"DokanMounter: stop mounter service\n");
			g_ServiceStatus.dwWaitHint     = 0;
			g_ServiceStatus.dwCheckPoint   = 0;
			g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			SetServiceStatus(g_StatusHandle, &g_ServiceStatus);

			break;
		}
		else
			break;
	}


	CloseHandle(pipe);
	CloseHandle(eventConnect);
	CloseHandle(g_EventControl);
	CloseHandle(device);
	CloseHandle(eventUnmount);

	DeleteCriticalSection(&g_CriticalSection);

	return;
}
コード例 #16
0
ファイル: device.cpp プロジェクト: kk1987/crostrackpad3-elan
NTSTATUS
OnPrepareHardware(
_In_  WDFDEVICE     FxDevice,
_In_  WDFCMRESLIST  FxResourcesRaw,
_In_  WDFCMRESLIST  FxResourcesTranslated
)
/*++

Routine Description:

This routine caches the SPB resource connection ID.

Arguments:

FxDevice - a handle to the framework device object
FxResourcesRaw - list of translated hardware resources that
the PnP manager has assigned to the device
FxResourcesTranslated - list of raw hardware resources that
the PnP manager has assigned to the device

Return Value:

Status

--*/
{
	FuncEntry(TRACE_FLAG_WDFLOADING);

	PDEVICE_CONTEXT pDevice = GetDeviceContext(FxDevice);
	BOOLEAN fSpbResourceFound = FALSE;
	NTSTATUS status = STATUS_INSUFFICIENT_RESOURCES;

	UNREFERENCED_PARAMETER(FxResourcesRaw);

	//
	// Parse the peripheral's resources.
	//

	ULONG resourceCount = WdfCmResourceListGetCount(FxResourcesTranslated);

	for (ULONG i = 0; i < resourceCount; i++)
	{
		PCM_PARTIAL_RESOURCE_DESCRIPTOR pDescriptor;
		UCHAR Class;
		UCHAR Type;

		pDescriptor = WdfCmResourceListGetDescriptor(
			FxResourcesTranslated, i);

		switch (pDescriptor->Type)
		{
		case CmResourceTypeConnection:
			//
			// Look for I2C or SPI resource and save connection ID.
			//
			Class = pDescriptor->u.Connection.Class;
			Type = pDescriptor->u.Connection.Type;
			if (Class == CM_RESOURCE_CONNECTION_CLASS_SERIAL &&
				Type == CM_RESOURCE_CONNECTION_TYPE_SERIAL_I2C)
			{
				if (fSpbResourceFound == FALSE)
				{
					status = STATUS_SUCCESS;
					pDevice->I2CContext.I2cResHubId.LowPart = pDescriptor->u.Connection.IdLowPart;
					pDevice->I2CContext.I2cResHubId.HighPart = pDescriptor->u.Connection.IdHighPart;
					fSpbResourceFound = TRUE;
					Trace(
						TRACE_LEVEL_INFORMATION,
						TRACE_FLAG_WDFLOADING,
						"SPB resource found with ID=0x%llx",
						pDevice->I2CContext.I2cResHubId.QuadPart);
				}
				else
				{
					Trace(
						TRACE_LEVEL_WARNING,
						TRACE_FLAG_WDFLOADING,
						"Duplicate SPB resource found with ID=0x%llx",
						pDevice->I2CContext.I2cResHubId.QuadPart);
				}
			}
			break;
		default:
			//
			// Ignoring all other resource types.
			//
			break;
		}
	}

	//
	// An SPB resource is required.
	//

	if (fSpbResourceFound == FALSE)
	{
		status = STATUS_NOT_FOUND;
		Trace(
			TRACE_LEVEL_ERROR,
			TRACE_FLAG_WDFLOADING,
			"SPB resource not found - %!STATUS!",
			status);
	}

	status = SpbTargetInitialize(FxDevice, &pDevice->I2CContext);
	if (!NT_SUCCESS(status))
	{
		Trace(
			TRACE_LEVEL_ERROR,
			TRACE_FLAG_WDFLOADING,
			"Error in Spb initialization - %!STATUS!",
			status);

		return status;
	}

	FuncExit(TRACE_FLAG_WDFLOADING);

	return status;
}
コード例 #17
0
// Program entry point function.
int APIENTRY wWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow) {
  UNREFERENCED_PARAMETER(hPrevInstance);
  UNREFERENCED_PARAMETER(lpCmdLine);

  g_appStartupTime = timeGetTime();

  CefMainArgs main_args(hInstance);
  CefRefPtr<ClientApp> app(new ClientApp);

  // Execute the secondary process, if any.
  int exit_code = CefExecuteProcess(main_args, app.get());
  if (exit_code >= 0)
    return exit_code;

  // Retrieve the current working directory.
  if (_getcwd(szWorkingDir, MAX_PATH) == NULL)
    szWorkingDir[0] = 0;

  // Parse command line arguments. The passed in values are ignored on Windows.
  AppInitCommandLine(0, NULL);

  CefSettings settings;

  // Populate the settings based on command line arguments.
  AppGetSettings(settings, app);

  // Check command
  if (CefString(&settings.cache_path).length() == 0) {
	  CefString(&settings.cache_path) = AppGetCachePath();
  }

  // Initialize CEF.
  CefInitialize(main_args, settings, app.get());

  HACCEL hAccelTable;

  // Initialize global strings
  LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  LoadString(hInstance, IDC_CEFCLIENT, szWindowClass, MAX_LOADSTRING);
  MyRegisterClass(hInstance, settings.locale);
 

  // If the shift key is not pressed, look for the index.html file 
  if (GetAsyncKeyState(VK_SHIFT) == 0) {
    // Get the full pathname for the app. We look for the index.html
    // file relative to this location.
    wchar_t appPath[MAX_PATH];
    wchar_t *pathRoot;
    GetModuleFileName(NULL, appPath, MAX_PATH);

    // Strip the .exe filename (and preceding "\") from the appPath
    // and store in pathRoot
    pathRoot = wcsrchr(appPath, '\\');

    // Look for .\dev\src\index.html first
    wcscpy(pathRoot, L"\\dev\\src\\index.html");

    // If the file exists, use it
    if (GetFileAttributes(appPath) != INVALID_FILE_ATTRIBUTES) {
      wcscpy(szInitialUrl, appPath);
    }

    if (!wcslen(szInitialUrl)) {
      // Look for .\www\index.html next
      wcscpy(pathRoot, L"\\www\\index.html");
      if (GetFileAttributes(appPath) != INVALID_FILE_ATTRIBUTES) {
        wcscpy(szInitialUrl, appPath);
      }
    }
  }

  if (!wcslen(szInitialUrl)) {
      // If we got here, either the startup file couldn't be found, or the user pressed the
      // shift key while launching. Prompt to select the index.html file.
      OPENFILENAME ofn = {0};
      ofn.lStructSize = sizeof(ofn);
      ofn.lpstrFile = szInitialUrl;
      ofn.nMaxFile = MAX_PATH;
      ofn.lpstrFilter = L"Web Files\0*.htm;*.html\0\0";
      ofn.lpstrTitle = L"Please select the " APP_NAME L" index.html file.";
      ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER;

      if (!GetOpenFileName(&ofn)) {
        // User cancelled, exit the app
        CefShutdown();
        return 0;
      }
  }

  // Perform application initialization
  if (!InitInstance (hInstance, nCmdShow))
    return FALSE;

  // Temporary localization hack. Default to English. Check for French.
  DWORD menuId = IDC_CEFCLIENT;
  if (settings.locale.str && (settings.locale.length > 0) &&
      (CefString(settings.locale.str) == CefString("fr-FR")))
  {
	  menuId = IDC_CEFCLIENT_FR;
  }

  hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(menuId));

  int result = 0;

  if (!settings.multi_threaded_message_loop) {
    // Run the CEF message loop. This function will block until the application
    // recieves a WM_QUIT message.
    CefRunMessageLoop();
  } else {
    MSG msg;

    // Run the application message loop.
    while (GetMessage(&msg, NULL, 0, 0)) {
      if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
      }
    }

    result = static_cast<int>(msg.wParam);
  }

  OnBeforeShutdown();

  // Shut down CEF.
  CefShutdown();

  return result;
}
コード例 #18
0
ファイル: device.cpp プロジェクト: kk1987/crostrackpad3-elan
VOID
OnIoDeviceControl(
_In_  WDFQUEUE    FxQueue,
_In_  WDFREQUEST  FxRequest,
_In_  size_t      OutputBufferLength,
_In_  size_t      InputBufferLength,
_In_  ULONG       IoControlCode
)
/*++
Routine Description:

This event is called when the framework receives IRP_MJ_DEVICE_CONTROL
requests from the system.

Arguments:

FxQueue - Handle to the framework queue object that is associated
with the I/O request.
FxRequest - Handle to a framework request object.
OutputBufferLength - length of the request's output buffer,
if an output buffer is available.
InputBufferLength - length of the request's input buffer,
if an input buffer is available.
IoControlCode - the driver-defined or system-defined I/O control code
(IOCTL) that is associated with the request.

Return Value:

VOID

--*/
{
	FuncEntry(TRACE_FLAG_SPBAPI);

	WDFDEVICE device;
	PDEVICE_CONTEXT pDevice;
	BOOLEAN fSync = FALSE;
	NTSTATUS status = STATUS_SUCCESS;
	UNREFERENCED_PARAMETER(OutputBufferLength);
	UNREFERENCED_PARAMETER(InputBufferLength);

	device = WdfIoQueueGetDevice(FxQueue);
	pDevice = GetDeviceContext(device);

	ElanPrint(
		DEBUG_LEVEL_INFO, DBG_IOCTL,
		"DeviceIoControl request %p received with IOCTL=%lu",
		FxRequest,
		IoControlCode);
	ElanPrint(DEBUG_LEVEL_INFO, DBG_IOCTL,
		"%s, Queue:0x%p, Request:0x%p\n",
		DbgHidInternalIoctlString(IoControlCode),
		FxQueue,
		FxRequest
		);

	//
	// Translate the test IOCTL into the appropriate 
	// SPB API method.  Open and close are completed 
	// synchronously.
	//

	switch (IoControlCode)
	{
	case IOCTL_HID_GET_DEVICE_DESCRIPTOR:
		//
		// Retrieves the device's HID descriptor.
		//
		status = ElanGetHidDescriptor(device, FxRequest);
		fSync = TRUE;
		break;

	case IOCTL_HID_GET_DEVICE_ATTRIBUTES:
		//
		//Retrieves a device's attributes in a HID_DEVICE_ATTRIBUTES structure.
		//
		status = ElanGetDeviceAttributes(FxRequest);
		fSync = TRUE;
		break;

	case IOCTL_HID_GET_REPORT_DESCRIPTOR:
		//
		//Obtains the report descriptor for the HID device.
		//
		status = ElanGetReportDescriptor(device, FxRequest);
		fSync = TRUE;
		break;

	case IOCTL_HID_GET_STRING:
		//
		// Requests that the HID minidriver retrieve a human-readable string
		// for either the manufacturer ID, the product ID, or the serial number
		// from the string descriptor of the device. The minidriver must send
		// a Get String Descriptor request to the device, in order to retrieve
		// the string descriptor, then it must extract the string at the
		// appropriate index from the string descriptor and return it in the
		// output buffer indicated by the IRP. Before sending the Get String
		// Descriptor request, the minidriver must retrieve the appropriate
		// index for the manufacturer ID, the product ID or the serial number
		// from the device extension of a top level collection associated with
		// the device.
		//
		status = ElanGetString(FxRequest);
		fSync = TRUE;
		break;

	case IOCTL_HID_WRITE_REPORT:
	case IOCTL_HID_SET_OUTPUT_REPORT:
		//
		//Transmits a class driver-supplied report to the device.
		//
		status = BOOTTRACKPAD(pDevice);
		if (!NT_SUCCESS(status)){
			ElanPrint(DBG_IOCTL, DEBUG_LEVEL_ERROR, "Error booting Elan device!\n");
		}
		fSync = TRUE;
		break;

	case IOCTL_HID_READ_REPORT:
	case IOCTL_HID_GET_INPUT_REPORT:
		//
		// Returns a report from the device into a class driver-supplied buffer.
		// 
		status = ElanReadReport(pDevice, FxRequest, &fSync);
		break;

	case IOCTL_HID_GET_FEATURE:
		//
		// returns a feature report associated with a top-level collection
		//
		status = ElanGetFeature(pDevice, FxRequest, &fSync);
		break;
	case IOCTL_HID_ACTIVATE_DEVICE:
		//
		// Makes the device ready for I/O operations.
		//
	case IOCTL_HID_DEACTIVATE_DEVICE:
		//
		// Causes the device to cease operations and terminate all outstanding
		// I/O requests.
		//
	default:
		fSync = TRUE;
		status = STATUS_NOT_SUPPORTED;
		ElanPrint(
			DEBUG_LEVEL_INFO, DBG_IOCTL,
			"Request %p received with unexpected IOCTL=%lu",
			FxRequest,
			IoControlCode);
	}

	//
	// Complete the request if necessary.
	//

	if (fSync)
	{
		ElanPrint(DEBUG_LEVEL_INFO, DBG_IOCTL,
			"%s completed, Queue:0x%p, Request:0x%p\n",
			DbgHidInternalIoctlString(IoControlCode),
			FxQueue,
			FxRequest
			);

		WdfRequestComplete(FxRequest, status);
	}
	else {
		ElanPrint(DEBUG_LEVEL_INFO, DBG_IOCTL,
			"%s deferred, Queue:0x%p, Request:0x%p\n",
			DbgHidInternalIoctlString(IoControlCode),
			FxQueue,
			FxRequest
			);
	}

	FuncExit(TRACE_FLAG_SPBAPI);
}
コード例 #19
0
ファイル: BasePin.cpp プロジェクト: EnoroF/easygamelibs
HRESULT
CBasePin::CompleteConnect(IPin *pReceivePin)
{
	UNREFERENCED_PARAMETER(pReceivePin);
	return NOERROR;
}
コード例 #20
0
ファイル: ByteStream.cpp プロジェクト: johnjohnsp1/AxHell
HRESULT STDMETHODCALLTYPE CByteStream::Load(IStream *pStm)
{
    UNREFERENCED_PARAMETER(pStm);

    return E_NOTIMPL;
}
コード例 #21
0
ファイル: BasePin.cpp プロジェクト: EnoroF/easygamelibs
HRESULT
CBasePin::Run(REFERENCE_TIME tStart)
{
	UNREFERENCED_PARAMETER(tStart);
	return NOERROR;
}
コード例 #22
0
ファイル: keyboard.c プロジェクト: Strongc/reactos
static VOID NTAPI
i8042PowerWorkItem(
	IN PDEVICE_OBJECT DeviceObject,
	IN PVOID Context)
{
	PI8042_KEYBOARD_EXTENSION DeviceExtension;
	PIRP WaitingIrp;
	NTSTATUS Status;

	UNREFERENCED_PARAMETER(DeviceObject);

	__analysis_assume(Context != NULL);
	DeviceExtension = Context;

	/* See http://blogs.msdn.com/doronh/archive/2006/09/08/746961.aspx */

	/* Register GUID_DEVICE_SYS_BUTTON interface and report capability */
	if (DeviceExtension->NewCaps != DeviceExtension->ReportedCaps)
	{
		WaitingIrp = InterlockedExchangePointer((PVOID)&DeviceExtension->PowerIrp, NULL);
		if (WaitingIrp)
		{
			/* Cancel the current power irp, as capability changed */
			WaitingIrp->IoStatus.Status = STATUS_UNSUCCESSFUL;
			WaitingIrp->IoStatus.Information = sizeof(ULONG);
			IoCompleteRequest(WaitingIrp, IO_NO_INCREMENT);
		}

		if (DeviceExtension->PowerInterfaceName.MaximumLength == 0)
		{
			/* We have never registred this interface ; do it */
			Status = IoRegisterDeviceInterface(
				DeviceExtension->Common.Pdo,
				&GUID_DEVICE_SYS_BUTTON,
				NULL,
				&DeviceExtension->PowerInterfaceName);
			if (!NT_SUCCESS(Status))
			{
				/* We can't do more yet, ignore the keypress... */
				WARN_(I8042PRT, "IoRegisterDeviceInterface(GUID_DEVICE_SYS_BUTTON) failed with status 0x%08lx\n",
					Status);
				DeviceExtension->PowerInterfaceName.MaximumLength = 0;
				return;
			}
		}
		else
		{
			/* Disable the interface. Once activated again, capabilities would be asked again */
			Status = IoSetDeviceInterfaceState(
				&DeviceExtension->PowerInterfaceName,
				FALSE);
			if (!NT_SUCCESS(Status))
			{
				/* Ignore the key press... */
				WARN_(I8042PRT, "Disabling interface %wZ failed with status 0x%08lx\n",
					&DeviceExtension->PowerInterfaceName, Status);
				return;
			}
		}
		/* Enable the interface. This leads to receving a IOCTL_GET_SYS_BUTTON_CAPS,
		 * so we can report new capability */
		Status = IoSetDeviceInterfaceState(
				&DeviceExtension->PowerInterfaceName,
				TRUE);
		if (!NT_SUCCESS(Status))
		{
			/* Ignore the key press... */
			WARN_(I8042PRT, "Enabling interface %wZ failed with status 0x%08lx\n",
					&DeviceExtension->PowerInterfaceName, Status);
			return;
		}
	}

	/* Directly complete the IOCTL_GET_SYS_BUTTON_EVENT Irp (if any) */
	WaitingIrp = InterlockedExchangePointer((PVOID)&DeviceExtension->PowerIrp, NULL);
	if (WaitingIrp)
	{
		PULONG pEvent = (PULONG)WaitingIrp->AssociatedIrp.SystemBuffer;

		WaitingIrp->IoStatus.Status = STATUS_SUCCESS;
		WaitingIrp->IoStatus.Information = sizeof(ULONG);
		*pEvent = InterlockedExchange((PLONG)&DeviceExtension->LastPowerKey, 0);
		IoCompleteRequest(WaitingIrp, IO_NO_INCREMENT);
	}
}
コード例 #23
0
ファイル: intrface.cpp プロジェクト: gvsurenderreddy/OVD
HRESULT __stdcall IOemPS::EnablePDEV(
    PDEVOBJ         pdevobj,
    __in PWSTR      pPrinterName,
    ULONG           cPatterns,
    HSURF          *phsurfPatterns,
    ULONG           cjGdiInfo,
    GDIINFO        *pGdiInfo,
    ULONG           cjDevInfo,
    DEVINFO        *pDevInfo,
    DRVENABLEDATA  *pded,
    OUT PDEVOEM    *pDevOem)
{
    UNREFERENCED_PARAMETER(pdevobj);
    UNREFERENCED_PARAMETER(pPrinterName);
    UNREFERENCED_PARAMETER(cPatterns);
    UNREFERENCED_PARAMETER(phsurfPatterns);
    UNREFERENCED_PARAMETER(cjGdiInfo);
    UNREFERENCED_PARAMETER(pGdiInfo);
    UNREFERENCED_PARAMETER(cjDevInfo);
    UNREFERENCED_PARAMETER(pDevInfo);

    VERBOSE("IOemPS::EnablePDEV() entry.\r\n");

    POEMPDEV    poempdev;
    INT         i, j;
    DWORD       dwDDIIndex;
    PDRVFN      pdrvfn;

    //
    // Allocate the OEMDev
    //
    poempdev = new OEMPDEV;
    if (NULL == poempdev)
    {
        return E_FAIL;
    }

    //
    // Fill in OEMDEV
    //

    for (i = 0; i < MAX_DDI_HOOKS; i++)
    {
        //
        // search through PS's hooks and locate the function ptr
        //
        dwDDIIndex = OEMHookFuncs[i].iFunc;
        for (j = pded->c, pdrvfn = pded->pdrvfn; j > 0; j--, pdrvfn++)
        {
            if (dwDDIIndex == pdrvfn->iFunc)
            {
                poempdev->pfnPS[i] = pdrvfn->pfn;
                break;
            }
        }
        if (j == 0)
        {
            //
            // Didn't find the hook. This could mean PS doesn't hook this DDI but allows OEMs to hook it out.
            //
            poempdev->pfnPS[i] = NULL;
        }

    }

    poempdev->spoolPSFileName = NULL;
    *pDevOem = (POEMPDEV) poempdev;

    return S_OK;
}
コード例 #24
0
ファイル: keyboard.c プロジェクト: Strongc/reactos
BOOLEAN NTAPI
i8042KbdInterruptService(
	IN PKINTERRUPT Interrupt,
	PVOID Context)
{
	PI8042_KEYBOARD_EXTENSION DeviceExtension;
	PPORT_DEVICE_EXTENSION PortDeviceExtension;
	PKEYBOARD_INPUT_DATA InputData;
	ULONG Counter;
	UCHAR PortStatus = 0, Output = 0;
	BOOLEAN ToReturn = FALSE;
	NTSTATUS Status;

	UNREFERENCED_PARAMETER(Interrupt);

	__analysis_assume(Context != NULL);
	DeviceExtension = Context;
	PortDeviceExtension = DeviceExtension->Common.PortDeviceExtension;
	InputData = DeviceExtension->KeyboardBuffer + DeviceExtension->KeysInBuffer;
	Counter = PortDeviceExtension->Settings.PollStatusIterations;

	while (Counter)
	{
		Status = i8042ReadStatus(PortDeviceExtension, &PortStatus);
		if (!NT_SUCCESS(Status))
		{
			WARN_(I8042PRT, "i8042ReadStatus() failed with status 0x%08lx\n", Status);
			return FALSE;
		}
		Status = i8042ReadKeyboardData(PortDeviceExtension, &Output);
		if (NT_SUCCESS(Status))
			break;
		KeStallExecutionProcessor(1);
		Counter--;
	}
	if (Counter == 0)
	{
		WARN_(I8042PRT, "Spurious i8042 keyboard interrupt\n");
		return FALSE;
	}

	INFO_(I8042PRT, "Got: 0x%02x\n", Output);

	if (PortDeviceExtension->Settings.CrashOnCtrlScroll)
	{
		/* Test for CTRL + SCROLL LOCK twice */
		static const UCHAR ScanCodes[] = { 0x1d, 0x46, 0xc6, 0x46, 0 };

		if (Output == ScanCodes[DeviceExtension->ComboPosition])
		{
			DeviceExtension->ComboPosition++;
			if (ScanCodes[DeviceExtension->ComboPosition] == 0)
				KeBugCheck(MANUALLY_INITIATED_CRASH);
		}
		else if (Output == 0xfa)
		{
		    /* Ignore ACK */
		}
		else if (Output == ScanCodes[0])
			DeviceExtension->ComboPosition = 1;
		else
			DeviceExtension->ComboPosition = 0;

		/* Test for TAB + key combination */
		if (InputData->MakeCode == 0x0F)
			DeviceExtension->TabPressed = !(InputData->Flags & KEY_BREAK);
		else if (DeviceExtension->TabPressed)
		{
			DeviceExtension->TabPressed = FALSE;

            /* Check which action to do */
            if (InputData->MakeCode == 0x25)
            {
                /* k - Breakpoint */
                DbgBreakPointWithStatus(DBG_STATUS_SYSRQ);
            }
            else if (InputData->MakeCode == 0x30)
            {
                /* b - Bugcheck */
                KeBugCheck(MANUALLY_INITIATED_CRASH);
            }
#if defined(KDBG)
            else
            {
			    /* Send request to the kernel debugger.
			     * Unknown requests will be ignored. */
			    KdSystemDebugControl(' soR',
			                         (PVOID)(ULONG_PTR)InputData->MakeCode,
			                         0,
			                         NULL,
			                         0,
			                         NULL,
			                         KernelMode);
            }
#endif
		}
	}

	if (i8042KbdCallIsrHook(DeviceExtension, PortStatus, Output, &ToReturn))
		return ToReturn;

	if (i8042PacketIsr(PortDeviceExtension, Output))
	{
		if (PortDeviceExtension->PacketComplete)
		{
			TRACE_(I8042PRT, "Packet complete\n");
			KeInsertQueueDpc(&DeviceExtension->DpcKeyboard, NULL, NULL);
		}
		TRACE_(I8042PRT, "Irq eaten by packet\n");
		return TRUE;
	}

	TRACE_(I8042PRT, "Irq is keyboard input\n");

	if (DeviceExtension->KeyboardScanState == Normal)
	{
		switch (Output)
		{
			case 0xe0:
				DeviceExtension->KeyboardScanState = GotE0;
				return TRUE;
			case 0xe1:
				DeviceExtension->KeyboardScanState = GotE1;
				return TRUE;
			default:
				break;
		}
	}

	/* Update InputData */
	InputData->Flags = 0;
	switch (DeviceExtension->KeyboardScanState)
	{
		case GotE0:
			InputData->Flags |= KEY_E0;
			break;
		case GotE1:
			InputData->Flags |= KEY_E1;
			break;
		default:
			break;
	}
	DeviceExtension->KeyboardScanState = Normal;
	if (Output & 0x80)
		InputData->Flags |= KEY_BREAK;
	else
		InputData->Flags |= KEY_MAKE;
	InputData->MakeCode = Output & 0x7f;
	InputData->Reserved = 0;

	DeviceExtension->KeyboardHook.QueueKeyboardPacket(DeviceExtension->KeyboardHook.CallContext);

	return TRUE;
}
コード例 #25
0
static int NaClDescInvalidExternalize(struct NaClDesc          *vself,
                                      struct NaClDescXferState *xfer) {
  UNREFERENCED_PARAMETER(vself);
  UNREFERENCED_PARAMETER(xfer);
  return 0;
}
コード例 #26
0
void NaClDeallocAddrRange(uintptr_t addr,
                          size_t    len) {
  UNREFERENCED_PARAMETER(addr);
  UNREFERENCED_PARAMETER(len);
  return;
}
コード例 #27
0
NTSTATUS
SimSensorDriverDeviceAdd (
    WDFDRIVER Driver,
    PWDFDEVICE_INIT DeviceInit
    )

/*++

Routine Description:

    EvtDriverDeviceAdd is called by the framework in response to AddDevice call
    from the PnP manager. A WDF device object is created and initialized to
    represent a new instance of the battery device.

Arguments:

    Driver - Supplies a handle to the WDF Driver object.

    DeviceInit - Supplies a pointer to a framework-allocated WDFDEVICE_INIT
        structure.

Return Value:

    NTSTATUS

--*/

{

    WDF_OBJECT_ATTRIBUTES DeviceAttributes;
    WDFDEVICE DeviceHandle;
    PFDO_DATA DevExt;
    BOOLEAN LockHeld;
    WDF_IO_QUEUE_CONFIG PendingRequestQueueConfig;
    WDF_PNPPOWER_EVENT_CALLBACKS PnpPowerCallbacks;
    WDFQUEUE Queue;
    WDF_IO_QUEUE_CONFIG QueueConfig;
    NTSTATUS Status;
    WDF_OBJECT_ATTRIBUTES WorkitemAttributes;
    WDF_WORKITEM_CONFIG WorkitemConfig;

    UNREFERENCED_PARAMETER(Driver);

    DebugEnter();
    PAGED_CODE();

    LockHeld = FALSE;

    //
    // Initialize attributes and a context area for the device object.
    //

    WDF_OBJECT_ATTRIBUTES_INIT(&DeviceAttributes);
    WDF_OBJECT_ATTRIBUTES_SET_CONTEXT_TYPE(&DeviceAttributes, FDO_DATA);

    //
    // Initailize power callbacks
    //

    WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&PnpPowerCallbacks);
    PnpPowerCallbacks.EvtDeviceD0Entry = SimSensorDeviceD0Entry;
    PnpPowerCallbacks.EvtDeviceD0Exit = SimSensorDeviceD0Exit;
    PnpPowerCallbacks.EvtDeviceSelfManagedIoSuspend =
        SimSensorSelfManagedIoSuspend;

    WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &PnpPowerCallbacks);

    //
    // Create a framework device object.  This call will in turn create
    // a WDM device object, attach to the lower stack, and set the
    // appropriate flags and attributes.
    //

    Status = WdfDeviceCreate(&DeviceInit, &DeviceAttributes, &DeviceHandle);
    if (!NT_SUCCESS(Status)) {
        DebugPrint(SIMSENSOR_ERROR,
                   "WdfDeviceCreate() Failed. 0x%x\n",
                   Status);

        goto DriverDeviceAddEnd;
    }

    DevExt = GetDeviceExtension(DeviceHandle);

    //
    // Configure a default queue for IO requests. This queue processes requests
    // to read the sensor state.
    //

    WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&QueueConfig,
                                           WdfIoQueueDispatchParallel);

    QueueConfig.EvtIoDeviceControl = SimSensorIoDeviceControl;

    //
    // The system uses IoInternalDeviceControl requests to communicate with the
    // ACPI driver on the device stack. For proper operation of thermal zones,
    // these requests must be forwarded unless the driver knows how to handle
    // them.
    //

    QueueConfig.EvtIoInternalDeviceControl = SimSensorIoInternalDeviceControl;
    Status = WdfIoQueueCreate(DeviceHandle,
                              &QueueConfig,
                              WDF_NO_OBJECT_ATTRIBUTES,
                              &Queue);

    if (!NT_SUCCESS(Status)) {
        DebugPrint(SIMSENSOR_ERROR,
                   "WdfIoQueueCreate() (Default) Failed.  0x%x\n",
                   Status);

        goto DriverDeviceAddEnd;
    }

    //
    // Configure a manual dispatch queue for pending requests. This queue
    // stores requests to read the sensor state which can't be retired
    // immediately.
    //

    WDF_IO_QUEUE_CONFIG_INIT(&PendingRequestQueueConfig,
                             WdfIoQueueDispatchManual);


    Status = WdfIoQueueCreate(DeviceHandle,
                              &PendingRequestQueueConfig,
                              WDF_NO_OBJECT_ATTRIBUTES,
                              &DevExt->PendingRequestQueue);

    PendingRequestQueueConfig.EvtIoStop = SimSensorQueueIoStop;
    if (!NT_SUCCESS(Status)) {
        DebugPrint(SIMSENSOR_ERROR,
                "WdfIoQueueCreate() (Pending) Failed. 0x%x\n",
                Status);

        goto DriverDeviceAddEnd;
    }


    //
    // Configure a workitem to process the simulated interrupt.
    //

    WDF_OBJECT_ATTRIBUTES_INIT(&WorkitemAttributes);
    WorkitemAttributes.ParentObject = DeviceHandle;
    WDF_WORKITEM_CONFIG_INIT(&WorkitemConfig,
                             SimSensorTemperatureInterruptWorker);

    Status = WdfWorkItemCreate(&WorkitemConfig,
                               &WorkitemAttributes,
                               &DevExt->InterruptWorker);

    if (!NT_SUCCESS(Status)) {
        DebugPrint(SIMSENSOR_ERROR,
                   "WdfWorkItemCreate() Failed. 0x%x\n",
                   Status);

        goto DriverDeviceAddEnd;
    }

    //
    // Create the request queue waitlock.
    //

    Status = WdfWaitLockCreate(NULL, &DevExt->QueueLock);
    if (!NT_SUCCESS(Status)) {
        DebugPrint(SIMSENSOR_ERROR,
                   "WdfWaitLockCreate() Failed. Status 0x%x\n",
                   Status);

        goto DriverDeviceAddEnd;
    }

    //
    // Initilize the simulated sensor hardware.
    //

    DevExt->Sensor.LowerBound = 0;
    DevExt->Sensor.UpperBound = (ULONG)-1;
    DevExt->Sensor.Temperature = VIRTUAL_SENSOR_RESET_TEMPERATURE;
    Status = WdfWaitLockCreate(NULL, &DevExt->Sensor.Lock);
    if (!NT_SUCCESS(Status)) {
        DebugPrint(SIMSENSOR_ERROR,
                   "WdfWaitLockCreate() Failed. 0x%x\n",
                   Status);

        goto DriverDeviceAddEnd;
    }

DriverDeviceAddEnd:

    DebugExitStatus(Status);
    return Status;
}
コード例 #28
0
int main(int argc, char* argv[])
{
	int res;
	unsigned char buf[256];
	#define MAX_STR 255
	wchar_t wstr[MAX_STR];
	hid_device *handle;
	int i;

#ifdef WIN32
	UNREFERENCED_PARAMETER(argc);
	UNREFERENCED_PARAMETER(argv);
#endif

	struct hid_device_info *devs, *cur_dev;
	
	devs = hid_enumerate(0x0, 0x0);
	cur_dev = devs;	
	while (cur_dev) {
		printf("Device Found\n  type: %04hx %04hx\n  path: %s\n  serial_number: %ls", cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number);
		printf("\n");
		printf("  Manufacturer: %ls\n", cur_dev->manufacturer_string);
		printf("  Product:      %ls\n", cur_dev->product_string);
		printf("  Release:      %hx\n", cur_dev->release_number);
		printf("  Interface:    %d\n",  cur_dev->interface_number);
		printf("\n");
		cur_dev = cur_dev->next;
	}
	hid_free_enumeration(devs);

	// Set up the command buffer.
	memset(buf,0x00,sizeof(buf));
	buf[0] = 0x01;
	buf[1] = 0x81;
	

	// Open the device using the VID, PID,
	// and optionally the Serial number.
	////handle = hid_open(0x4d8, 0x3f, L"12345");
	// handle = hid_open(0x4d8, 0x3f, NULL);
	handle = hid_open(0x1fc9, 0x003, NULL);
	handle = hid_open(0x1234, 0x006, NULL);
	
	if (!handle) {
		printf("unable to open device\n");
 		return 1;
	}

	// Read the Manufacturer String
	wstr[0] = 0x0000;
	res = hid_get_manufacturer_string(handle, wstr, MAX_STR);
	if (res < 0)
		printf("Unable to read manufacturer string\n");
	printf("Manufacturer String: %ls\n", wstr);

	// Read the Product String
	wstr[0] = 0x0000;
	res = hid_get_product_string(handle, wstr, MAX_STR);
	if (res < 0)
		printf("Unable to read product string\n");
	printf("Product String: %ls\n", wstr);

	// Read the Serial Number String
	wstr[0] = 0x0000;
	res = hid_get_serial_number_string(handle, wstr, MAX_STR);
	if (res < 0)
		printf("Unable to read serial number string\n");
	printf("Serial Number String: (%d) %ls", wstr[0], wstr);
	printf("\n");

	// Read Indexed String 1
	wstr[0] = 0x0000;
	res = hid_get_indexed_string(handle, 1, wstr, MAX_STR);
	if (res < 0)
		printf("Unable to read indexed string 1\n");
	printf("Indexed String 1: %ls\n", wstr);

	// Set the hid_read() function to be non-blocking.
//	hid_set_nonblocking(handle, 1);
	
	// Try to read from the device. There shoud be no
	// data here, but execution should not block.
	res = hid_read(handle, buf, 64);
	//res = hid_read(handle, buf, 17);
	
    printf("res: %d, buf[0]=%d\n", (int)res, (int)buf[0]);
	// Send a Feature Report to the device
	buf[0] = 0x1;
	buf[1] = 0x2;
/*	res = hid_send_feature_report(handle, buf, 3);
	if (res < 0) {
		printf("Unable to send a feature report.\n");
	}

	memset(buf,0,sizeof(buf));
*/

	// Read a Feature Report from the device
	buf[0] = 0x1;
	res = hid_get_feature_report(handle, buf, sizeof(buf));
	if (res < 0) {
		printf("Unable to get a feature report.\n");
		printf("%ls", hid_error(handle));
	}
	else {
		// Print out the returned buffer.
		printf("Feature Report\n   ");
		for (i = 0; i < res; i++)
			printf("%02hhx ", buf[i]);
		printf("\n");
	}

	memset(buf,0,sizeof(buf));
	
	
	buf[0] = 0;
	buf[1] = 0x0;
	for(int j = 0; j<4; j++)
	for(int i=0; i<8; i++)
	{
	  buf[1] = 1<<i; // led
	  buf[2] = i*32;
	  buf[3] = i*32; // servo2
	  
  	  res = hid_write(handle, buf, 65);
	  
	  if (res < 0) {
		printf("Unable to write(): %d\n", i);
		printf("Error: %ls\n", hid_error(handle));
	  }
	 //usleep(200*1000);
	  buf[1] = 0;
	  res = hid_read(handle, buf, sizeof(buf));
	  printf("\nresponse: %d, data=%d %d\n", res, buf[1], buf[2]);
	  // usleep(200*1000);
	}
/*
	// Toggle LED (cmd 0x80). The first byte is the report number (0x1).
	buf[0] = 0x1;
	buf[1] = 0x80;
	res = hid_write(handle, buf, 17);
	if (res < 0) {
		printf("Unable to write()\n");
		printf("Error: %ls\n", hid_error(handle));
	}
	

	// Request state (cmd 0x81). The first byte is the report number (0x1).
	buf[0] = 0x1;
	buf[1] = 0x81;
	hid_write(handle, buf, 17);
	if (res < 0)
		printf("Unable to write() (2)\n");
*/

	// Read requested state. hid_read() has been set to be
	// non-blocking by the call to hid_set_nonblocking() above.
	// This loop demonstrates the non-blocking nature of hid_read().
	res = 0;
	while (res == 0) {
		res = hid_read(handle, buf, sizeof(buf));
		if (res == 0)
			printf("waiting...\n");
		if (res < 0)
			printf("Unable to read()\n");
		#ifdef WIN32
		Sleep(5);
		#else
		usleep(5*1000);
		#endif
	}

	printf("Data read:\n   ");
	// Print out the returned buffer.
	for (i = 0; i < res; i++)
		printf("%02hhx ", buf[i]);
	printf("\n");

	hid_close(handle);

	/* Free static HIDAPI objects. */
	hid_exit();

#ifdef WIN32
	system("pause");
#endif

	return 0;
}
コード例 #29
0
NTSTATUS
StreamEditRegisterCallout(
   const STREAM_EDITOR* streamEditor,
   _Inout_ void* deviceObject
   )
/* ++

   This function registers dynamic callouts and filters that intercept
   TCP traffic at WFP FWPM_LAYER_STREAM_V4 and FWPM_LAYER_STREAM_V6 
   layer.

   Callouts and filters will be removed during DriverUnload.

-- */
{
   NTSTATUS status = STATUS_SUCCESS;

   BOOLEAN engineOpened = FALSE;
   BOOLEAN inTransaction = FALSE;

   FWPM_SESSION session = {0};

   UNREFERENCED_PARAMETER(streamEditor);

   session.flags = FWPM_SESSION_FLAG_DYNAMIC;

   status = FwpmEngineOpen(
                NULL,
                RPC_C_AUTHN_WINNT,
                NULL,
                &session,
                &gEngineHandle
                );
   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }
   engineOpened = TRUE;

   status = FwpmTransactionBegin(gEngineHandle, 0);
   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }
   inTransaction = TRUE;

   status = RegisterCalloutForLayer(
               &FWPM_LAYER_STREAM_V4,
               &STREAM_EDITOR_STREAM_CALLOUT_V4,
               deviceObject,
               &gCalloutIdV4
               );
   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }

   status = RegisterCalloutForLayer(
               &FWPM_LAYER_STREAM_V6,
               &STREAM_EDITOR_STREAM_CALLOUT_V6,
               deviceObject,
               &gCalloutIdV6
               );
   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }

   status = FwpmTransactionCommit(gEngineHandle);
   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }
   inTransaction = FALSE;

Exit:

   if (!NT_SUCCESS(status))
   {
      if (inTransaction)
      {
         NTSTATUS abortStatus;
         abortStatus = FwpmTransactionAbort(gEngineHandle);
         _Analysis_assume_(NT_SUCCESS(abortStatus));
      }
      if (engineOpened)
      {
         FwpmEngineClose(gEngineHandle);
         gEngineHandle = NULL;
      }
   }

   return status;
}
コード例 #30
0
ファイル: busenum.c プロジェクト: imahmoodz/ScpToolkit
NTSTATUS Bus_ReportDevice(PBUSENUM_REPORT_HARDWARE Report, PFDO_DEVICE_DATA fdoData, PUCHAR Transfer)
{
    PLIST_ENTRY         entry;
    PPDO_DEVICE_DATA    pdoData = NULL;
    BOOLEAN             Found = FALSE;

    UNREFERENCED_PARAMETER(Transfer);

    ExAcquireFastMutex(&fdoData->Mutex);

    if (fdoData->NumPDOs == 0)
	{
        Bus_KdPrint(("No devices to report!\n"));
        ExReleaseFastMutex(&fdoData->Mutex);

        return STATUS_NO_SUCH_DEVICE;
    }

    for (entry = fdoData->ListOfPDOs.Flink; entry != &fdoData->ListOfPDOs && !Found; entry = entry->Flink)
	{
        pdoData = CONTAINING_RECORD(entry, PDO_DEVICE_DATA, Link);

        if (Report->SerialNo == pdoData->SerialNo) Found = pdoData->Present;
    }

    ExReleaseFastMutex(&fdoData->Mutex);

    if (Found)
	{
		int     Index;
		BOOLEAN Changed = FALSE;

		for (Index = 0; Index < REPORT_SIZE && !Changed; Index++)
		{
			if (pdoData->Report[Index] != Report->Data[Index]) Changed = TRUE;
		}

		if (Changed)
		{
			PIRP  PendingIrp = NULL;
			KIRQL PrevIrql;

			KeAcquireSpinLock(&pdoData->PendingQueueLock, &PrevIrql);
			{
				if (!IsListEmpty(&pdoData->PendingQueue))
				{
					PLIST_ENTRY  le = RemoveHeadList(&pdoData->PendingQueue);
					PPENDING_IRP lr = CONTAINING_RECORD(le, PENDING_IRP, Link);

					PendingIrp = lr->Irp;
					ExFreeToNPagedLookasideList(&g_LookAside, le);
				}
			}
			KeReleaseSpinLock(&pdoData->PendingQueueLock, PrevIrql);

			if (PendingIrp != NULL)
			{
				KeRaiseIrql(DISPATCH_LEVEL, &PrevIrql);
				{
					PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(PendingIrp);
					PURB pHxp = (PURB) irpStack->Parameters.Others.Argument1;

					PUCHAR Buffer = (PUCHAR) pHxp->UrbBulkOrInterruptTransfer.TransferBuffer;
					pHxp->UrbBulkOrInterruptTransfer.TransferBufferLength = REPORT_SIZE;

					for (Index = 0; Index < REPORT_SIZE; Index++)
					{
						Buffer[Index] = pdoData->Report[Index] = Report->Data[Index];
					}

					PendingIrp->IoStatus.Status = STATUS_SUCCESS;
					IoCompleteRequest(PendingIrp, IO_NO_INCREMENT);
				}
				KeLowerIrql(PrevIrql);
			}
		}

		for (Index = 0; Index < RUMBLE_SIZE; Index++)
		{
			Transfer[Index] = pdoData->Rumble[Index];
			pdoData->Rumble[Index] = 0;
		}

		return STATUS_SUCCESS;
    }

    Bus_KdPrint(("Device %d is not present\n", Report->SerialNo));
    return STATUS_NO_SUCH_DEVICE;
}