コード例 #1
0
ファイル: strutil.cpp プロジェクト: sillsdev/FwSupportTools
/********************************************************************
StrAllocPrefix - allocates or reuses dynamic string memory and
				 prefixes a string

NOTE: caller is responsible for freeing ppwz even if function fails
NOTE: cchPrefix does not have to equal the length of wzPrefix
NOTE: if cchPrefix == 0, length of wzPrefix is used instead
********************************************************************/
extern "C" HRESULT DAPI StrAllocPrefix(
	__inout LPWSTR* ppwz,
	__in LPCWSTR wzPrefix,
	__in DWORD_PTR cchPrefix
	)
{
	Assert(ppwz && wzPrefix);

	HRESULT hr = S_OK;
	DWORD_PTR cch = 0;
	DWORD_PTR cchLen = 0;

	if (*ppwz)
	{
		cch = MemSize(*ppwz);  // get the count in bytes so we can check if it failed (returns -1)
		if (-1 == cch)
			ExitOnFailure(hr = E_INVALIDARG, "failed to get size of destination string");
		cch /= sizeof(WCHAR);  //convert the count in bytes to count in characters

		StringCchLengthW(*ppwz, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchLen));
	}

	Assert(cchLen <= cch);

	if (0 == cchPrefix)
	{
		StringCchLengthW(wzPrefix, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchPrefix));
	}

	if (cch - cchLen < cchPrefix + 1)
	{
		cch = cchPrefix + cchLen + 1;
		hr = StrAlloc(ppwz, cch);
		ExitOnFailure1(hr, "failed to allocate string from string: %S", wzPrefix);
	}

	if (*ppwz)
	{
		DWORD_PTR cb = cch * sizeof(WCHAR);
		DWORD_PTR cbPrefix = cchPrefix * sizeof(WCHAR);

		memmove(*ppwz + cchPrefix, *ppwz, cb - cbPrefix);
		memcpy(*ppwz, wzPrefix, cbPrefix);
	}
	else
	{
		ExitOnFailure(hr = E_UNEXPECTED, "for some reason our buffer is still null");
	}

LExit:
	return hr;
}
コード例 #2
0
ファイル: strsafe_length.c プロジェクト: JSund/libstrsafe
HRESULT StringCbLengthW(
        LPCWSTR psz,
        size_t cbMax,
        size_t *pcb){
    size_t pcch;
    HRESULT result = StringCchLengthW(psz, cbMax / sizeof(wchar_t), &pcch);
    *pcb = pcch * sizeof(wchar_t);
    return result;
}
コード例 #3
0
ファイル: strutil.cpp プロジェクト: sillsdev/FwSupportTools
/********************************************************************
StrAllocConcat - allocates or reuses dynamic string memory and adds an existing string

NOTE: caller is responsible for freeing ppwz even if function fails
NOTE: cchSource does not have to equal the length of wzSource
NOTE: if cchSource == 0, length of wzSource is used instead
********************************************************************/
extern "C" HRESULT DAPI StrAllocConcat(
	__inout LPWSTR* ppwz,
	__in LPCWSTR wzSource,
	__in DWORD_PTR cchSource
	)
{
	Assert(ppwz && wzSource); // && *wzSource);

	HRESULT hr = S_OK;
	DWORD_PTR cch = 0;
	DWORD_PTR cchLen = 0;

	if (*ppwz)
	{
		cch = MemSize(*ppwz);  // get the count in bytes so we can check if it failed (returns -1)
		if (-1 == cch)
			ExitOnFailure(hr = E_INVALIDARG, "failed to get size of destination string");
		cch /= sizeof(WCHAR);  //convert the count in bytes to count in characters

		StringCchLengthW(*ppwz, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchLen));
	}

	Assert(cchLen <= cch);

	if (0 == cchSource)
		StringCchLengthW(wzSource, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchSource));

	if (cch - cchLen < cchSource + 1)
	{
		cch = (cchSource + cchLen + 1) * 2;
		hr = StrAlloc(ppwz, cch);
		ExitOnFailure1(hr, "failed to allocate string from string: %S", wzSource);
	}

	if (*ppwz)
		hr = StringCchCatNExW(*ppwz, cch, wzSource, cchSource, NULL, NULL, STRSAFE_FILL_BEHIND_NULL);
	else
		ExitOnFailure(hr = E_UNEXPECTED, "for some reason our buffer is still null");

LExit:
	return hr;
}
コード例 #4
0
// Function returns S_OK and *ppszValue = NULL if retrieved string property is
//  actually a NULL variant
HRESULT WpcuWmiStringFromInstance(IWbemClassObject* piInstance, PCWSTR pcszProperty, 
                                  PWSTR* ppszValue)
{
    HRESULT hr = E_INVALIDARG;
    if (piInstance && pcszProperty && ppszValue)
    {
        *ppszValue = NULL;
        VARIANT var;
        VariantInit(&var);
        hr = piInstance->Get(pcszProperty, 0, &var, NULL, NULL);
        if (SUCCEEDED(hr))
        {
            // Only allow BSTR and NULL states
            if (var.vt != VT_BSTR)
            {  
                if (var.vt != VT_NULL)
                {
                    hr = E_FAIL;
                }
				else
				{
					hr = S_OK;
				}
            }
            else
            {
                size_t cch;
                hr = StringCchLengthW(var.bstrVal, STRSAFE_MAX_CCH, &cch);
                if (SUCCEEDED(hr))
                {
					// Allocate with null terminator
					*ppszValue = new WCHAR[++cch];
					if (!(*ppszValue))
					{
						hr = E_OUTOFMEMORY;
					}
					else
					{
						hr = StringCchCopyW(*ppszValue, cch, var.bstrVal);
					}
                }
            }
        }
        VariantClear(&var);
    }

    return hr;
}
コード例 #5
0
ファイル: launcher.cpp プロジェクト: fcharlie/msys2-launcher
inline HRESULT StringCchCatW(
  LPWSTR  pszDest,
  size_t  cchDest,
  LPCWSTR pszSrc)
{
  HRESULT hr = S_OK;
  if(cchDest==0||pszDest==nullptr)
    return STRSAFE_E_INVALID_PARAMETER;
  size_t lengthDest;
  if(StringCchLengthW(pszDest,cchDest,&lengthDest)!=S_OK){
    hr=STRSAFE_E_INVALID_PARAMETER;
  }else{
    hr=StringCchCopyW(pszDest+lengthDest,cchDest-lengthDest,pszSrc);
  }
  return hr;
}
コード例 #6
0
ファイル: stdafx.cpp プロジェクト: Edenspuzzle/EdensEngine
void WCharToString( const WCHAR* source, std::string& dest )
{
	try
	{
		size_t size = 0;
		StringCchLengthW(source, STRSAFE_MAX_CCH, &size);
		size++;

		CHAR* tmp = (CHAR*) alloca( size * sizeof(CHAR) );
		StringCchPrintfA(tmp, size, "%S", source);

		dest = tmp;
	}
	catch( ... )
	{}
}
コード例 #7
0
HRESULT GetGUIDNameNew(const GUID& guid, WCHAR **ppwsz)
{
    HRESULT hr = S_OK;
    WCHAR *pName = NULL;

    LPCWSTR pcwsz = GetGUIDNameConstNew(guid);
    if (pcwsz)
    {
        size_t cchLength = 0;

        hr = StringCchLengthW(pcwsz, STRSAFE_MAX_CCH, &cchLength);
        if (FAILED(hr))
        {
            goto done;
        }

        pName = (WCHAR*)CoTaskMemAlloc((cchLength + 1) * sizeof(WCHAR));

        if (pName == NULL)
        {
            hr = E_OUTOFMEMORY;
            goto done;
        }

        hr = StringCchCopyW(pName, cchLength + 1, pcwsz);
        if (FAILED(hr))
        {
            goto done;
        }
    }
    else
    {
        hr = StringFromCLSID(guid, &pName);
    }

done:
    if (FAILED(hr))
    {
        *ppwsz = NULL;
        CoTaskMemFree(pName);
    }
    else
    {
        *ppwsz = pName;
    }
    return hr;
}
コード例 #8
0
//----------------------------------------------------------------------------
std::wstring FormatReader::StringFromGUID( const GUID& aGuid )
{
    HRESULT hr = S_OK;
    WCHAR *pName = NULL;

    LPCWSTR pcwsz = GetGUIDNameConstNew(aGuid);
    if (pcwsz)
    {
        size_t cchLength = 0;

        hr = StringCchLengthW(pcwsz, STRSAFE_MAX_CCH, &cchLength);
        if (FAILED(hr))
        {
            goto done;
        }

        pName = (WCHAR*)CoTaskMemAlloc((cchLength + 1) * sizeof(WCHAR));

        if (pName == NULL)
        {
            hr = E_OUTOFMEMORY;
            goto done;
        }

        hr = StringCchCopyW(pName, cchLength + 1, pcwsz);
        if (FAILED(hr))
        {
            goto done;
        }
    }
    else
    {
        hr = StringFromCLSID(aGuid, &pName);
    }

done:
    std::wstring result;
    if (FAILED(hr))
    {
        CoTaskMemFree(pName);
    }
    else
    {
        result = std::wstring(pName);
    }
    return result;
}
コード例 #9
0
ファイル: helpers.cpp プロジェクト: codeandsec/RFIDCred
//
// This function copies the length of pwz and the pointer pwz into the UNICODE_STRING structure
// This function is intended for serializing a credential in GetSerialization only.
// Note that this function just makes a copy of the string pointer. It DOES NOT ALLOCATE storage!
// Be very, very sure that this is what you want, because it probably isn't outside of the
// exact GetSerialization call where the sample uses it.
//
HRESULT UnicodeStringInitWithString(
                                    PWSTR pwz,
                                    UNICODE_STRING* pus
                                    )
{
    HRESULT hr;
    if (pwz)
    {
        size_t lenString;
        hr = StringCchLengthW(pwz, USHORT_MAX, &(lenString));

        if (SUCCEEDED(hr))
        {
            USHORT usCharCount;
            hr = SizeTToUShort(lenString, &usCharCount);
            if (SUCCEEDED(hr))
            {
                USHORT usSize;
                hr = SizeTToUShort(sizeof(WCHAR), &usSize);
                if (SUCCEEDED(hr))
                {
                    hr = UShortMult(usCharCount, usSize, &(pus->Length)); // Explicitly NOT including NULL terminator
                    if (SUCCEEDED(hr))
                    {
                        pus->MaximumLength = pus->Length;
                        pus->Buffer = pwz;
                        hr = S_OK;
                    }
                    else
                    {
                        hr = HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW);
                    }
                }
            }
        }
    }
    else
    {
        hr = E_INVALIDARG;
    }
    return hr;
}
コード例 #10
0
CardUnlockCredential::~CardUnlockCredential()
{
    if (_rgFieldStrings[SFI_PASSWORD])
    {
        // CoTaskMemFree (below) deals with NULL, but StringCchLength does not.
        size_t lenPassword;
        HRESULT hr = StringCchLengthW(_rgFieldStrings[SFI_PASSWORD], 128, &(lenPassword));
        if (SUCCEEDED(hr))
        {
            SecureZeroMemory(_rgFieldStrings[SFI_PASSWORD], lenPassword * sizeof(*_rgFieldStrings[SFI_PASSWORD]));
        }
        else
        {
            // TODO: Determine how to handle count error here.
        }
    }
    for (int i = 0; i < ARRAYSIZE(_rgFieldStrings); i++)
    {
        CoTaskMemFree(_rgFieldStrings[i]);
        CoTaskMemFree(_rgCredProvFieldDescriptors[i].pszLabel);
    }

    DllRelease();
}
コード例 #11
0
HRESULT RegisterServer()
{
    LPOLESTR psz;
    WCHAR szCLSID[MAX_PATH];
    HRESULT hr = StringFromCLSID(CLSID_OVDeskBand, &psz);
    if (SUCCEEDED(hr))
    {
        hr = StringCchCopyW(szCLSID, ARRAYSIZE(szCLSID), psz);
        CoTaskMemFree(psz);
    }

    WCHAR szSubkey[MAX_PATH];
    HKEY hKey;
    DWORD dwDisp;

    if (SUCCEEDED(hr))
    {
        hr = StringCchPrintfW(szSubkey, ARRAYSIZE(szSubkey), L"CLSID\\%s", szCLSID);
        if (SUCCEEDED(hr))
        {
            hr = E_FAIL;
            if (ERROR_SUCCESS == RegCreateKeyExW(HKEY_CLASSES_ROOT, 
                                                 szSubkey, 
                                                 0, 
                                                 NULL, 
                                                 REG_OPTION_NON_VOLATILE, 
                                                 KEY_WRITE, 
                                                 NULL, 
                                                 &hKey, 
                                                 &dwDisp))
            {
                WCHAR szName[] = L"OVDeskBand";
                if (ERROR_SUCCESS == RegSetValueExW(hKey, 
                                                    NULL, 
                                                    0, 
                                                    REG_SZ, 
                                                    (LPBYTE) szName, 
                                                    sizeof(szName)))
                {
                    hr = S_OK;
                }

                RegCloseKey(hKey);
            }
        }
    }

    if (SUCCEEDED(hr))
    {
        hr = StringCchPrintfW(szSubkey, ARRAYSIZE(szSubkey), L"CLSID\\%s\\InprocServer32", szCLSID);
        if (SUCCEEDED(hr))
        {
            hr = E_FAIL;
            if (ERROR_SUCCESS == RegCreateKeyExW(HKEY_CLASSES_ROOT, 
                                                 szSubkey, 
                                                 0, 
                                                 NULL, 
                                                 REG_OPTION_NON_VOLATILE, 
                                                 KEY_WRITE, 
                                                 NULL, 
                                                 &hKey, 
                                                 &dwDisp))
            {
                WCHAR szModule[MAX_PATH];
                if (GetModuleFileNameW(g_hInst, szModule, ARRAYSIZE(szModule)))
                {
                    DWORD cch;
                    hr = StringCchLengthW(szModule, ARRAYSIZE(szModule), (size_t *)(&cch));
                    if (SUCCEEDED(hr))
                    {
                        if (ERROR_SUCCESS != RegSetValueExW(hKey, 
                                                            NULL, 
                                                            0, 
                                                            REG_SZ, 
                                                            (LPBYTE) szModule, 
                                                            cch * sizeof(WCHAR)))
                        {
                            hr = E_FAIL;
                        }
                    }
                }

                if (SUCCEEDED(hr))
                {
                    WCHAR szModel[] = L"Apartment";
                    if (ERROR_SUCCESS != RegSetValueExW(hKey, 
                                                        L"ThreadingModel", 
                                                        0, 
                                                        REG_SZ, 
                                                        (LPBYTE) szModel, 
                                                        sizeof(szModel)))
                    {
                        hr = E_FAIL;
                    }
                }

                RegCloseKey(hKey);
            }
        }
    }

    return hr;
}
コード例 #12
0
// Function returns S_OK and *pppszValue = NULL if retrieved string array property 
//  is actually a NULL variant
HRESULT WpcuWmiStringArrayFromInstance(IWbemClassObject* piInstance, 
                                       PCWSTR pcszProperty, 
                                       DWORD* pdwNumElements, 
                                       PWSTR** pppszValue)
{
    HRESULT hr = E_INVALIDARG;
    if (piInstance && pcszProperty && pdwNumElements && pppszValue)
    {
        *pppszValue = NULL;
        *pdwNumElements = 0;

        VARIANT var;
        VariantInit(&var);
        hr = piInstance->Get(pcszProperty, 0, &var, NULL, NULL);
        if (SUCCEEDED(hr))
        {
            // Only allow BSTR array and NULL states
            if (var.vt != (VT_BSTR | VT_ARRAY))
            {
                if (var.vt != VT_NULL)
                {
                    hr = E_FAIL;
                }
				else
				{
					hr = S_OK;
				}
            }
            else
            {
                // Transfer array data from variant
                long lUpper, lLower;
                hr = SafeArrayGetUBound(var.parray, 1, &lUpper);
                if (SUCCEEDED(hr))
                {
                    hr = SafeArrayGetLBound(var.parray, 1, &lLower);
                    if (SUCCEEDED(hr))
                    {
                        DWORD dwNumElements = lUpper - lLower + 1;
                        if (lUpper - lLower + 1 < lUpper - lLower)
                        {
                            // Overflow
                            hr = E_FAIL;
                        }
                        else if (dwNumElements > 0)
                        {
                            BSTR* pData;
                            hr = SafeArrayAccessData(var.parray, 
                                                     (void HUGEP**)(&pData));
                            if (SUCCEEDED(hr))
                            {
                                // Allocate results array
                                *pppszValue = new PWSTR[dwNumElements];
                                if (*pppszValue == NULL)
                                {
                                    hr = E_OUTOFMEMORY;
                                }
                                else
                                {
                                    size_t cch;
                                    for (DWORD i = 0; 
                                         i < dwNumElements && SUCCEEDED(hr); 
                                         i++)
                                    {
                                        hr = StringCchLengthW(pData[lLower + i], 
                                                              STRSAFE_MAX_CCH, 
                                                              &cch);
                                        if (SUCCEEDED(hr))
                                        {
                                            (*pppszValue)[i] = new WCHAR[++cch];
                                            if (!(*pppszValue)[i])
                                            {
                                                hr = E_OUTOFMEMORY;
                                            }
                                            else
                                            {
                                                hr = StringCchCopyW((*pppszValue)[i], 
                                                                    cch, 
                                                                    pData[lLower + i]);
                                                if (SUCCEEDED(hr))
                                                {
                                                    // Successful addition
                                                    (*pdwNumElements)++;
                                                }
                                                else
                                                {
                                                    delete[] (*pppszValue)[i];
                                                    (*pppszValue)[i] = NULL;
                                                }
                                            }
                                        }
                                    }
                                }
                                // Always unlock the array
                                SafeArrayUnaccessData(var.parray);
                            }
                        }
                    }
                }
            }
            VariantClear(&var);
        }
    }

    return hr;
}
コード例 #13
0
ファイル: afslogon.c プロジェクト: stevenjenkins/openafs
VOID AFS_Logoff_Event( PWLX_NOTIFICATION_INFO pInfo )
{
    DWORD code;
    TCHAR profileDir[1024] = TEXT("");
    DWORD  len = 1024;
    PTOKEN_USER  tokenUser = NULL;
    DWORD  retLen;
    DWORD LSPtype, LSPsize;
    HKEY NPKey;
    DWORD LogoffPreserveTokens = 0;
    LogonOptions_t opt;

    /* Make sure the AFS Libraries are initialized */
    AfsLogonInit();

    DebugEvent0("AFS_Logoff_Event - Start");

    (void) RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
                         0, KEY_QUERY_VALUE, &NPKey);
    LSPsize=sizeof(LogoffPreserveTokens);
    RegQueryValueEx(NPKey, REG_CLIENT_LOGOFF_TOKENS_PARM, NULL,
                     &LSPtype, (LPBYTE)&LogoffPreserveTokens, &LSPsize);
    RegCloseKey (NPKey);

    if (!LogoffPreserveTokens) {
	memset(&opt, 0, sizeof(LogonOptions_t));

	if (pInfo->UserName && pInfo->Domain) {
	    char username[MAX_USERNAME_LENGTH] = "";
	    char domain[MAX_DOMAIN_LENGTH] = "";
	    size_t szlen = 0;

	    StringCchLengthW(pInfo->UserName, MAX_USERNAME_LENGTH, &szlen);
	    WideCharToMultiByte(CP_UTF8, 0, pInfo->UserName, szlen,
				 username, sizeof(username), NULL, NULL);

	    StringCchLengthW(pInfo->Domain, MAX_DOMAIN_LENGTH, &szlen);
	    WideCharToMultiByte(CP_UTF8, 0, pInfo->Domain, szlen,
				 domain, sizeof(domain), NULL, NULL);

	    GetDomainLogonOptions(NULL, username, domain, &opt);
	}

        if (ISREMOTE(opt.flags)) {
	    if (!GetTokenInformation(pInfo->hToken, TokenUser, NULL, 0, &retLen))
	    {
		if ( GetLastError() == ERROR_INSUFFICIENT_BUFFER ) {
		    tokenUser = (PTOKEN_USER) LocalAlloc(LPTR, retLen);

		    if (!GetTokenInformation(pInfo->hToken, TokenUser, tokenUser, retLen, &retLen))
		    {
			DebugEvent("AFS_Logoff_Event - GetTokenInformation failed: GLE = %lX", GetLastError());
		    }
		}
	    }

	    /* We can't use pInfo->Domain for the domain since in the cross realm case 
	     * this is source domain and not the destination domain.
	     */
	    if (tokenUser && QueryAdHomePathFromSid( profileDir, sizeof(profileDir), tokenUser->User.Sid, pInfo->Domain)) {
		WCHAR Domain[64]=L"";
		GetLocalShortDomain(Domain, sizeof(Domain));
		if (QueryAdHomePathFromSid( profileDir, sizeof(profileDir), tokenUser->User.Sid, Domain)) {
		    if (NetUserGetProfilePath(pInfo->Domain, pInfo->UserName, profileDir, len))
			GetUserProfileDirectory(pInfo->hToken, profileDir, &len);
		}
	    }

	    if (strlen(profileDir)) {
		DebugEvent("AFS_Logoff_Event - Profile Directory: %s", profileDir);
		if (!IsPathInAfs(profileDir)) {
		    if (code = ktc_ForgetAllTokens())
			DebugEvent("AFS_Logoff_Event - ForgetAllTokens failed [%lX]",code);
		    else
			DebugEvent0("AFS_Logoff_Event - ForgetAllTokens succeeded");
		} else {
		    DebugEvent0("AFS_Logoff_Event - Tokens left in place; profile in AFS");
		}
	    } else {
		DebugEvent0("AFS_Logoff_Event - Unable to load profile");
	    }

	    if ( tokenUser )
		LocalFree(tokenUser);
	} else {
	    DebugEvent0("AFS_Logoff_Event - Local Logon");
	    if (code = ktc_ForgetAllTokens())
		DebugEvent("AFS_Logoff_Event - ForgetAllTokens failed [%lX]",code);
	    else
		DebugEvent0("AFS_Logoff_Event - ForgetAllTokens succeeded");
	}
    } else {
	DebugEvent0("AFS_Logoff_Event - Preserving Tokens");
    }

    DebugEvent0("AFS_Logoff_Event - End");
}   
コード例 #14
0
ファイル: Module.cpp プロジェクト: DamianSuess/LiteStep
bool Module::_LoadDll()
{
    bool bReturn = false;

    if (!m_hInstance)
    {
        // Modules like popup2 like to call SetErrorMode. While that may not be
        // good style, there is little we can do about it. However, LoadLibrary
        // usually produces helpful error messages such as
        // "msvcp70.dll not found" which are not displayed if a module has
        // disabled them via SetErrorMode. We force their display here.
        // First, make Windows display all errors
        UINT uOldMode = SetErrorMode(0);

        if ((m_hInstance = LoadLibraryW(m_wzLocation.c_str())) != nullptr)
        {
            AssignToFunction(m_pInit, (initModuleProc) GetProcAddress(
                m_hInstance, "initModuleW"));

            if (!m_pInit) // Might be a legacy module, check for initModuleEx
            {
                initModuleProcA pInit = (initModuleProcA)GetProcAddress(
                    m_hInstance, "initModuleEx");

                if (!pInit) // Might be a BC module, check for underscore
                {
                    pInit = (initModuleProcA)GetProcAddress(
                        m_hInstance, "_initModuleEx");
                }

                if (pInit)
                {
                    m_pInit = [pInit] (HWND hWnd, HINSTANCE hInst, LPCWSTR pwzPath) -> int {
                        char szPath[MAX_PATH];
                        WideCharToMultiByte(CP_ACP, 0, pwzPath, -1,
                            szPath, sizeof(szPath), "", nullptr);
                        return pInit(hWnd, hInst, szPath);
                    };
                }
            }

            m_pQuit = (quitModuleProc)GetProcAddress(
                m_hInstance, "quitModule");

            if (!m_pQuit)   // Might be a BC module, check for underscore
            {
                m_pQuit = (quitModuleProc)GetProcAddress(
                    m_hInstance, "_quitModule");
            }

            if (m_pInit == nullptr)
            {
                RESOURCE_STR(nullptr, IDS_INITMODULEEXNOTFOUND_ERROR,
                    L"Error: Could not find initModule().\n"
                    L"\n"
                    L"Please confirm that the dll is a LiteStep module,\n"
                    L"and check with the author for updates.");
            }
            else if (m_pQuit == nullptr)
            {
                RESOURCE_STR(nullptr, IDS_QUITMODULENOTFOUND_ERROR,
                    L"Error: Could not find quitModule().\n"
                    L"\n"
                    L"Please confirm that the dll is a LiteStep module.");
            }
            else
            {
                bReturn = true;
            }
        }
        else
        {
            HRESULT hrError = HrGetLastError();

#if defined(_WIN64)
            if (GetModuleArchitecture(m_wzLocation.c_str()) == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
            {
                RESOURCE_STR(nullptr, IDS_MODULEWRONGARCH64_ERROR,
                    L"Error: Could not load module.\n"
                    L"\n"
                    L"The module seems to compiled for 32-bit LiteStep. This is a 64-bit version of LiteStep, which can only load 64-bit modules.");
            }
#else
            if (GetModuleArchitecture(m_wzLocation.c_str()) == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
            {
                RESOURCE_STR(nullptr, IDS_MODULEWRONGARCH32_ERROR,
                    L"Error: Could not load module.\n"
                    L"\n"
                    L"The module seems to compiled for 64-bit LiteStep. This is a 32-bit version of LiteStep, which can only load 32-bit modules.");
            }
#endif
            else if (PathFileExistsW(m_wzLocation.c_str()))
            {
                RESOURCE_STR(nullptr, IDS_MODULEDEPENDENCY_ERROR,
                    L"Error: Could not load module.\n"
                    L"\n"
                    L"This is likely a case of a missing C Run-Time Library"
                    L"or other dependency."
                    L"\n"
                    L"Error Information:"
                    L"\n");

                size_t nLen = 0;
                StringCchLengthW(resourceTextBuffer, _countof(resourceTextBuffer), &nLen);
                DescriptionFromHR(hrError, resourceTextBuffer + nLen, _countof(resourceTextBuffer) - nLen);
            }
            else
            {
                RESOURCE_STR(nullptr, IDS_MODULENOTFOUND_ERROR,
                    L"Error: Could not locate module.\n"
                    L"\n"
                    L"Please check your configuration.");
            }
        }

        // Second, restore the old state
        SetErrorMode(uOldMode);

        if (!bReturn)
        {
            LPCWSTR pwzFileName = PathFindFileNameW(m_wzLocation.c_str());

            RESOURCE_MSGBOX_F(pwzFileName, MB_ICONERROR);

            if (m_hInstance)
            {
                FreeLibrary(m_hInstance);
                m_hInstance = nullptr;
            }
        }
    }

    return bReturn;
}
コード例 #15
0
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPTSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
   LPWIN32_FIND_DATAW ffd;
   LARGE_INTEGER filesize;
   WCHAR szDir[MAX_PATH];
   size_t length_of_arg;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError=0;
   LPWSTR *szArgList;
   int argCount;

   std::ofstream logFile;
   logFile.open ("FileListing.log");

   
   // If the directory is not specified as a command-line argument,
   // print usage.

  szArgList = CommandLineToArgvW((LPCWSTR)GetCommandLine(), &argCount);

  if(argCount !=2)
	  logFile << "\nUsage: %s <directory name>\n" << szArgList[0];

   /*if(argc != 2)
   {
      _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
      return (-1);
   }*/

   // Check that the input path plus 3 is not longer than MAX_PATH.
   // Three characters are for the "\*" plus NULL appended below.

   StringCchLengthW(szArgList[1], MAX_PATH,  (size_t *)&argCount);

   if ( argCount > (MAX_PATH - 3))
   {
      logFile << "\nDirectory path is too long.\n";
      return (-1);
   }

  logFile <<"\nTarget directory is "<<szArgList[1] <<":\n\n";

   // Prepare string for use with FindFile functions. First, copy the
   // string to a buffer, then append '\*' to the directory name.

   StringCchCopyW(szDir, MAX_PATH, szArgList[1]);
   StringCchCatW(szDir, MAX_PATH, L"\\*");

   // Find the first file in the directory.

   hFind = FindFirstFileW(szDir, &ffd);

   if (INVALID_HANDLE_VALUE == hFind) 
   {
      DisplayErrorBox(TEXT("FindFirstFile"));
      return dwError;
   } 
   
   // List all the files in the directory with some info about them.

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
         _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
      }
      else
      {
         filesize.LowPart = ffd.nFileSizeLow;
         filesize.HighPart = ffd.nFileSizeHigh;
         _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);
 
   dwError = GetLastError();
   if (dwError != ERROR_NO_MORE_FILES) 
   {
      DisplayErrorBox(TEXT("FindFirstFile"));
   }

   FindClose(hFind);
   return dwError;

	return 0;
}
コード例 #16
0
ファイル: afslogon.c プロジェクト: stevenjenkins/openafs
VOID AFS_Logon_Event( PWLX_NOTIFICATION_INFO pInfo )
{
    TCHAR profileDir[1024] = TEXT("");
    DWORD  len = 1024;
    PTOKEN_USER  tokenUser = NULL;
    DWORD  retLen;
    WCHAR szUserW[128] = L"";
    char  szUserA[128] = "";
    char  szClient[MAX_PATH];
    char szPath[MAX_PATH] = "";
    NETRESOURCE nr;
    DWORD res;
    DWORD dwSize;
    LogonOptions_t opt;

    /* Make sure the AFS Libraries are initialized */
    AfsLogonInit();

    DebugEvent0("AFS_Logon_Event - Start");

    DebugEvent("AFS_Logon_Event Process ID: %d",GetCurrentProcessId());

    memset(&opt, 0, sizeof(LogonOptions_t));

    if (pInfo->UserName && pInfo->Domain) {
        char username[MAX_USERNAME_LENGTH] = "";
        char domain[MAX_DOMAIN_LENGTH] = "";
        size_t szlen = 0;

	DebugEvent0("AFS_Logon_Event - pInfo UserName and Domain");

        StringCchLengthW(pInfo->UserName, MAX_USERNAME_LENGTH, &szlen);
        WideCharToMultiByte(CP_UTF8, 0, pInfo->UserName, szlen,
                            username, sizeof(username), NULL, NULL);
        
        StringCchLengthW(pInfo->Domain, MAX_DOMAIN_LENGTH, &szlen);
        WideCharToMultiByte(CP_UTF8, 0, pInfo->Domain, szlen,
                            domain, sizeof(domain), NULL, NULL);

	DebugEvent0("AFS_Logon_Event - Calling GetDomainLogonOptions");
        GetDomainLogonOptions(NULL, username, domain, &opt);
    } else {
	if (!pInfo->UserName)
	    DebugEvent0("AFS_Logon_Event - No pInfo->UserName");
	if (!pInfo->Domain)
	    DebugEvent0("AFS_Logon_Event - No pInfo->Domain");
    }

    DebugEvent("AFS_Logon_Event - opt.LogonOption = %lX opt.flags = %lX", 
		opt.LogonOption, opt.flags);

    if (!ISLOGONINTEGRATED(opt.LogonOption) || !ISREMOTE(opt.flags)) {
        DebugEvent0("AFS_Logon_Event - Logon is not integrated or not remote");
        goto done_logon_event;
    }

    DebugEvent0("AFS_Logon_Event - Calling GetTokenInformation");

    if (!GetTokenInformation(pInfo->hToken, TokenUser, NULL, 0, &retLen))
    {
        if ( GetLastError() == ERROR_INSUFFICIENT_BUFFER ) {
            tokenUser = (PTOKEN_USER) LocalAlloc(LPTR, retLen);

            if (!GetTokenInformation(pInfo->hToken, TokenUser, tokenUser, retLen, &retLen))
            {
                DebugEvent("AFS_Logon_Event - GetTokenInformation failed: GLE = %lX", GetLastError());
            }
        }
    }

    /* We can't use pInfo->Domain for the domain since in the cross realm case 
     * this is source domain and not the destination domain.
     */
    if (tokenUser && QueryAdHomePathFromSid( profileDir, sizeof(profileDir), tokenUser->User.Sid, pInfo->Domain)) {
        WCHAR Domain[64]=L"";
        GetLocalShortDomain(Domain, sizeof(Domain));
        if (QueryAdHomePathFromSid( profileDir, sizeof(profileDir), tokenUser->User.Sid, Domain)) {
            if (NetUserGetProfilePath(pInfo->Domain, pInfo->UserName, profileDir, len))
                GetUserProfileDirectory(pInfo->hToken, profileDir, &len);
        }
    }
    
    if (strlen(profileDir)) {
        DebugEvent("AFS_Logon_Event - Profile Directory: %s", profileDir);
    } else {
        DebugEvent0("AFS_Logon_Event - Unable to load profile");
    }

  done_logon_event:
    dwSize = sizeof(szUserA);
    if (!KFW_AFS_get_lsa_principal(szUserA, &dwSize)) {
        StringCbPrintfW(szUserW, sizeof(szUserW), L"%s\\%s", pInfo->Domain, pInfo->UserName);
        WideCharToMultiByte(CP_ACP, 0, szUserW, -1, szUserA, MAX_PATH, NULL, NULL);
    }

    if (szUserA[0])
    {
        lana_GetNetbiosName(szClient, LANA_NETBIOS_NAME_FULL);
        StringCbPrintf(szPath, sizeof(szPath), "\\\\%s", szClient);

        DebugEvent("AFS_Logon_Event - Logon Name: %s", szUserA);

        memset (&nr, 0x00, sizeof(NETRESOURCE));
        nr.dwType=RESOURCETYPE_DISK;
        nr.lpLocalName=0;
        nr.lpRemoteName=szPath;
        res = WNetAddConnection2(&nr,NULL,szUserA,0);
        if (res)
            DebugEvent("AFS_Logon_Event - WNetAddConnection2(%s,%s) failed: 0x%X",
                        szPath, szUserA,res);
        else
            DebugEvent0("AFS_Logon_Event - WNetAddConnection2() succeeded");
    } else 
        DebugEvent("AFS_Logon_Event - User name conversion failed: GLE = 0x%X",GetLastError());

    if ( tokenUser )
        LocalFree(tokenUser);

    DebugEvent0("AFS_Logon_Event - End");
}
コード例 #17
0
_Must_inspect_result_
NTSTATUS
FxDriver::AddDevice(
    _In_  IWudfDeviceStack *        DevStack,
    _In_  LPCWSTR                   KernelDeviceName,
    _In_opt_ HKEY                   PdoKey,
    _In_  LPCWSTR                   ServiceName,
    _In_  LPCWSTR                   DevInstanceID,
    _In_  ULONG                     DriverID
    )
{
    WDFDEVICE_INIT init(this);
    FxDevice* pDevice;
    NTSTATUS status;
    HRESULT hr = S_OK;
    LONG lRetVal = -1;

    DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                        "Enter AddDevice DevStack %p", DevStack);

    //FX_VERIFY(INTERNAL, CHECK_NOT_NULL(DevStack));
    //FX_VERIFY(INTERNAL, CHECK_NOT_NULL(KernelDeviceName));
    //FX_VERIFY(INTERNAL, CHECK_HANDLE(PdoKey));
    //FX_VERIFY(INTERNAL, CHECK_NOT_NULL(ServiceName));
    //FX_VERIFY(INTERNAL, CHECK_NOT_NULL(DevInstanceID));

    pDevice = NULL;
    init.CreatedOnStack = TRUE;
    init.InitType = FxDeviceInitTypeFdo;
    init.Fdo.PhysicalDevice = NULL;

    //
    // Capture the input parameters
    //
    init.DevStack = DevStack;
    init.DriverID = DriverID;

    lRetVal = RegOpenKeyEx(
        PdoKey,
        NULL,
        0,
        KEY_READ,
        &init.PdoKey
        );

    if (ERROR_SUCCESS != lRetVal) {
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                            "Registry key open failed for the PDO key, "
                            "winerror %!WINERROR!", lRetVal);

        hr = HRESULT_FROM_WIN32(lRetVal);
        return FxDevice::NtStatusFromHr(DevStack, hr);
    }

    size_t len = 0;
    hr = StringCchLengthW(ServiceName, STRSAFE_MAX_CCH, &len);
    if (FAILED(hr)) {
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                            "Registry path string too long or badly formed "
                            "path. Invalid configuration HRESULT %!hresult!", 
                            hr);
        return FxDevice::NtStatusFromHr(DevStack, hr);
    }

    len += 1;    // Add one for the string termination character
    init.ConfigRegistryPath = new WCHAR[len];
    if (NULL == init.ConfigRegistryPath) {
        hr = E_OUTOFMEMORY;
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                            "Failed to allocate memory for Config path"
                            " HRESULT %!hresult!", hr);

        return FxDevice::NtStatusFromHr(DevStack, hr);
    }

    hr = StringCchCopyW(init.ConfigRegistryPath, len, ServiceName);
    if (FAILED(hr)) {
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                            "Failed to copy the configuration path status "
                            "%!hresult!", hr);
        return FxDevice::NtStatusFromHr(DevStack, hr);
    }

    //
    // Capture the PDO device instance ID.
    //
    len = 0;
    hr = StringCchLengthW(DevInstanceID, STRSAFE_MAX_CCH, &len);
    if (FAILED(hr)) {
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                            "Device Instance ID string too long or badly formed"
                            " path. Invalid configuration %!hresult!", hr);
        return FxDevice::NtStatusFromHr(DevStack, hr);
    }

    len += 1; // Add one for the string termination character
    init.DevInstanceID = new WCHAR[len];
    if (NULL == init.DevInstanceID) {
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                            "Failed to allocate memory for DevInstanceID "
                            "%!hresult!", hr);
        hr = E_OUTOFMEMORY;
        return FxDevice::NtStatusFromHr(DevStack, hr);
    }

    hr = StringCchCopyW(init.DevInstanceID, len, DevInstanceID);
    if (FAILED(hr)) {
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                            "Unable to copy DevInstanceID %!hresult!", hr);
        return FxDevice::NtStatusFromHr(DevStack, hr);
    }

    //
    // Capture Kernel device name.
    //
    len = 0;
    hr = StringCchLengthW(KernelDeviceName, STRSAFE_MAX_CCH, &len);
    if (FAILED(hr)) {
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                            "Unable to determine KernelDeviceName length"
                            "%!hresult!", hr);
        return FxDevice::NtStatusFromHr(DevStack, hr);
    }

    len += 1; // Add one for string termination character.
    init.KernelDeviceName = new WCHAR[len];
    if (init.KernelDeviceName == NULL) {
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                            "Failed to allocate memory for KernelDeviceName "
                            "%!hresult!", hr);
        hr = E_OUTOFMEMORY;
        return FxDevice::NtStatusFromHr(DevStack, hr);
    }

    hr = StringCchCopyW(init.KernelDeviceName, len, KernelDeviceName);
    if (FAILED(hr)) {
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                            "Unable to copy kernel device name KernelDeviceName"
                            " %!hresult!", hr);
        return FxDevice::NtStatusFromHr(DevStack, hr);
    }

    //
    // Invoke driver's AddDevice callback
    //
    status = m_DriverDeviceAdd.Invoke(GetHandle(), &init);

    //
    // Caller returned w/out creating a device, we are done.  Returning
    // STATUS_SUCCESS w/out creating a device and attaching to the stack is OK,
    // especially for filter drivers which selectively attach to devices.
    //
    if (init.CreatedDevice == NULL) {
        DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_WARNING, TRACINGPNP,
                            "Driver did not create a device in "
                            "EvtDriverAddDevice, status %!STATUS!", status);

        //
        // We do not let filters affect the building of the rest of the stack.
        // If they return error, we convert it to STATUS_SUCCESS.
        //
        if (init.Fdo.Filter && !NT_SUCCESS(status)) {
            DoTraceLevelMessage(
                GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNP,
                "Filter returned %!STATUS! without creating a WDFDEVICE, "
                "converting to STATUS_SUCCESS", status);
            status = STATUS_SUCCESS;
        }

        return status;
    }

    pDevice = init.CreatedDevice;

    if (NT_SUCCESS(status)) {
        //
        // Make sure that DO_DEVICE_INITIALIZING is cleared.
        // FxDevice::FdoInitialize does not do this b/c the driver writer may
        // want the bit set until sometime after WdfDeviceCreate returns
        //
        pDevice->FinishInitializing();
    }
    else {
        //
        // Created a device, but returned error.
        //
        ASSERT(pDevice->IsPnp());
        ASSERT(pDevice->m_CurrentPnpState == WdfDevStatePnpInit);

        status = pDevice->DeleteDeviceFromFailedCreate(status, TRUE);
        pDevice = NULL;
    }

    DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGPNP,
                        "Exit, status %!STATUS!", status);

    return status;
}