diff --git a/include/WinStd/Base64.h b/include/WinStd/Base64.h index f2f2d1b0..66e47e0b 100644 --- a/include/WinStd/Base64.h +++ b/include/WinStd/Base64.h @@ -23,15 +23,6 @@ #include #include -namespace winstd -{ - class WINSTD_API base64_enc; - class WINSTD_API base64_dec; -} - -#pragma once - - namespace winstd { /// @@ -43,6 +34,21 @@ namespace winstd /// /// Base64 encoding session /// + class WINSTD_API base64_enc; + + /// + /// Base64 decoding session + /// + class WINSTD_API base64_dec; + + /// @} +} + +#pragma once + + +namespace winstd +{ class WINSTD_API base64_enc { public: @@ -165,9 +171,6 @@ namespace winstd }; - /// - /// Base64 decoding session - /// class WINSTD_API base64_dec { public: @@ -267,6 +270,4 @@ namespace winstd size_t num; ///< Number of bytes used in `buf` static const unsigned char lookup[256]; ///< Look-up table }; - - /// @} } diff --git a/include/WinStd/COM.h b/include/WinStd/COM.h index 26a1f15b..1d434baa 100644 --- a/include/WinStd/COM.h +++ b/include/WinStd/COM.h @@ -24,12 +24,45 @@ namespace winstd { + /// + /// \defgroup WinStdCOM COM object management + /// Provides helper templates for Windows COM object manipulation + /// + /// @{ + + /// + /// COM object wrapper template + /// template class com_obj; + /// + /// BSTR string wrapper + /// class WINSTD_API bstr; + + /// + /// VARIANT struct wrapper + /// class WINSTD_API variant; + + /// @} + class WINSTD_API com_initializer; + + /// + /// \defgroup WinStdExceptions Exceptions + /// Additional exceptions + /// + /// @{ + + /// + /// COM runtime error + /// + /// \note Must be defined as derived class from num_runtime_error<> to allow correct type info for dynamic typecasting and prevent folding with other derivates of num_runtime_error<>. + /// class WINSTD_API com_runtime_error; + + /// @} } #pragma once @@ -37,16 +70,6 @@ namespace winstd namespace winstd { - /// - /// \defgroup WinStdCOM COM object management - /// Provides helper templates for Windows COM object manipulation - /// - /// @{ - - - /// - /// COM object wrapper template - /// template class com_obj : public handle { @@ -129,9 +152,6 @@ namespace winstd }; - /// - /// BSTR string wrapper - /// class WINSTD_API bstr : public handle { public: @@ -209,9 +229,6 @@ namespace winstd }; - /// - /// VARIANT struct wrapper - /// class WINSTD_API variant : public VARIANT { public: @@ -914,8 +931,6 @@ namespace winstd } }; - /// @} - class WINSTD_API com_initializer { @@ -965,17 +980,6 @@ namespace winstd }; - /// - /// \defgroup WinStdExceptions Exceptions - /// Additional exceptions - /// - /// @{ - - /// - /// COM runtime error - /// - /// \note Must be defined as derived class from num_runtime_error<> to allow correct type info for dynamic typecasting and prevent folding with other derivates of num_runtime_error<>. - /// class WINSTD_API com_runtime_error : public num_runtime_error { public: @@ -1010,6 +1014,4 @@ namespace winstd { } }; - - /// @} } diff --git a/include/WinStd/Common.h b/include/WinStd/Common.h index 9c2da055..52bd2886 100644 --- a/include/WinStd/Common.h +++ b/include/WinStd/Common.h @@ -48,10 +48,40 @@ inline int vsnprintf(_Out_z_cap_(capacity) char *str, _In_ size_t capacity, _In_z_ _Printf_format_string_ const char *format, _In_ va_list arg); inline int vsnprintf(_Out_z_cap_(capacity) wchar_t *str, _In_ size_t capacity, _In_z_ _Printf_format_string_ const wchar_t *format, _In_ va_list arg); + +/// +/// Formats string using `printf()`. +/// +/// \param[out] str Formatted string +/// \param[in ] format String template using `printf()` style +/// \param[in ] arg Arguments to `format` +/// +/// \returns Number of characters in result. +/// template inline int vsprintf(_Out_ std::basic_string<_Elem, _Traits, _Ax> &str, _In_z_ _Printf_format_string_ const _Elem *format, _In_ va_list arg); + +/// +/// Formats string using `printf()`. +/// +/// \param[out] str Formatted string +/// \param[in ] format String template using `printf()` style +/// +/// \returns Number of characters in result. +/// template inline int sprintf(_Out_ std::basic_string<_Elem, _Traits, _Ax> &str, _In_z_ _Printf_format_string_ const _Elem *format, ...); +/// +/// Formats a message string. +/// +/// \sa [FormatMessage function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351.aspx) +/// template inline DWORD FormatMessage(_In_ DWORD dwFlags, _In_opt_ LPCVOID lpSource, _In_ DWORD dwMessageId, _In_ DWORD dwLanguageId, _Out_ std::basic_string &str, _In_opt_ va_list *Arguments); + +/// +/// Formats a message string. +/// +/// \sa [FormatMessage function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351.aspx) +/// template inline DWORD FormatMessage(_In_ DWORD dwFlags, _In_opt_ LPCVOID lpSource, _In_ DWORD dwMessageId, _In_ DWORD dwLanguageId, _Out_ std::basic_string &str, _In_opt_ va_list *Arguments); namespace winstd @@ -65,10 +95,37 @@ namespace winstd typedef std::string tstring; #endif + /// + /// Deleter for unique_ptr using LocalFree + /// template struct LocalFree_delete; + + /// + /// Deleter for unique_ptr to array of unknown size using LocalFree + /// template struct LocalFree_delete<_Ty[]>; + + /// + /// \defgroup WinStdSysHandles System Handles + /// Simplifies work with object handles of various type + /// + /// @{ + + /// + /// Base abstract template class to support generic object handle keeping + /// + /// It provides basic operators and methods common to all descendands of this class establishing a base to ease the replacement of native object handle type with classes in object-oriented approach. + /// template class handle; + + /// + /// Base abstract template class to support object handle keeping for objects that support handle duplication + /// template class dplhandle; + + /// + /// Helper class to allow limited size FIFO queues implemented as vector of elements + /// template class vector_queue; /// @@ -77,14 +134,34 @@ namespace winstd /// /// @{ + /// + /// Numerical runtime error + /// template class num_runtime_error; + + /// + /// Windows runtime error + /// class WINSTD_API win_runtime_error; /// @} - /// \addtogroup WinStdStrFormat + /// + /// \defgroup WinStdStrFormat String Formatting + /// Formatted string generation + /// + /// \par Example + /// \code + /// // Please note the PCSTR typecasting invokes an operator to return + /// // pointer to formatted buffer rather than class reference itself. + /// cout << (PCSTR)(winstd::string_printf("%i is less than %i.\n", 1, 5)); + /// \endcode + /// /// @{ + /// + /// Base template class to support string formatting using `printf()` style templates + /// template, class _Ax = std::allocator<_Elem> > class basic_string_printf; /// @@ -106,6 +183,9 @@ namespace winstd typedef string_printf tstring_printf; #endif + /// + /// Base template class to support string formatting using `FormatMessage()` style templates + /// template, class _Ax = std::allocator<_Elem> > class basic_string_msg; /// @@ -127,8 +207,19 @@ namespace winstd typedef string_msg tstring_msg; #endif + /// + /// Base template class to support converting GUID to string + /// template, class _Ax = std::allocator<_Elem> > class basic_string_guid; + + /// + /// Single-byte character implementation of a class to support converting GUID to string + /// class WINSTD_API string_guid; + + /// + /// Wide character implementation of a class to support converting GUID to string + /// class WINSTD_API wstring_guid; /// @@ -142,9 +233,18 @@ namespace winstd /// @} - /// \addtogroup WinStdMemSanitize + /// \defgroup WinStdMemSanitize Auto-sanitize Memory Management + /// Sanitizes memory before dismissed + /// /// @{ + /// + /// An allocator template that sanitizes each memory block before it is destroyed or reallocated + /// + /// \note + /// `sanitizing_allocator` introduces a performance penalty. However, it provides an additional level of security. + /// Use for security sensitive data memory storage only. + /// template class sanitizing_allocator; /// @@ -221,15 +321,6 @@ inline int vsnprintf(_Out_z_cap_(capacity) wchar_t *str, _In_ size_t capacity, _ } -/// -/// Formats string using `printf()`. -/// -/// \param[out] str Formatted string -/// \param[in ] format String template using `printf()` style -/// \param[in ] arg Arguments to `format` -/// -/// \returns Number of characters in result. -/// template inline int vsprintf(_Out_ std::basic_string<_Elem, _Traits, _Ax> &str, _In_z_ _Printf_format_string_ const _Elem *format, _In_ va_list arg) { @@ -258,14 +349,6 @@ inline int vsprintf(_Out_ std::basic_string<_Elem, _Traits, _Ax> &str, _In_z_ _P #pragma warning(pop) -/// -/// Formats string using `printf()`. -/// -/// \param[out] str Formatted string -/// \param[in ] format String template using `printf()` style -/// -/// \returns Number of characters in result. -/// template inline int sprintf(_Out_ std::basic_string<_Elem, _Traits, _Ax> &str, _In_z_ _Printf_format_string_ const _Elem *format, ...) { @@ -277,11 +360,6 @@ inline int sprintf(_Out_ std::basic_string<_Elem, _Traits, _Ax> &str, _In_z_ _Pr } -/// -/// Formats a message string. -/// -/// \sa [FormatMessage function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351.aspx) -/// template inline DWORD FormatMessage(_In_ DWORD dwFlags, _In_opt_ LPCVOID lpSource, _In_ DWORD dwMessageId, _In_ DWORD dwLanguageId, _Out_ std::basic_string &str, _In_opt_ va_list *Arguments) { @@ -293,11 +371,6 @@ inline DWORD FormatMessage(_In_ DWORD dwFlags, _In_opt_ LPCVOID lpSource, _In_ D } -/// -/// Formats a message string. -/// -/// \sa [FormatMessage function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351.aspx) -/// template inline DWORD FormatMessage(_In_ DWORD dwFlags, _In_opt_ LPCVOID lpSource, _In_ DWORD dwMessageId, _In_ DWORD dwLanguageId, _Out_ std::basic_string &str, _In_opt_ va_list *Arguments) { @@ -311,9 +384,6 @@ inline DWORD FormatMessage(_In_ DWORD dwFlags, _In_opt_ LPCVOID lpSource, _In_ D namespace winstd { - /// - /// Deleter for unique_ptr using LocalFree - /// template struct LocalFree_delete { typedef LocalFree_delete<_Ty> _Myt; ///< This type @@ -338,9 +408,6 @@ namespace winstd }; - /// - /// Deleter for unique_ptr to array of unknown size using LocalFree - /// template struct LocalFree_delete<_Ty[]> { typedef LocalFree_delete<_Ty> _Myt; ///< This type @@ -369,17 +436,6 @@ namespace winstd }; - /// - /// \defgroup WinStdSysHandles System Handles - /// Simplifies work with object handles of various type - /// - /// @{ - - /// - /// Base abstract template class to support generic object handle keeping - /// - /// It provides basic operators and methods common to all descendands of this class establishing a base to ease the replacement of native object handle type with classes in object-oriented approach. - /// template class handle { @@ -622,9 +678,6 @@ namespace winstd }; - /// - /// Base abstract template class to support object handle keeping for objects that support handle duplication - /// template class dplhandle : public handle { @@ -710,9 +763,6 @@ namespace winstd /// @} - /// - /// Helper class to allow limited size FIFO queues implemented as vector of elements - /// template class vector_queue { @@ -1104,15 +1154,6 @@ namespace winstd }; - /// - /// \defgroup WinStdExceptions Exceptions - /// Additional exceptions - /// - /// @{ - - /// - /// Numerical runtime error - /// template class num_runtime_error : public std::runtime_error { @@ -1187,9 +1228,6 @@ namespace winstd }; - /// - /// Windows runtime error - /// class WINSTD_API win_runtime_error : public num_runtime_error { public: @@ -1246,24 +1284,6 @@ namespace winstd }; - /// @} - - /// - /// \defgroup WinStdStrFormat String Formatting - /// Formatted string generation - /// - /// \par Example - /// \code - /// // Please note the PCSTR typecasting invokes an operator to return - /// // pointer to formatted buffer rather than class reference itself. - /// cout << (PCSTR)(winstd::string_printf("%i is less than %i.\n", 1, 5)); - /// \endcode - /// - /// @{ - - /// - /// Base template class to support string formatting using `printf()` style templates - /// template class basic_string_printf : public std::basic_string<_Elem, _Traits, _Ax> { @@ -1328,9 +1348,6 @@ namespace winstd }; - /// - /// Base template class to support string formatting using `FormatMessage()` style templates - /// template class basic_string_msg : public std::basic_string<_Elem, _Traits, _Ax> { @@ -1438,9 +1455,7 @@ namespace winstd } }; - /// - /// Base template class to support converting GUID to string - /// + template class basic_string_guid : public std::basic_string<_Elem, _Traits, _Ax> { @@ -1467,9 +1482,6 @@ namespace winstd }; - /// - /// Single-byte character implementation of a class to support converting GUID to string - /// class WINSTD_API string_guid : public basic_string_guid, std::allocator > { public: @@ -1490,9 +1502,6 @@ namespace winstd }; - /// - /// Wide character implementation of a class to support converting GUID to string - /// class WINSTD_API wstring_guid : public basic_string_guid, std::allocator > { public: @@ -1512,24 +1521,11 @@ namespace winstd /// @} }; - /// @} - - /// \defgroup WinStdMemSanitize Auto-sanitize Memory Management - /// Sanitizes memory before dismissed - /// - /// @{ // winstd::sanitizing_allocator::destroy() member generates _Ptr parameter not used warning for primitive datatypes _Ty. #pragma warning(push) #pragma warning(disable: 4100) - /// - /// An allocator template that sanitizes each memory block before it is destroyed or reallocated - /// - /// \note - /// `sanitizing_allocator` introduces a performance penalty. However, it provides an additional level of security. - /// Use for security sensitive data memory storage only. - /// template class sanitizing_allocator : public std::allocator<_Ty> { @@ -1583,6 +1579,4 @@ namespace winstd }; #pragma warning(pop) - - /// @} } diff --git a/include/WinStd/Cred.h b/include/WinStd/Cred.h index 6b455f12..104f24ea 100644 --- a/include/WinStd/Cred.h +++ b/include/WinStd/Cred.h @@ -26,27 +26,71 @@ namespace winstd { + /// + /// \defgroup WinStdCryptoAPI Cryptography API + /// Integrates WinStd classes with Microsoft Cryptography API + /// + /// @{ + + /// + /// Deleter for unique_ptr using CredFree + /// template struct CredFree_delete; + + /// + /// Deleter for unique_ptr to array of unknown size using CredFree + /// template struct CredFree_delete<_Ty[]>; + + /// @} } + +/// \addtogroup WinStdCryptoAPI +/// @{ + +/// +/// Enumerates the credentials from the user's credential set. The credential set used is the one associated with the logon session of the current token. The token must not have the user's SID disabled. +/// +/// \sa [CredEnumerate function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa374794.aspx) +/// inline BOOL CredEnumerate(_In_ LPCTSTR Filter, _In_ DWORD Flags, _Out_ DWORD *Count, _Out_ std::unique_ptr > &cCredentials); + +/// +/// Encrypts the specified credentials so that only the current security context can decrypt them. +/// +/// \sa [CredProtect function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa374803.aspx) +/// template inline BOOL CredProtectA(_In_ BOOL fAsSelf, _In_ LPCSTR pszCredentials, _In_ DWORD cchCredentials, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sProtectedCredentials, _Out_ CRED_PROTECTION_TYPE *ProtectionType); + +/// +/// Encrypts the specified credentials so that only the current security context can decrypt them. +/// +/// \sa [CredProtect function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa374803.aspx) +/// template inline BOOL CredProtectW(_In_ BOOL fAsSelf, _In_ LPCWSTR pszCredentials, _In_ DWORD cchCredentials, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sProtectedCredentials, _Out_ CRED_PROTECTION_TYPE *ProtectionType); + +/// +/// Decrypts credentials that were previously encrypted by using the CredProtect function. +/// +/// \sa [CredUnprotect function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa375186.aspx) +/// template inline BOOL CredUnprotectA(_In_ BOOL fAsSelf, _In_ LPCSTR pszProtectedCredentials, _In_ DWORD cchCredentials, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sCredentials); + +/// +/// Decrypts credentials that were previously encrypted by using the CredProtect function. +/// +/// \sa [CredUnprotect function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa375186.aspx) +/// template inline BOOL CredUnprotectW(_In_ BOOL fAsSelf, _In_ LPCWSTR pszProtectedCredentials, _In_ DWORD cchCredentials, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sCredentials); +/// @} + #pragma once namespace winstd { - /// \addtogroup WinStdCryptoAPI - /// @{ - - /// - /// Deleter for unique_ptr using CredFree - /// template struct CredFree_delete { typedef CredFree_delete<_Ty> _Myt; ///< This type @@ -71,9 +115,6 @@ namespace winstd }; - /// - /// Deleter for unique_ptr to array of unknown size using CredFree - /// template struct CredFree_delete<_Ty[]> { typedef CredFree_delete<_Ty> _Myt; ///< This type @@ -100,22 +141,9 @@ namespace winstd CredFree(_Ptr); } }; - - /// @} } -/// -/// \defgroup WinStdCryptoAPI Cryptography API -/// Integrates WinStd classes with Microsoft Cryptography API -/// -/// @{ - -/// -/// Enumerates the credentials from the user's credential set. The credential set used is the one associated with the logon session of the current token. The token must not have the user's SID disabled. -/// -/// \sa [CredEnumerate function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa374794.aspx) -/// inline BOOL CredEnumerate(_In_ LPCTSTR Filter, _In_ DWORD Flags, _Out_ DWORD *Count, _Out_ std::unique_ptr > &cCredentials) { PCREDENTIAL *pCredentials; @@ -127,11 +155,6 @@ inline BOOL CredEnumerate(_In_ LPCTSTR Filter, _In_ DWORD Flags, _Out_ DWORD *Co } -/// -/// Encrypts the specified credentials so that only the current security context can decrypt them. -/// -/// \sa [CredProtect function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa374803.aspx) -/// template inline BOOL CredProtectA(_In_ BOOL fAsSelf, _In_ LPCSTR pszCredentials, _In_ DWORD cchCredentials, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sProtectedCredentials, _Out_ CRED_PROTECTION_TYPE *ProtectionType) { @@ -156,11 +179,6 @@ inline BOOL CredProtectA(_In_ BOOL fAsSelf, _In_ LPCSTR pszCredentials, _In_ DWO } -/// -/// Encrypts the specified credentials so that only the current security context can decrypt them. -/// -/// \sa [CredProtect function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa374803.aspx) -/// template inline BOOL CredProtectW(_In_ BOOL fAsSelf, _In_ LPCWSTR pszCredentials, _In_ DWORD cchCredentials, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sProtectedCredentials, _Out_ CRED_PROTECTION_TYPE *ProtectionType) { @@ -185,11 +203,6 @@ inline BOOL CredProtectW(_In_ BOOL fAsSelf, _In_ LPCWSTR pszCredentials, _In_ DW } -/// -/// Decrypts credentials that were previously encrypted by using the CredProtect function. -/// -/// \sa [CredUnprotect function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa375186.aspx) -/// template inline BOOL CredUnprotectA(_In_ BOOL fAsSelf, _In_ LPCSTR pszProtectedCredentials, _In_ DWORD cchCredentials, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sCredentials) { @@ -214,11 +227,6 @@ inline BOOL CredUnprotectA(_In_ BOOL fAsSelf, _In_ LPCSTR pszProtectedCredential } -/// -/// Decrypts credentials that were previously encrypted by using the CredProtect function. -/// -/// \sa [CredUnprotect function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa375186.aspx) -/// template inline BOOL CredUnprotectW(_In_ BOOL fAsSelf, _In_ LPCWSTR pszProtectedCredentials, _In_ DWORD cchCredentials, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sCredentials) { @@ -241,5 +249,3 @@ inline BOOL CredUnprotectW(_In_ BOOL fAsSelf, _In_ LPCWSTR pszProtectedCredentia return FALSE; } - -/// @} diff --git a/include/WinStd/Crypt.h b/include/WinStd/Crypt.h index ea2dd58b..fb994451 100644 --- a/include/WinStd/Crypt.h +++ b/include/WinStd/Crypt.h @@ -25,31 +25,6 @@ #include #include -template inline DWORD CertGetNameStringA(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwType, _In_ DWORD dwFlags, _In_ void *pvTypePara, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sNameString); -template inline DWORD CertGetNameStringW(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwType, _In_ DWORD dwFlags, _In_ void *pvTypePara, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sNameString); -template inline BOOL WINAPI CertGetCertificateContextProperty(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwPropId, _Out_ std::vector<_Ty, _Ax> &aData); -template inline BOOL CryptGetHashParam(_In_ HCRYPTHASH hHash, _In_ DWORD dwParam, _Out_ std::vector<_Ty, _Ax> &aData, _In_ DWORD dwFlags); -template inline BOOL CryptGetKeyParam(_In_ HCRYPTKEY hKey, _In_ DWORD dwParam, _Out_ std::vector<_Ty, _Ax> &aData, _In_ DWORD dwFlags); -template inline BOOL CryptGetKeyParam(_In_ HCRYPTKEY hKey, _In_ DWORD dwParam, _Out_ T &data, _In_ DWORD dwFlags); -template inline BOOL CryptExportKey(_In_ HCRYPTKEY hKey, _In_ HCRYPTKEY hExpKey, _In_ DWORD dwBlobType, _In_ DWORD dwFlags, _Out_ std::vector<_Ty, _Ax> &aData); -template inline BOOL CryptEncrypt(_In_ HCRYPTKEY hKey, _In_opt_ HCRYPTHASH hHash, _In_ BOOL Final, _In_ DWORD dwFlags, _Inout_ std::vector<_Ty, _Ax> &aData); -template inline BOOL CryptDecrypt(_In_ HCRYPTKEY hKey, _In_opt_ HCRYPTHASH hHash, _In_ BOOL Final, _In_ DWORD dwFlags, _Inout_ std::vector<_Ty, _Ax> &aData); -namespace winstd -{ - class WINSTD_API cert_context; - class WINSTD_API cert_chain_context; - class WINSTD_API cert_store; - class WINSTD_API crypt_prov; - class WINSTD_API crypt_hash; - class WINSTD_API crypt_key; - class WINSTD_API data_blob; -} - -#pragma once - -#include - - /// /// \defgroup WinStdCryptoAPI Cryptography API /// Integrates WinStd classes with Microsoft Cryptography API @@ -61,6 +36,114 @@ namespace winstd /// /// \sa [CertGetNameString function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa376086.aspx) /// +template inline DWORD CertGetNameStringA(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwType, _In_ DWORD dwFlags, _In_ void *pvTypePara, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sNameString); + +/// +/// Obtains the subject or issuer name from a certificate [CERT_CONTEXT](https://msdn.microsoft.com/en-us/library/windows/desktop/aa377189.aspx) structure and stores it in a std::wstring string. +/// +/// \sa [CertGetNameString function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa376086.aspx) +/// +template inline DWORD CertGetNameStringW(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwType, _In_ DWORD dwFlags, _In_ void *pvTypePara, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sNameString); + +/// +/// Retrieves the information contained in an extended property of a certificate context. +/// +/// \sa [CertGetCertificateContextProperty function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa376079.aspx) +/// +template inline BOOL WINAPI CertGetCertificateContextProperty(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwPropId, _Out_ std::vector<_Ty, _Ax> &aData); + +/// +/// Retrieves data that governs the operations of a hash object. The actual hash value can be retrieved by using this function. +/// +/// \sa [CryptGetHashParam function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379947.aspx) +/// +template inline BOOL CryptGetHashParam(_In_ HCRYPTHASH hHash, _In_ DWORD dwParam, _Out_ std::vector<_Ty, _Ax> &aData, _In_ DWORD dwFlags); + +/// +/// Retrieves data that governs the operations of a key. +/// +/// \sa [CryptGetKeyParam function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379949.aspx) +/// +template inline BOOL CryptGetKeyParam(_In_ HCRYPTKEY hKey, _In_ DWORD dwParam, _Out_ std::vector<_Ty, _Ax> &aData, _In_ DWORD dwFlags); + +/// +/// Retrieves data that governs the operations of a key. +/// +/// \sa [CryptGetKeyParam function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379949.aspx) +/// +template inline BOOL CryptGetKeyParam(_In_ HCRYPTKEY hKey, _In_ DWORD dwParam, _Out_ T &data, _In_ DWORD dwFlags); + +/// +/// Exports a cryptographic key or a key pair from a cryptographic service provider (CSP) in a secure manner. +/// +/// \sa [CryptExportKey function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379931.aspx) +/// +template inline BOOL CryptExportKey(_In_ HCRYPTKEY hKey, _In_ HCRYPTKEY hExpKey, _In_ DWORD dwBlobType, _In_ DWORD dwFlags, _Out_ std::vector<_Ty, _Ax> &aData); + +/// +/// Encrypts data. +/// +/// \sa [CryptEncrypt function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379924.aspx) +/// +template inline BOOL CryptEncrypt(_In_ HCRYPTKEY hKey, _In_opt_ HCRYPTHASH hHash, _In_ BOOL Final, _In_ DWORD dwFlags, _Inout_ std::vector<_Ty, _Ax> &aData); + +/// +/// Decrypts data previously encrypted by using the CryptEncrypt function. +/// +/// \sa [CryptDecrypt function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379913.aspx) +/// +template inline BOOL CryptDecrypt(_In_ HCRYPTKEY hKey, _In_opt_ HCRYPTHASH hHash, _In_ BOOL Final, _In_ DWORD dwFlags, _Inout_ std::vector<_Ty, _Ax> &aData); + +/// @} + +namespace winstd +{ + /// \addtogroup WinStdCryptoAPI + /// @{ + + /// + /// PCCERT_CONTEXT wrapper class + /// + class WINSTD_API cert_context; + + /// + /// PCCERT_CHAIN_CONTEXT wrapper class + /// + class WINSTD_API cert_chain_context; + + /// + /// HCERTSTORE wrapper class + /// + class WINSTD_API cert_store; + + /// + /// HCRYPTPROV wrapper class + /// + class WINSTD_API crypt_prov; + + /// + /// HCRYPTHASH wrapper class + /// + class WINSTD_API crypt_hash; + + /// + /// HCRYPTKEY wrapper class + /// + class WINSTD_API crypt_key; + + /// + /// DATA_BLOB wrapper class + /// + class WINSTD_API data_blob; + + /// @} +} + +#pragma once + +#include + + template inline DWORD CertGetNameStringA(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwType, _In_ DWORD dwFlags, _In_ void *pvTypePara, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sNameString) { @@ -75,11 +158,6 @@ inline DWORD CertGetNameStringA(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwT } -/// -/// Obtains the subject or issuer name from a certificate [CERT_CONTEXT](https://msdn.microsoft.com/en-us/library/windows/desktop/aa377189.aspx) structure and stores it in a std::wstring string. -/// -/// \sa [CertGetNameString function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa376086.aspx) -/// template inline DWORD CertGetNameStringW(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwType, _In_ DWORD dwFlags, _In_ void *pvTypePara, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sNameString) { @@ -94,11 +172,6 @@ inline DWORD CertGetNameStringW(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwT } -/// -/// Retrieves the information contained in an extended property of a certificate context. -/// -/// \sa [CertGetCertificateContextProperty function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa376079.aspx) -/// template inline BOOL WINAPI CertGetCertificateContextProperty(_In_ PCCERT_CONTEXT pCertContext, _In_ DWORD dwPropId, _Out_ std::vector<_Ty, _Ax> &aData) { @@ -121,11 +194,6 @@ inline BOOL WINAPI CertGetCertificateContextProperty(_In_ PCCERT_CONTEXT pCertCo } -/// -/// Retrieves data that governs the operations of a hash object. The actual hash value can be retrieved by using this function. -/// -/// \sa [CryptGetHashParam function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379947.aspx) -/// template inline BOOL CryptGetHashParam(_In_ HCRYPTHASH hHash, _In_ DWORD dwParam, _Out_ std::vector<_Ty, _Ax> &aData, _In_ DWORD dwFlags) { @@ -148,11 +216,6 @@ inline BOOL CryptGetHashParam(_In_ HCRYPTHASH hHash, _In_ DWORD dwParam, _Out_ s } -/// -/// Retrieves data that governs the operations of a hash object. The actual hash value can be retrieved by using this function. -/// -/// \sa [CryptGetHashParam function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379947.aspx) -/// template inline BOOL CryptGetHashParam(_In_ HCRYPTHASH hHash, _In_ DWORD dwParam, _Out_ T &data, _In_ DWORD dwFlags) { @@ -161,11 +224,6 @@ inline BOOL CryptGetHashParam(_In_ HCRYPTHASH hHash, _In_ DWORD dwParam, _Out_ T } -/// -/// Retrieves data that governs the operations of a key. -/// -/// \sa [CryptGetKeyParam function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379949.aspx) -/// template inline BOOL CryptGetKeyParam(_In_ HCRYPTKEY hKey, _In_ DWORD dwParam, _Out_ std::vector<_Ty, _Ax> &aData, _In_ DWORD dwFlags) { @@ -188,11 +246,6 @@ inline BOOL CryptGetKeyParam(_In_ HCRYPTKEY hKey, _In_ DWORD dwParam, _Out_ std: } -/// -/// Retrieves data that governs the operations of a key. -/// -/// \sa [CryptGetKeyParam function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379949.aspx) -/// template inline BOOL CryptGetKeyParam(_In_ HCRYPTKEY hKey, _In_ DWORD dwParam, _Out_ T &data, _In_ DWORD dwFlags) { @@ -201,11 +254,6 @@ inline BOOL CryptGetKeyParam(_In_ HCRYPTKEY hKey, _In_ DWORD dwParam, _Out_ T &d } -/// -/// Exports a cryptographic key or a key pair from a cryptographic service provider (CSP) in a secure manner. -/// -/// \sa [CryptExportKey function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379931.aspx) -/// template inline BOOL CryptExportKey(_In_ HCRYPTKEY hKey, _In_ HCRYPTKEY hExpKey, _In_ DWORD dwBlobType, _In_ DWORD dwFlags, _Out_ std::vector<_Ty, _Ax> &aData) { @@ -222,11 +270,6 @@ inline BOOL CryptExportKey(_In_ HCRYPTKEY hKey, _In_ HCRYPTKEY hExpKey, _In_ DWO } -/// -/// Encrypts data. -/// -/// \sa [CryptEncrypt function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379924.aspx) -/// template inline BOOL CryptEncrypt(_In_ HCRYPTKEY hKey, _In_opt_ HCRYPTHASH hHash, _In_ BOOL Final, _In_ DWORD dwFlags, _Inout_ std::vector<_Ty, _Ax> &aData) { @@ -273,11 +316,6 @@ inline BOOL CryptEncrypt(_In_ HCRYPTKEY hKey, _In_opt_ HCRYPTHASH hHash, _In_ BO } -/// -/// Decrypts data previously encrypted by using the CryptEncrypt function. -/// -/// \sa [CryptDecrypt function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379913.aspx) -/// template inline BOOL CryptDecrypt(_In_ HCRYPTKEY hKey, _In_opt_ HCRYPTHASH hHash, _In_ BOOL Final, _In_ DWORD dwFlags, _Inout_ std::vector<_Ty, _Ax> &aData) { @@ -292,17 +330,9 @@ inline BOOL CryptDecrypt(_In_ HCRYPTKEY hKey, _In_opt_ HCRYPTHASH hHash, _In_ BO return FALSE; } -/// @} - namespace winstd { - /// \addtogroup WinStdCryptoAPI - /// @{ - - /// - /// PCCERT_CONTEXT wrapper class - /// class WINSTD_API cert_context : public dplhandle { public: @@ -462,9 +492,6 @@ namespace winstd }; - /// - /// PCCERT_CHAIN_CONTEXT wrapper class - /// class WINSTD_API cert_chain_context : public dplhandle { public: @@ -542,9 +569,6 @@ namespace winstd }; - /// - /// HCERTSTORE wrapper class - /// class WINSTD_API cert_store : public handle { public: @@ -639,9 +663,6 @@ namespace winstd }; - /// - /// HCRYPTPROV wrapper class - /// class WINSTD_API crypt_prov : public handle { public: @@ -717,9 +738,6 @@ namespace winstd }; - /// - /// HCRYPTHASH wrapper class - /// class WINSTD_API crypt_hash : public dplhandle { public: @@ -797,9 +815,6 @@ namespace winstd }; - /// - /// HCRYPTKEY wrapper class - /// class WINSTD_API crypt_key : public dplhandle { public: @@ -928,9 +943,6 @@ namespace winstd }; - /// - /// DATA_BLOB wrapper class - /// class WINSTD_API data_blob : public DATA_BLOB { public: @@ -1043,6 +1055,4 @@ namespace winstd return pbData; } }; - - /// @} } diff --git a/include/WinStd/EAP.h b/include/WinStd/EAP.h index 92611462..9b3bdb21 100644 --- a/include/WinStd/EAP.h +++ b/include/WinStd/EAP.h @@ -23,20 +23,6 @@ #include #include // Must include after -namespace winstd -{ - enum eap_type_t; - - class WINSTD_API eap_attr; - class WINSTD_API eap_method_prop; - class WINSTD_API eap_packet; -} - -#pragma once - -#include - - namespace winstd { /// @@ -50,6 +36,33 @@ namespace winstd /// /// \sa [Extensible Authentication Protocol (EAP) Registry (Chapter: Method Types)](https://www.iana.org/assignments/eap-numbers/eap-numbers.xhtml#eap-numbers-4) /// + enum eap_type_t; + + /// + /// EAP_ATTRIBUTE wrapper class + /// + class WINSTD_API eap_attr; + + /// + /// EAP_METHOD_PROPERTY wrapper class + /// + class WINSTD_API eap_method_prop; + + /// + /// EapPacket wrapper class + /// + class WINSTD_API eap_packet; + + /// @} +} + +#pragma once + +#include + + +namespace winstd +{ #pragma warning(suppress: 4480) enum eap_type_t : unsigned char { eap_type_undefined = 0, ///< Undefined EAP type @@ -61,9 +74,6 @@ namespace winstd }; - /// - /// EAP_ATTRIBUTE wrapper class - /// class WINSTD_API __declspec(novtable) eap_attr : public EAP_ATTRIBUTE { public: @@ -169,9 +179,6 @@ namespace winstd }; - /// - /// EAP_METHOD_PROPERTY wrapper class - /// class WINSTD_API __declspec(novtable) eap_method_prop : public EAP_METHOD_PROPERTY { public: @@ -221,9 +228,6 @@ namespace winstd }; - /// - /// EapPacket wrapper class - /// class WINSTD_API eap_packet : public dplhandle { public: @@ -304,6 +308,4 @@ namespace winstd /// virtual handle_type duplicate_internal(_In_ handle_type h) const; }; - - /// @} } diff --git a/include/WinStd/ETW.h b/include/WinStd/ETW.h index 9ab9db29..f7eb8e10 100644 --- a/include/WinStd/ETW.h +++ b/include/WinStd/ETW.h @@ -30,102 +30,6 @@ #include #include -inline ULONG TdhGetEventInformation(_In_ PEVENT_RECORD pEvent, _In_ ULONG TdhContextCount, _In_ PTDH_CONTEXT pTdhContext, _Out_ std::unique_ptr &info); -inline ULONG TdhGetEventMapInformation(_In_ PEVENT_RECORD pEvent, _In_ LPWSTR pMapName, _Out_ std::unique_ptr &info); -template inline ULONG TdhGetProperty(_In_ PEVENT_RECORD pEvent, _In_ ULONG TdhContextCount, _In_ PTDH_CONTEXT pTdhContext, _In_ ULONG PropertyDataCount, _In_ PPROPERTY_DATA_DESCRIPTOR pPropertyData, _Out_ std::vector<_Ty, _Ax> &aData); - -namespace winstd -{ - class WINSTD_API event_data; - class WINSTD_API event_rec; - class WINSTD_API event_provider; - class WINSTD_API event_session; - class WINSTD_API event_trace; - class WINSTD_API event_trace_enabler; - - class event_fn_auto; - template class event_fn_auto_ret; -} - -#pragma once - - -/// -/// Retrieves metadata about an event. -/// -/// \sa [TdhGetEventInformation function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa964840.aspx) -/// -inline ULONG TdhGetEventInformation(_In_ PEVENT_RECORD pEvent, _In_ ULONG TdhContextCount, _In_ PTDH_CONTEXT pTdhContext, _Out_ std::unique_ptr &info) -{ - BYTE szBuffer[WINSTD_STACK_BUFFER_BYTES]; - ULONG ulSize = sizeof(szBuffer), ulResult; - - // Try with stack buffer first. - ulResult = TdhGetEventInformation(pEvent, TdhContextCount, pTdhContext, (PTRACE_EVENT_INFO)szBuffer, &ulSize); - if (ulResult == ERROR_SUCCESS) { - // Copy from stack. - info.reset((PTRACE_EVENT_INFO)new char[ulSize]); - memcpy(info.get(), szBuffer, ulSize); - return ERROR_SUCCESS; - } else if (ulResult == ERROR_INSUFFICIENT_BUFFER) { - // Create buffer on heap and retry. - info.reset((PTRACE_EVENT_INFO)new char[ulSize]); - return TdhGetEventInformation(pEvent, TdhContextCount, pTdhContext, info.get(), &ulSize); - } - - return ulResult; -} - - -/// -/// Retrieves information about the event map contained in the event. -/// -/// \sa [TdhGetEventMapInformation function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa964841.aspx) -/// -inline ULONG TdhGetEventMapInformation(_In_ PEVENT_RECORD pEvent, _In_ LPWSTR pMapName, _Out_ std::unique_ptr &info) -{ - BYTE szBuffer[WINSTD_STACK_BUFFER_BYTES]; - ULONG ulSize = sizeof(szBuffer), ulResult; - - // Try with stack buffer first. - ulResult = TdhGetEventMapInformation(pEvent, pMapName, (PEVENT_MAP_INFO)szBuffer, &ulSize); - if (ulResult == ERROR_SUCCESS) { - // Copy from stack. - info.reset((PEVENT_MAP_INFO)new char[ulSize]); - memcpy(info.get(), szBuffer, ulSize); - return ERROR_SUCCESS; - } else if (ulResult == ERROR_INSUFFICIENT_BUFFER) { - // Create buffer on heap and retry. - info.reset((PEVENT_MAP_INFO)new char[ulSize]); - return TdhGetEventMapInformation(pEvent, pMapName, info.get(), &ulSize); - } - - return ulResult; -} - - -/// -/// Retrieves a property value from the event data. -/// -/// \sa [TdhGetProperty function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa964843.aspx) -/// -template -inline ULONG TdhGetProperty(_In_ PEVENT_RECORD pEvent, _In_ ULONG TdhContextCount, _In_ PTDH_CONTEXT pTdhContext, _In_ ULONG PropertyDataCount, _In_ PPROPERTY_DATA_DESCRIPTOR pPropertyData, _Out_ std::vector<_Ty, _Ax> &aData) -{ - ULONG ulSize, ulResult; - - // Query property size. - ulResult = TdhGetPropertySize(pEvent, TdhContextCount, pTdhContext, PropertyDataCount, pPropertyData, &ulSize); - if (ulResult == ERROR_SUCCESS) { - // Query property value. - aData.resize((ulSize + sizeof(_Ty) - 1) / sizeof(_Ty)); - ulResult = TdhGetProperty(pEvent, TdhContextCount, pTdhContext, PropertyDataCount, pPropertyData, ulSize, (LPBYTE)aData.data()); - } - - return ulResult; -} - - namespace winstd { /// @@ -134,10 +38,84 @@ namespace winstd /// /// @{ - /// /// EVENT_DATA_DESCRIPTOR wrapper /// + class WINSTD_API event_data; + + /// + /// EVENT_RECORD wrapper + /// + class WINSTD_API event_rec; + + /// + /// ETW event provider + /// + class WINSTD_API event_provider; + + /// + /// ETW session + /// + class WINSTD_API event_session; + + /// + /// ETW trace + /// + class WINSTD_API event_trace; + + /// + /// Helper class to enable event provider in constructor and disables it in destructor + /// + class WINSTD_API event_trace_enabler; + + /// + /// Helper class to write an event on entry/exit of scope. + /// + /// It writes one string event at creation and another at destruction. + /// + class event_fn_auto; + + /// + /// Helper template to write an event on entry/exit of scope with one parameter (typically result). + /// + /// It writes one string event at creation and another at destruction, with allowing one sprintf type parameter for string event at destruction. + /// + template class event_fn_auto_ret; + + /// @} +} + +/// \addtogroup WinStdCryptoAPI +/// @{ + +/// +/// Retrieves metadata about an event. +/// +/// \sa [TdhGetEventInformation function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa964840.aspx) +/// +inline ULONG TdhGetEventInformation(_In_ PEVENT_RECORD pEvent, _In_ ULONG TdhContextCount, _In_ PTDH_CONTEXT pTdhContext, _Out_ std::unique_ptr &info); + +/// +/// Retrieves information about the event map contained in the event. +/// +/// \sa [TdhGetEventMapInformation function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa964841.aspx) +/// +inline ULONG TdhGetEventMapInformation(_In_ PEVENT_RECORD pEvent, _In_ LPWSTR pMapName, _Out_ std::unique_ptr &info); + +/// +/// Retrieves a property value from the event data. +/// +/// \sa [TdhGetProperty function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa964843.aspx) +/// +template inline ULONG TdhGetProperty(_In_ PEVENT_RECORD pEvent, _In_ ULONG TdhContextCount, _In_ PTDH_CONTEXT pTdhContext, _In_ ULONG PropertyDataCount, _In_ PPROPERTY_DATA_DESCRIPTOR pPropertyData, _Out_ std::vector<_Ty, _Ax> &aData); + +/// @} + +#pragma once + + +namespace winstd +{ class WINSTD_API event_data : public EVENT_DATA_DESCRIPTOR { public: @@ -250,9 +228,6 @@ namespace winstd }; - /// - /// EVENT_RECORD wrapper - /// class WINSTD_API event_rec : public EVENT_RECORD { public: @@ -392,9 +367,6 @@ namespace winstd }; - /// - /// ETW event provider - /// class WINSTD_API event_provider : public handle { public: @@ -571,9 +543,6 @@ namespace winstd }; - /// - /// ETW session - /// class WINSTD_API event_session : public handle { public: @@ -754,9 +723,46 @@ namespace winstd }; - /// - /// Helper class to enable event provider in constructor and disables it in destructor - /// + class WINSTD_API event_trace : public handle + { + public: + /// + /// Closes the trace. + /// + /// \sa [CloseTrace function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363686.aspx) + /// + virtual ~event_trace(); + + + /// + /// Opens a real-time trace session or log file for consuming. + /// + /// \return + /// - `ERROR_SUCCESS` when creation succeeds; + /// - error code otherwise. + /// + /// \sa [OpenTrace function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364089.aspx) + /// + inline bool create(_Inout_ PEVENT_TRACE_LOGFILE Logfile) + { + handle_type h = OpenTrace(Logfile); + if (h != (TRACEHANDLE)INVALID_HANDLE_VALUE) { + attach(h); + return true; + } else + return false; + } + + protected: + /// + /// Closes the trace. + /// + /// \sa [CloseTrace function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363686.aspx) + /// + virtual void free_internal(); + }; + + class WINSTD_API event_trace_enabler { public: @@ -862,54 +868,6 @@ namespace winstd }; - /// - /// ETW trace - /// - class WINSTD_API event_trace : public handle - { - public: - /// - /// Closes the trace. - /// - /// \sa [CloseTrace function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363686.aspx) - /// - virtual ~event_trace(); - - - /// - /// Opens a real-time trace session or log file for consuming. - /// - /// \return - /// - `ERROR_SUCCESS` when creation succeeds; - /// - error code otherwise. - /// - /// \sa [OpenTrace function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364089.aspx) - /// - inline bool create(_Inout_ PEVENT_TRACE_LOGFILE Logfile) - { - handle_type h = OpenTrace(Logfile); - if (h != (TRACEHANDLE)INVALID_HANDLE_VALUE) { - attach(h); - return true; - } else - return false; - } - - protected: - /// - /// Closes the trace. - /// - /// \sa [CloseTrace function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363686.aspx) - /// - virtual void free_internal(); - }; - - - /// - /// Helper class to write an event on entry/exit of scope. - /// - /// It writes one string event at creation and another at destruction. - /// class event_fn_auto { public: @@ -996,11 +954,6 @@ namespace winstd }; - /// - /// Helper template to write an event on entry/exit of scope with one parameter (typically result). - /// - /// It writes one string event at creation and another at destruction, with allowing one sprintf type parameter for string event at destruction. - /// template class event_fn_auto_ret { @@ -1094,6 +1047,65 @@ namespace winstd EVENT_DATA_DESCRIPTOR m_desc[2]; ///< Function name and return value T &m_result; ///< Function result }; - - /// @} +} + + +inline ULONG TdhGetEventInformation(_In_ PEVENT_RECORD pEvent, _In_ ULONG TdhContextCount, _In_ PTDH_CONTEXT pTdhContext, _Out_ std::unique_ptr &info) +{ + BYTE szBuffer[WINSTD_STACK_BUFFER_BYTES]; + ULONG ulSize = sizeof(szBuffer), ulResult; + + // Try with stack buffer first. + ulResult = TdhGetEventInformation(pEvent, TdhContextCount, pTdhContext, (PTRACE_EVENT_INFO)szBuffer, &ulSize); + if (ulResult == ERROR_SUCCESS) { + // Copy from stack. + info.reset((PTRACE_EVENT_INFO)new char[ulSize]); + memcpy(info.get(), szBuffer, ulSize); + return ERROR_SUCCESS; + } else if (ulResult == ERROR_INSUFFICIENT_BUFFER) { + // Create buffer on heap and retry. + info.reset((PTRACE_EVENT_INFO)new char[ulSize]); + return TdhGetEventInformation(pEvent, TdhContextCount, pTdhContext, info.get(), &ulSize); + } + + return ulResult; +} + + +inline ULONG TdhGetEventMapInformation(_In_ PEVENT_RECORD pEvent, _In_ LPWSTR pMapName, _Out_ std::unique_ptr &info) +{ + BYTE szBuffer[WINSTD_STACK_BUFFER_BYTES]; + ULONG ulSize = sizeof(szBuffer), ulResult; + + // Try with stack buffer first. + ulResult = TdhGetEventMapInformation(pEvent, pMapName, (PEVENT_MAP_INFO)szBuffer, &ulSize); + if (ulResult == ERROR_SUCCESS) { + // Copy from stack. + info.reset((PEVENT_MAP_INFO)new char[ulSize]); + memcpy(info.get(), szBuffer, ulSize); + return ERROR_SUCCESS; + } else if (ulResult == ERROR_INSUFFICIENT_BUFFER) { + // Create buffer on heap and retry. + info.reset((PEVENT_MAP_INFO)new char[ulSize]); + return TdhGetEventMapInformation(pEvent, pMapName, info.get(), &ulSize); + } + + return ulResult; +} + + +template +inline ULONG TdhGetProperty(_In_ PEVENT_RECORD pEvent, _In_ ULONG TdhContextCount, _In_ PTDH_CONTEXT pTdhContext, _In_ ULONG PropertyDataCount, _In_ PPROPERTY_DATA_DESCRIPTOR pPropertyData, _Out_ std::vector<_Ty, _Ax> &aData) +{ + ULONG ulSize, ulResult; + + // Query property size. + ulResult = TdhGetPropertySize(pEvent, TdhContextCount, pTdhContext, PropertyDataCount, pPropertyData, &ulSize); + if (ulResult == ERROR_SUCCESS) { + // Query property value. + aData.resize((ulSize + sizeof(_Ty) - 1) / sizeof(_Ty)); + ulResult = TdhGetProperty(pEvent, TdhContextCount, pTdhContext, PropertyDataCount, pPropertyData, ulSize, (LPBYTE)aData.data()); + } + + return ulResult; } diff --git a/include/WinStd/Hex.h b/include/WinStd/Hex.h index 52c9aaaa..872dfc0e 100644 --- a/include/WinStd/Hex.h +++ b/include/WinStd/Hex.h @@ -23,15 +23,6 @@ #include #include -namespace winstd -{ - class WINSTD_API hex_enc; - class WINSTD_API hex_dec; -} - -#pragma once - - namespace winstd { /// @@ -43,6 +34,21 @@ namespace winstd /// /// Hexadecimal encoding session /// + class WINSTD_API hex_enc; + + /// + /// Hexadecimal decoding session + /// + class WINSTD_API hex_dec; + + /// @} +} + +#pragma once + + +namespace winstd +{ class WINSTD_API hex_enc { public: @@ -96,9 +102,6 @@ namespace winstd }; - /// - /// Hexadecimal decoding session - /// class WINSTD_API hex_dec { public: @@ -183,6 +186,4 @@ namespace winstd unsigned char buf; ///< Internal buffer size_t num; ///< Number of nibbles used in `buf` }; - - /// @} } diff --git a/include/WinStd/MSI.h b/include/WinStd/MSI.h index 3cda60ff..d99cd4f5 100644 --- a/include/WinStd/MSI.h +++ b/include/WinStd/MSI.h @@ -25,21 +25,6 @@ #include #include -template inline UINT MsiGetPropertyA(_In_ MSIHANDLE hInstall, _In_ LPCSTR szName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline UINT MsiGetPropertyW(_In_ MSIHANDLE hInstall, _In_ LPCWSTR szName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline UINT MsiRecordGetStringA(_In_ MSIHANDLE hRecord, _In_ unsigned int iField, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline UINT MsiRecordGetStringW(_In_ MSIHANDLE hRecord, _In_ unsigned int iField, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline UINT MsiFormatRecordA(MSIHANDLE hInstall, MSIHANDLE hRecord, std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline UINT MsiFormatRecordW(MSIHANDLE hInstall, MSIHANDLE hRecord, std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline UINT MsiRecordReadStream(_In_ MSIHANDLE hRecord, _In_ unsigned int iField, _Out_ std::vector<_Ty, _Ax> &binData); -template inline UINT MsiGetTargetPathA(_In_ MSIHANDLE hInstall, _In_ LPCSTR szFolder, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline UINT MsiGetTargetPathW(_In_ MSIHANDLE hInstall, _In_ LPCWSTR szFolder, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline INSTALLSTATE MsiGetComponentPathA(_In_ LPCSTR szProduct, _In_ LPCSTR szComponent, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline INSTALLSTATE MsiGetComponentPathW(_In_ LPCWSTR szProduct, _In_ LPCWSTR szComponent, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); - -#pragma once - - /// /// \defgroup WinStdMSIAPI Microsoft Installer API /// Integrates WinStd classes with Microsoft Installer API @@ -51,6 +36,83 @@ template inline INSTALLSTATE MsiGetCompon /// /// \sa [MsiGetProperty function](https://msdn.microsoft.com/en-us/library/aa370134.aspx) /// +template inline UINT MsiGetPropertyA(_In_ MSIHANDLE hInstall, _In_ LPCSTR szName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Gets the value for an installer property and stores it in a std::wstring string. +/// +/// \sa [MsiGetProperty function](https://msdn.microsoft.com/en-us/library/aa370134.aspx) +/// +template inline UINT MsiGetPropertyW(_In_ MSIHANDLE hInstall, _In_ LPCWSTR szName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Returns the string value of a record field and stores it in a std::string string. +/// +/// \sa [MsiRecordGetString function](https://msdn.microsoft.com/en-us/library/aa370368.aspx) +/// +template inline UINT MsiRecordGetStringA(_In_ MSIHANDLE hRecord, _In_ unsigned int iField, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Returns the string value of a record field and stores it in a std::wstring string. +/// +/// \sa [MsiRecordGetString function](https://msdn.microsoft.com/en-us/library/aa370368.aspx) +/// +template inline UINT MsiRecordGetStringW(_In_ MSIHANDLE hRecord, _In_ unsigned int iField, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Formats record field data and properties using a format string and stores it in a std::string string. +/// +/// \sa [MsiFormatRecord function](https://msdn.microsoft.com/en-us/library/aa370109.aspx) +/// +template inline UINT MsiFormatRecordA(MSIHANDLE hInstall, MSIHANDLE hRecord, std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Formats record field data and properties using a format string and stores it in a std::wstring string. +/// +/// \sa [MsiFormatRecord function](https://msdn.microsoft.com/en-us/library/aa370109.aspx) +/// +template inline UINT MsiFormatRecordW(MSIHANDLE hInstall, MSIHANDLE hRecord, std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Reads bytes from a record stream field into a std::vector buffer. +/// +/// \sa [MsiRecordReadStream function](https://msdn.microsoft.com/en-us/library/aa370370.aspx) +/// +template inline UINT MsiRecordReadStream(_In_ MSIHANDLE hRecord, _In_ unsigned int iField, _Out_ std::vector<_Ty, _Ax> &binData); + +/// +/// Returns the full target path for a folder in the Directory table and stores it in a std::string string. +/// +/// \sa [MsiGetTargetPath function](https://msdn.microsoft.com/en-us/library/aa370303.aspx) +/// +template inline UINT MsiGetTargetPathA(_In_ MSIHANDLE hInstall, _In_ LPCSTR szFolder, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Returns the full target path for a folder in the Directory table and stores it in a std::wstring string. +/// +/// \sa [MsiGetTargetPath function](https://msdn.microsoft.com/en-us/library/aa370303.aspx) +/// +template inline UINT MsiGetTargetPathW(_In_ MSIHANDLE hInstall, _In_ LPCWSTR szFolder, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Returns the full path to an installed component. If the key path for the component is a registry key then the registry key is returned. +/// +/// \sa [MsiGetComponentPath function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa370112.aspx) +/// +template inline INSTALLSTATE MsiGetComponentPathA(_In_ LPCSTR szProduct, _In_ LPCSTR szComponent, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Returns the full path to an installed component. If the key path for the component is a registry key then the registry key is returned. +/// +/// \sa [MsiGetComponentPath function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa370112.aspx) +/// +template inline INSTALLSTATE MsiGetComponentPathW(_In_ LPCWSTR szProduct, _In_ LPCWSTR szComponent, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// @} + +#pragma once + + template inline UINT MsiGetPropertyA(_In_ MSIHANDLE hInstall, _In_ LPCSTR szName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) { @@ -79,11 +141,6 @@ inline UINT MsiGetPropertyA(_In_ MSIHANDLE hInstall, _In_ LPCSTR szName, _Out_ s } -/// -/// Gets the value for an installer property and stores it in a std::wstring string. -/// -/// \sa [MsiGetProperty function](https://msdn.microsoft.com/en-us/library/aa370134.aspx) -/// template inline UINT MsiGetPropertyW(_In_ MSIHANDLE hInstall, _In_ LPCWSTR szName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) { @@ -112,11 +169,6 @@ inline UINT MsiGetPropertyW(_In_ MSIHANDLE hInstall, _In_ LPCWSTR szName, _Out_ } -/// -/// Returns the string value of a record field and stores it in a std::string string. -/// -/// \sa [MsiRecordGetString function](https://msdn.microsoft.com/en-us/library/aa370368.aspx) -/// template inline UINT MsiRecordGetStringA(_In_ MSIHANDLE hRecord, _In_ unsigned int iField, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) { @@ -145,11 +197,6 @@ inline UINT MsiRecordGetStringA(_In_ MSIHANDLE hRecord, _In_ unsigned int iField } -/// -/// Returns the string value of a record field and stores it in a std::wstring string. -/// -/// \sa [MsiRecordGetString function](https://msdn.microsoft.com/en-us/library/aa370368.aspx) -/// template inline UINT MsiRecordGetStringW(_In_ MSIHANDLE hRecord, _In_ unsigned int iField, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) { @@ -178,11 +225,6 @@ inline UINT MsiRecordGetStringW(_In_ MSIHANDLE hRecord, _In_ unsigned int iField } -/// -/// Formats record field data and properties using a format string and stores it in a std::string string. -/// -/// \sa [MsiFormatRecord function](https://msdn.microsoft.com/en-us/library/aa370109.aspx) -/// template inline UINT MsiFormatRecordA(MSIHANDLE hInstall, MSIHANDLE hRecord, std::basic_string<_Elem, _Traits, _Ax> &sValue) { @@ -211,11 +253,6 @@ inline UINT MsiFormatRecordA(MSIHANDLE hInstall, MSIHANDLE hRecord, std::basic_s } -/// -/// Formats record field data and properties using a format string and stores it in a std::wstring string. -/// -/// \sa [MsiFormatRecord function](https://msdn.microsoft.com/en-us/library/aa370109.aspx) -/// template inline UINT MsiFormatRecordW(MSIHANDLE hInstall, MSIHANDLE hRecord, std::basic_string<_Elem, _Traits, _Ax> &sValue) { @@ -244,11 +281,6 @@ inline UINT MsiFormatRecordW(MSIHANDLE hInstall, MSIHANDLE hRecord, std::basic_s } -/// -/// Reads bytes from a record stream field into a std::vector buffer. -/// -/// \sa [MsiRecordReadStream function](https://msdn.microsoft.com/en-us/library/aa370370.aspx) -/// template inline UINT MsiRecordReadStream(_In_ MSIHANDLE hRecord, _In_ unsigned int iField, _Out_ std::vector<_Ty, _Ax> &binData) { @@ -269,11 +301,6 @@ inline UINT MsiRecordReadStream(_In_ MSIHANDLE hRecord, _In_ unsigned int iField } -/// -/// Returns the full target path for a folder in the Directory table and stores it in a std::string string. -/// -/// \sa [MsiGetTargetPath function](https://msdn.microsoft.com/en-us/library/aa370303.aspx) -/// template inline UINT MsiGetTargetPathA(_In_ MSIHANDLE hInstall, _In_ LPCSTR szFolder, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) { @@ -302,11 +329,6 @@ inline UINT MsiGetTargetPathA(_In_ MSIHANDLE hInstall, _In_ LPCSTR szFolder, _Ou } -/// -/// Returns the full target path for a folder in the Directory table and stores it in a std::wstring string. -/// -/// \sa [MsiGetTargetPath function](https://msdn.microsoft.com/en-us/library/aa370303.aspx) -/// template inline UINT MsiGetTargetPathW(_In_ MSIHANDLE hInstall, _In_ LPCWSTR szFolder, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) { @@ -335,11 +357,6 @@ inline UINT MsiGetTargetPathW(_In_ MSIHANDLE hInstall, _In_ LPCWSTR szFolder, _O } -/// -/// Returns the full path to an installed component. If the key path for the component is a registry key then the registry key is returned. -/// -/// \sa [MsiGetComponentPath function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa370112.aspx) -/// template inline INSTALLSTATE MsiGetComponentPathA(_In_ LPCSTR szProduct, _In_ LPCSTR szComponent, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) { @@ -366,11 +383,6 @@ inline INSTALLSTATE MsiGetComponentPathA(_In_ LPCSTR szProduct, _In_ LPCSTR szCo } -/// -/// Returns the full path to an installed component. If the key path for the component is a registry key then the registry key is returned. -/// -/// \sa [MsiGetComponentPath function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa370112.aspx) -/// template inline INSTALLSTATE MsiGetComponentPathW(_In_ LPCWSTR szProduct, _In_ LPCWSTR szComponent, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) { @@ -395,5 +407,3 @@ inline INSTALLSTATE MsiGetComponentPathW(_In_ LPCWSTR szProduct, _In_ LPCWSTR sz return state; } } - -/// @} diff --git a/include/WinStd/Sec.h b/include/WinStd/Sec.h index 6f1b9c70..08244337 100644 --- a/include/WinStd/Sec.h +++ b/include/WinStd/Sec.h @@ -24,23 +24,48 @@ #include -template BOOLEAN GetUserNameExA(_In_ EXTENDED_NAME_FORMAT NameFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sName); -template BOOLEAN GetUserNameExW(_In_ EXTENDED_NAME_FORMAT NameFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sName); namespace winstd { + /// + /// \defgroup WinStdSecurityAPI Security API + /// Integrates WinStd classes with Microsoft Security API + /// + /// @{ + + /// + /// PCredHandle wrapper class + /// class WINSTD_API sec_credentials; + + /// + /// PCtxtHandle wrapper class + /// class WINSTD_API sec_context; + + /// + /// SecBufferDesc wrapper class + /// class WINSTD_API sec_buffer_desc; + + /// @} + + /// + /// \defgroup WinStdExceptions Exceptions + /// Additional exceptions + /// + /// @{ + + /// + /// Security runtime error + /// + /// \note Must be defined as derived class from num_runtime_error<> to allow correct type info for dynamic typecasting and prevent folding with other derivates of num_runtime_error<>. + /// class WINSTD_API sec_runtime_error; + + /// @} } -#pragma once - - -/// -/// \defgroup WinStdSecurityAPI Security API -/// Integrates WinStd classes with Microsoft Security API -/// +/// \addtogroup WinStdSecurityAPI /// @{ /// @@ -48,76 +73,22 @@ namespace winstd /// /// \sa [GetUserNameEx function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx) /// -template -BOOLEAN GetUserNameExA(_In_ EXTENDED_NAME_FORMAT NameFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sName) -{ - assert(0); // TODO: Test this code. - - _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; - ULONG ulSize = _countof(szStackBuffer); - - // Try with stack buffer first. - if (::GetUserNameExA(NameFormat, szStackBuffer, &ulSize)) { - // Copy from stack. - sName.assign(szStackBuffer, ulSize); - return TRUE; - } else { - if (::GetLastError() == ERROR_MORE_DATA) { - // Allocate buffer on heap and retry. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[ulSize]); - if (::GetUserNameExA(NameFormat, szBuffer.get(), &ulSize)) { - sName.assign(szBuffer.get(), ulSize); - return TRUE; - } - } - } - - sName.clear(); - return FALSE; -} - +template BOOLEAN GetUserNameExA(_In_ EXTENDED_NAME_FORMAT NameFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sName); /// /// Retrieves the name of the user or other security principal associated with the calling thread and stores it in a std::wstring string. /// /// \sa [GetUserNameEx function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx) /// -template -BOOLEAN GetUserNameExW(_In_ EXTENDED_NAME_FORMAT NameFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sName) -{ - assert(0); // TODO: Test this code. - - _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; - ULONG ulSize = _countof(szStackBuffer); - - // Try with stack buffer first. - if (::GetUserNameExW(NameFormat, szStackBuffer, &ulSize)) { - // Copy from stack. - sName.assign(szStackBuffer, ulSize); - return TRUE; - } else { - if (::GetLastError() == ERROR_MORE_DATA) { - // Allocate buffer on heap and retry. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[ulSize]); - if (::GetUserNameExW(NameFormat, szBuffer.get(), &ulSize)) { - sName.assign(szBuffer.get(), ulSize); - return TRUE; - } - } - } - - sName.clear(); - return FALSE; -} +template BOOLEAN GetUserNameExW(_In_ EXTENDED_NAME_FORMAT NameFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sName); /// @} +#pragma once + namespace winstd { - /// \addtogroup WinStdSecurityAPI - /// @{ - class WINSTD_API sec_credentials : public handle { public: @@ -345,20 +316,7 @@ namespace winstd virtual ~sec_buffer_desc(); }; - /// @} - - /// - /// \defgroup WinStdExceptions Exceptions - /// Additional exceptions - /// - /// @{ - - /// - /// COM runtime error - /// - /// \note Must be defined as derived class from num_runtime_error<> to allow correct type info for dynamic typecasting and prevent folding with other derivates of num_runtime_error<>. - /// class WINSTD_API sec_runtime_error : public num_runtime_error { public: @@ -393,6 +351,62 @@ namespace winstd { } }; - - /// @} +} + + +template +BOOLEAN GetUserNameExA(_In_ EXTENDED_NAME_FORMAT NameFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sName) +{ + assert(0); // TODO: Test this code. + + _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; + ULONG ulSize = _countof(szStackBuffer); + + // Try with stack buffer first. + if (::GetUserNameExA(NameFormat, szStackBuffer, &ulSize)) { + // Copy from stack. + sName.assign(szStackBuffer, ulSize); + return TRUE; + } else { + if (::GetLastError() == ERROR_MORE_DATA) { + // Allocate buffer on heap and retry. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[ulSize]); + if (::GetUserNameExA(NameFormat, szBuffer.get(), &ulSize)) { + sName.assign(szBuffer.get(), ulSize); + return TRUE; + } + } + } + + sName.clear(); + return FALSE; +} + + +template +BOOLEAN GetUserNameExW(_In_ EXTENDED_NAME_FORMAT NameFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sName) +{ + assert(0); // TODO: Test this code. + + _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; + ULONG ulSize = _countof(szStackBuffer); + + // Try with stack buffer first. + if (::GetUserNameExW(NameFormat, szStackBuffer, &ulSize)) { + // Copy from stack. + sName.assign(szStackBuffer, ulSize); + return TRUE; + } else { + if (::GetLastError() == ERROR_MORE_DATA) { + // Allocate buffer on heap and retry. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[ulSize]); + if (::GetUserNameExW(NameFormat, szBuffer.get(), &ulSize)) { + sName.assign(szBuffer.get(), ulSize); + return TRUE; + } + } + } + + sName.clear(); + return FALSE; } diff --git a/include/WinStd/Shell.h b/include/WinStd/Shell.h index 9062f12c..1d09c559 100644 --- a/include/WinStd/Shell.h +++ b/include/WinStd/Shell.h @@ -24,12 +24,6 @@ #include -template inline BOOL PathCanonicalizeA(__out std::basic_string<_Elem, _Traits, _Ax> &sValue, __in LPCSTR pszPath); -template inline BOOL PathCanonicalizeW(__out std::basic_string<_Elem, _Traits, _Ax> &sValue, __in LPCWSTR pszPath); - -#pragma once - - /// /// \defgroup WinStdShellWAPI Shell API /// Integrates WinStd classes with Microsoft Shell API @@ -41,6 +35,20 @@ template inline BOOL PathCanonicalizeW(__ /// /// \sa [PathCanonicalize function](https://msdn.microsoft.com/en-us/library/windows/desktop/bb773569.aspx) /// +template inline BOOL PathCanonicalizeA(__out std::basic_string<_Elem, _Traits, _Ax> &sValue, __in LPCSTR pszPath); + +/// +/// Simplifies a path by removing navigation elements such as "." and ".." to produce a direct, well-formed path, and stores it in a std::wstring string. +/// +/// \sa [PathCanonicalize function](https://msdn.microsoft.com/en-us/library/windows/desktop/bb773569.aspx) +/// +template inline BOOL PathCanonicalizeW(__out std::basic_string<_Elem, _Traits, _Ax> &sValue, __in LPCWSTR pszPath); + +/// @} + +#pragma once + + template inline BOOL PathCanonicalizeA(__out std::basic_string<_Elem, _Traits, _Ax> &sValue, __in LPCSTR pszPath) { @@ -54,11 +62,6 @@ inline BOOL PathCanonicalizeA(__out std::basic_string<_Elem, _Traits, _Ax> &sVal } -/// -/// Simplifies a path by removing navigation elements such as "." and ".." to produce a direct, well-formed path, and stores it in a std::wstring string. -/// -/// \sa [PathCanonicalize function](https://msdn.microsoft.com/en-us/library/windows/desktop/bb773569.aspx) -/// template inline BOOL PathCanonicalizeW(__out std::basic_string<_Elem, _Traits, _Ax> &sValue, __in LPCWSTR pszPath) { @@ -69,5 +72,3 @@ inline BOOL PathCanonicalizeW(__out std::basic_string<_Elem, _Traits, _Ax> &sVal sValue.assign(szBuffer, bResult ? MAX_PATH : 0); return bResult; } - -/// @} diff --git a/include/WinStd/WLAN.h b/include/WinStd/WLAN.h index 366dded6..8fa18f12 100644 --- a/include/WinStd/WLAN.h +++ b/include/WinStd/WLAN.h @@ -28,11 +28,6 @@ // without a WLAN interface. extern DWORD (WINAPI *pfnWlanReasonCodeToString)(__in DWORD dwReasonCode, __in DWORD dwBufferSize, __in_ecount(dwBufferSize) PWCHAR pStringBuffer, __reserved PVOID pReserved); -template inline DWORD WlanReasonCodeToString(_In_ DWORD dwReasonCode, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue, __reserved PVOID pReserved); - -#pragma once - - /// /// \defgroup WinStdWLANAPI WLAN API /// Integrates WinStd classes with Microsoft WLAN API @@ -48,6 +43,13 @@ template inline DWORD WlanReasonCodeToStr /// Since Wlanapi.dll is not always present, the \c pfnWlanReasonCodeToString pointer to \c WlanReasonCodeToString /// function must be loaded dynamically. /// +template inline DWORD WlanReasonCodeToString(_In_ DWORD dwReasonCode, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue, __reserved PVOID pReserved); + +/// @} + +#pragma once + + template inline DWORD WlanReasonCodeToString(_In_ DWORD dwReasonCode, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue, __reserved PVOID pReserved) { @@ -77,5 +79,3 @@ inline DWORD WlanReasonCodeToString(_In_ DWORD dwReasonCode, _Out_ std::basic_st } } } - -/// @} diff --git a/include/WinStd/Win.h b/include/WinStd/Win.h index 80de3edb..dede6b74 100644 --- a/include/WinStd/Win.h +++ b/include/WinStd/Win.h @@ -25,15 +25,126 @@ #include #include +namespace winstd +{ + /// + /// \defgroup WinStdWinAPI Windows API + /// Integrates WinStd classes with Microsoft Windows API + /// + /// @{ + + /// + /// Windows HANDLE wrapper class + /// + class WINSTD_API win_handle; + + /// + /// Module handle wrapper + /// + class WINSTD_API library; + + /// + /// Process handle wrapper + /// + class WINSTD_API process; + + /// + /// Heap handle wrapper + /// + class WINSTD_API heap; + + /// + /// Activates given activation context in constructor and deactivates it in destructor + /// + class WINSTD_API actctx_activator; + + /// + /// Lets the calling thread impersonate the security context of a logged-on user + /// + class WINSTD_API user_impersonator; + + /// + /// Memory in virtual address space of a process handle wrapper + /// + class WINSTD_API vmemory; + + /// @} +} + + +/// \addtogroup WinStdWinAPI +/// @{ + +/// +/// Retrieves the fully qualified path for the file that contains the specified module and stores it in a std::string string. +/// +/// \sa [GetModuleFileName function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms683197.aspx) +/// template inline DWORD GetModuleFileNameA(_In_opt_ HMODULE hModule, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Retrieves the fully qualified path for the file that contains the specified module and stores it in a std::wstring string. +/// +/// \sa [GetModuleFileName function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms683197.aspx) +/// template inline DWORD GetModuleFileNameW(_In_opt_ HMODULE hModule, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Copies the text of the specified window's title bar (if it has one) into a std::string string. +/// +/// \sa [GetWindowText function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms633520.aspx) +/// template inline int GetWindowTextA(_In_ HWND hWnd, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Copies the text of the specified window's title bar (if it has one) into a std::wstring string. +/// +/// \sa [GetWindowText function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms633520.aspx) +/// template inline int GetWindowTextW(_In_ HWND hWnd, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Retrieves version information for the specified file and stores it in a std::vector buffer. +/// +/// \sa [GetFileVersionInfo function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms647003.aspx) +/// template inline BOOL GetFileVersionInfoA(_In_ LPCSTR lptstrFilename, __reserved DWORD dwHandle, _Out_ std::vector<_Ty, _Ax> &aValue); + +/// +/// Retrieves version information for the specified file and stores it in a std::vector buffer. +/// +/// \sa [GetFileVersionInfo function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms647003.aspx) +/// template inline BOOL GetFileVersionInfoW(_In_ LPCWSTR lptstrFilename, __reserved DWORD dwHandle, _Out_ std::vector<_Ty, _Ax> &aValue); + +/// +/// Expands environment-variable strings, replaces them with the values defined for the current user, and stores it in a std::string string. +/// +/// \sa [ExpandEnvironmentStrings function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724265.aspx) +/// template inline DWORD ExpandEnvironmentStringsW(_In_ LPCSTR lpSrc, std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Expands environment-variable strings, replaces them with the values defined for the current user, and stores it in a std::wstring string. +/// +/// \sa [ExpandEnvironmentStrings function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724265.aspx) +/// template inline DWORD ExpandEnvironmentStringsW(_In_ LPCWSTR lpSrc, std::basic_string<_Elem, _Traits, _Ax> &sValue); + +/// +/// Formats GUID and stores it in a std::string string. +/// +/// \param[in ] lpGuid Pointer to GUID +/// \param[out] str String to store the result to +/// template inline VOID GuidToStringA(_In_ LPCGUID lpGuid, _Out_ std::basic_string<_Elem, _Traits, _Ax> &str); + +/// +/// Formats GUID and stores it in a std::wstring string. +/// +/// \param[in ] lpGuid Pointer to GUID +/// \param[out] str String to store the result to +/// template inline VOID GuidToStringW(_In_ LPCGUID lpGuid, _Out_ std::basic_string<_Elem, _Traits, _Ax> &str); #ifdef _UNICODE #define GuidToString GuidToStringW @@ -63,318 +174,6 @@ BOOL WINSTD_API StringToGuidW(_In_z_ LPCWSTR lpszGuid, _Out_ LPGUID lpGuid); #define StringToGuid StringToGuidA #endif -template inline LSTATUS RegQueryStringValue(_In_ HKEY hReg, _In_z_ LPCSTR pszName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline LSTATUS RegQueryStringValue(_In_ HKEY hReg, _In_z_ LPCWSTR pszName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); -template inline LSTATUS RegQueryValueExA(_In_ HKEY hKey, _In_opt_ LPCSTR lpValueName, __reserved LPDWORD lpReserved, _Out_opt_ LPDWORD lpType, _Out_ std::vector<_Ty, _Ax> &aData); -template inline LSTATUS RegQueryValueExW(_In_ HKEY hKey, _In_opt_ LPCWSTR lpValueName, __reserved LPDWORD lpReserved, _Out_opt_ LPDWORD lpType, _Out_ std::vector<_Ty, _Ax> &aData); -#if _WIN32_WINNT >= _WIN32_WINNT_VISTA -template inline LSTATUS RegLoadMUIStringA(_In_ HKEY hKey, _In_opt_ LPCSTR pszValue, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sOut, _In_ DWORD Flags, _In_opt_ LPCSTR pszDirectory); -template inline LSTATUS RegLoadMUIStringW(_In_ HKEY hKey, _In_opt_ LPCWSTR pszValue, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sOut, _In_ DWORD Flags, _In_opt_ LPCWSTR pszDirectory); -#endif -template inline int WideCharToMultiByte(_In_ UINT CodePage, _In_ DWORD dwFlags, _In_z_count_(cchWideChar) LPCWSTR lpWideCharStr, _In_ int cchWideChar, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sMultiByteStr, _In_opt_ LPCSTR lpDefaultChar, _Out_opt_ LPBOOL lpUsedDefaultChar); -template inline int MultiByteToWideChar(_In_ UINT CodePage, _In_ DWORD dwFlags, _In_z_count_(cbMultiByte) LPCSTR lpMultiByteStr, _In_ int cbMultiByte, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sWideCharStr); -template inline int WINAPI LoadString(_In_opt_ HINSTANCE hInstance, _In_ UINT uID, _Out_ std::basic_string &sBuffer); -template inline int WINAPI LoadString(_In_opt_ HINSTANCE hInstance, _In_ UINT uID, _Out_ std::basic_string &sBuffer); -inline VOID OutputDebugStrV(_In_ LPCSTR lpOutputString, _In_ va_list arg); -inline VOID OutputDebugStrV(_In_ LPCWSTR lpOutputString, _In_ va_list arg); -inline VOID OutputDebugStr(_In_ LPCSTR lpOutputString, ...); -inline VOID OutputDebugStr(_In_ LPCWSTR lpOutputString, ...); -template inline int GetDateFormatA(_In_ LCID Locale, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpDate, _In_opt_ LPCSTR lpFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sDate); -template inline int GetDateFormatW(_In_ LCID Locale, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpDate, _In_opt_ LPCWSTR lpFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sDate); -template inline BOOL LookupAccountSidA(_In_opt_ LPCSTR lpSystemName, _In_ PSID lpSid, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sName, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sReferencedDomainName, _Out_ PSID_NAME_USE peUse); -template inline BOOL LookupAccountSidW(_In_opt_ LPCWSTR lpSystemName, _In_ PSID lpSid, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sName, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sReferencedDomainName, _Out_ PSID_NAME_USE peUse); - - -namespace winstd -{ - class WINSTD_API win_handle; - class WINSTD_API library; - class WINSTD_API process; - class WINSTD_API heap; - class WINSTD_API actctx_activator; - class WINSTD_API user_impersonator; - class WINSTD_API vmemory; -} - -#pragma once - - -/// -/// \defgroup WinStdWinAPI Windows API -/// Integrates WinStd classes with Microsoft Windows API -/// -/// @{ - -/// -/// Retrieves the fully qualified path for the file that contains the specified module and stores it in a std::string string. -/// -/// \sa [GetModuleFileName function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms683197.aspx) -/// -template -inline DWORD GetModuleFileNameA(_In_opt_ HMODULE hModule, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) -{ - assert(0); // TODO: Test this code. - - _Elem szBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; - - // Try with stack buffer first. - DWORD dwResult = ::GetModuleFileNameA(hModule, szBuffer, _countof(szBuffer)); - if (dwResult < _countof(szBuffer)) { - // Copy from stack. - sValue.assign(szBuffer, dwResult); - return dwResult; - } else { - for (DWORD dwCapacity = 2*WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem);; dwCapacity *= 2) { - // Allocate on heap and retry. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwCapacity]); - dwResult = ::GetModuleFileNameA(hModule, szBuffer.get(), dwCapacity); - if (dwResult < dwCapacity) { - sValue.assign(szBuffer.get(), dwResult); - return dwResult; - } - } - } -} - - -/// -/// Retrieves the fully qualified path for the file that contains the specified module and stores it in a std::wstring string. -/// -/// \sa [GetModuleFileName function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms683197.aspx) -/// -template -inline DWORD GetModuleFileNameW(_In_opt_ HMODULE hModule, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) -{ - _Elem szBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; - - // Try with stack buffer first. - DWORD dwResult = ::GetModuleFileNameW(hModule, szBuffer, _countof(szBuffer)); - if (dwResult < _countof(szBuffer)) { - // Copy from stack. - sValue.assign(szBuffer, dwResult); - return dwResult; - } else { - for (DWORD dwCapacity = 2*WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem);; dwCapacity *= 2) { - // Allocate on heap and retry. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwCapacity]); - dwResult = ::GetModuleFileNameW(hModule, szBuffer.get(), dwCapacity); - if (dwResult < dwCapacity) { - sValue.assign(szBuffer.get(), dwResult); - return dwResult; - } - } - } -} - - -/// -/// Copies the text of the specified window's title bar (if it has one) into a std::string string. -/// -/// \sa [GetWindowText function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms633520.aspx) -/// -template -inline int GetWindowTextA(_In_ HWND hWnd, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) -{ - assert(0); // TODO: Test this code. - - int iResult; - - // Query the final string length first. - iResult = ::GetWindowTextLengthA(hWnd); - if (iResult > 0) { - if (++iResult < WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)) { - // Read string data to stack. - _Elem szBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; - iResult = ::GetWindowTextA(hWnd, szBuffer, _countof(szBuffer)); - sValue.assign(szBuffer, iResult); - } else { - // Allocate buffer on heap and read the string data into it. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[++iResult]); - iResult = ::GetWindowTextA(hWnd, szBuffer.get(), iResult); - sValue.assign(szBuffer.get(), iResult); - } - return iResult; - } - - sValue.clear(); - return 0; -} - - -/// -/// Copies the text of the specified window's title bar (if it has one) into a std::wstring string. -/// -/// \sa [GetWindowText function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms633520.aspx) -/// -template -inline int GetWindowTextW(_In_ HWND hWnd, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) -{ - assert(0); // TODO: Test this code. - - int iResult; - - // Query the final string length first. - iResult = ::GetWindowTextLengthW(hWnd); - if (iResult > 0) { - if (++iResult < WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)) { - // Read string data to stack. - _Elem szBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; - iResult = ::GetWindowTextW(hWnd, szBuffer, _countof(szBuffer)); - sValue.assign(szBuffer, iResult); - } else { - // Allocate buffer on heap and read the string data into it. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[++iResult]); - iResult = ::GetWindowTextW(hWnd, szBuffer.get(), iResult); - sValue.assign(szBuffer.get(), iResult); - } - return iResult; - } - - sValue.clear(); - return 0; -} - - -/// -/// Retrieves version information for the specified file and stores it in a std::vector buffer. -/// -/// \sa [GetFileVersionInfo function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms647003.aspx) -/// -template -inline BOOL GetFileVersionInfoA(_In_ LPCSTR lptstrFilename, __reserved DWORD dwHandle, _Out_ std::vector<_Ty, _Ax> &aValue) -{ - assert(0); // TODO: Test this code. - - // Get version info size. - DWORD dwVerInfoSize = ::GetFileVersionInfoSizeA(lptstrFilename, &dwHandle); - if (dwVerInfoSize != 0) { - // Read version info. - aValue.resize((dwVerInfoSize + sizeof(_Ty) - 1) / sizeof(_Ty)); - return ::GetFileVersionInfoA(lptstrFilename, dwHandle, dwVerInfoSize, aValue.data()); - } else - return FALSE; -} - - -/// -/// Retrieves version information for the specified file and stores it in a std::vector buffer. -/// -/// \sa [GetFileVersionInfo function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms647003.aspx) -/// -template -inline BOOL GetFileVersionInfoW(_In_ LPCWSTR lptstrFilename, __reserved DWORD dwHandle, _Out_ std::vector<_Ty, _Ax> &aValue) -{ - assert(0); // TODO: Test this code. - - // Get version info size. - DWORD dwVerInfoSize = ::GetFileVersionInfoSizeW(lptstrFilename, &dwHandle); - if (dwVerInfoSize != 0) { - // Read version info. - aValue.resize((dwVerInfoSize + sizeof(_Ty) - 1) / sizeof(_Ty)); - return ::GetFileVersionInfoW(lptstrFilename, dwHandle, dwVerInfoSize, aValue.data()); - } else - return FALSE; -} - - -/// -/// Expands environment-variable strings, replaces them with the values defined for the current user, and stores it in a std::string string. -/// -/// \sa [ExpandEnvironmentStrings function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724265.aspx) -/// -template -inline DWORD ExpandEnvironmentStringsW(_In_ LPCSTR lpSrc, std::basic_string<_Elem, _Traits, _Ax> &sValue) -{ - assert(0); // TODO: Test this code. - - for (DWORD dwSizeOut = (DWORD)strlen(lpSrc) + 0x100;;) { - DWORD dwSizeIn = dwSizeOut; - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSizeIn + 2]); // Note: ANSI version requires one extra char. - dwSizeOut = ::ExpandEnvironmentStringsA(lpSrc, szBuffer.get(), dwSizeIn); - if (dwSizeOut == 0) { - // Error. - break; - } else if (dwSizeOut <= dwSizeIn) { - // The buffer was sufficient. - sValue.assign(szBuffer.get(), dwSizeOut); - return dwSizeOut; - } - } - - sValue.clear(); - return 0; -} - - -/// -/// Expands environment-variable strings, replaces them with the values defined for the current user, and stores it in a std::wstring string. -/// -/// \sa [ExpandEnvironmentStrings function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724265.aspx) -/// -template -inline DWORD ExpandEnvironmentStringsW(_In_ LPCWSTR lpSrc, std::basic_string<_Elem, _Traits, _Ax> &sValue) -{ - assert(0); // TODO: Test this code. - - for (DWORD dwSizeOut = (DWORD)wcslen(lpSrc) + 0x100;;) { - DWORD dwSizeIn = dwSizeOut; - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSizeIn + 1]); - dwSizeOut = ::ExpandEnvironmentStringsW(lpSrc, szBuffer.get(), dwSizeIn); - if (dwSizeOut == 0) { - // Error. - break; - } else if (dwSizeOut <= dwSizeIn) { - // The buffer was sufficient. - sValue.assign(szBuffer.get(), dwSizeOut); - return dwSizeOut; - } - } - - sValue.clear(); - return 0; -} - - -/// -/// Formats GUID and stores it in a std::string string. -/// -/// \param[in ] lpGuid Pointer to GUID -/// \param[out] str String to store the result to -/// -template -inline VOID GuidToStringA(_In_ LPCGUID lpGuid, _Out_ std::basic_string<_Elem, _Traits, _Ax> &str) -{ - assert(0); // TODO: Test this code. - - sprintf(str, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", - lpGuid->Data1, - lpGuid->Data2, - lpGuid->Data3, - lpGuid->Data4[0], lpGuid->Data4[1], - lpGuid->Data4[2], lpGuid->Data4[3], lpGuid->Data4[4], lpGuid->Data4[5], lpGuid->Data4[6], lpGuid->Data4[7]); -} - - -/// -/// Formats GUID and stores it in a std::wstring string. -/// -/// \param[in ] lpGuid Pointer to GUID -/// \param[out] str String to store the result to -/// -template -inline VOID GuidToStringW(_In_ LPCGUID lpGuid, _Out_ std::basic_string<_Elem, _Traits, _Ax> &str) -{ - assert(0); // TODO: Test this code. - - sprintf(str, L"{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", - lpGuid->Data1, - lpGuid->Data2, - lpGuid->Data3, - lpGuid->Data4[0], lpGuid->Data4[1], - lpGuid->Data4[2], lpGuid->Data4[3], lpGuid->Data4[4], lpGuid->Data4[5], lpGuid->Data4[6], lpGuid->Data4[7]); -} - - /// /// Queries for a string value in the registry and stores it in a std::string string. /// @@ -393,54 +192,7 @@ inline VOID GuidToStringW(_In_ LPCGUID lpGuid, _Out_ std::basic_string<_Elem, _T /// \sa [RegQueryValueEx function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724911.aspx) /// \sa [ExpandEnvironmentStrings function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724265.aspx) /// -template -inline LSTATUS RegQueryStringValue(_In_ HKEY hReg, _In_z_ LPCSTR pszName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) -{ - assert(0); // TODO: Test this code. - - LSTATUS lResult; - BYTE aStackBuffer[WINSTD_STACK_BUFFER_BYTES]; - DWORD dwSize = sizeof(aStackBuffer), dwType; - - // Try with stack buffer first. - lResult = ::RegQueryValueExA(hReg, pszName, NULL, &dwType, aStackBuffer, &dwSize); - if (lResult == ERROR_SUCCESS) { - if (dwType == REG_SZ || dwType == REG_MULTI_SZ) { - // The value is REG_SZ or REG_MULTI_SZ. - sValue.assign((_Elem*)aStackBuffer, dwSize / sizeof(_Elem)); - } else if (dwType == REG_EXPAND_SZ) { - // The value is REG_EXPAND_SZ. Expand it from stack buffer. - if (::ExpandEnvironmentStringsW((const _Elem*)aStackBuffer, sValue) == 0) - lResult = ::GetLastError(); - } else { - // The value is not a string type. - lResult = ERROR_INVALID_DATA; - } - } else if (lResult == ERROR_MORE_DATA) { - if (dwType == REG_SZ || dwType == REG_MULTI_SZ) { - // The value is REG_SZ or REG_MULTI_SZ. Read it now. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize / sizeof(_Elem)]); - if ((lResult = ::RegQueryValueExA(hReg, pszName, NULL, NULL, (LPBYTE)szBuffer.get(), &dwSize)) == ERROR_SUCCESS) - sValue.assign(szBuffer.get(), dwSize / sizeof(_Elem)); - else - sValue.clear(); - } else if (dwType == REG_EXPAND_SZ) { - // The value is REG_EXPAND_SZ. Read it and expand environment variables. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize / sizeof(_Elem)]); - if ((lResult = ::RegQueryValueExA(hReg, pszName, NULL, NULL, (LPBYTE)szBuffer.get(), &dwSize)) == ERROR_SUCCESS) { - if (::ExpandEnvironmentStringsW(szBuffer.get(), sValue) == 0) - lResult = ::GetLastError(); - } else - sValue.clear(); - } else { - // The value is not a string type. - lResult = ERROR_INVALID_DATA; - } - } - - return lResult; -} - +template inline LSTATUS RegQueryStringValue(_In_ HKEY hReg, _In_z_ LPCSTR pszName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); /// /// Queries for a string value in the registry and stores it in a std::wstring string. @@ -460,116 +212,21 @@ inline LSTATUS RegQueryStringValue(_In_ HKEY hReg, _In_z_ LPCSTR pszName, _Out_ /// \sa [RegQueryValueEx function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724911.aspx) /// \sa [ExpandEnvironmentStrings function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724265.aspx) /// -template -inline LSTATUS RegQueryStringValue(_In_ HKEY hReg, _In_z_ LPCWSTR pszName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) -{ - assert(0); // TODO: Test this code. - - LSTATUS lResult; - BYTE aStackBuffer[WINSTD_STACK_BUFFER_BYTES]; - DWORD dwSize = sizeof(aStackBuffer), dwType; - - // Try with stack buffer first. - lResult = ::RegQueryValueExW(hReg, pszName, NULL, &dwType, aStackBuffer, &dwSize); - if (lResult == ERROR_SUCCESS) { - if (dwType == REG_SZ || dwType == REG_MULTI_SZ) { - // The value is REG_SZ or REG_MULTI_SZ. - sValue.assign((_Elem*)aStackBuffer, dwSize / sizeof(_Elem)); - } else if (dwType == REG_EXPAND_SZ) { - // The value is REG_EXPAND_SZ. Expand it from stack buffer. - if (::ExpandEnvironmentStringsW((const _Elem*)aStackBuffer, sValue) == 0) - lResult = ::GetLastError(); - } else { - // The value is not a string type. - lResult = ERROR_INVALID_DATA; - } - } else if (lResult == ERROR_MORE_DATA) { - if (dwType == REG_SZ || dwType == REG_MULTI_SZ) { - // The value is REG_SZ or REG_MULTI_SZ. Read it now. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize / sizeof(_Elem)]); - if ((lResult = ::RegQueryValueExW(hReg, pszName, NULL, NULL, (LPBYTE)szBuffer.get(), &dwSize)) == ERROR_SUCCESS) - sValue.assign(szBuffer.get(), dwSize / sizeof(_Elem)); - else - sValue.clear(); - } else if (dwType == REG_EXPAND_SZ) { - // The value is REG_EXPAND_SZ. Read it and expand environment variables. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize / sizeof(_Elem)]); - if ((lResult = ::RegQueryValueExW(hReg, pszName, NULL, NULL, (LPBYTE)szBuffer.get(), &dwSize)) == ERROR_SUCCESS) { - if (::ExpandEnvironmentStringsW(szBuffer.get(), sValue) == 0) - lResult = ::GetLastError(); - } else - sValue.clear(); - } else { - // The value is not a string type. - lResult = ERROR_INVALID_DATA; - } - } - - return lResult; -} - +template inline LSTATUS RegQueryStringValue(_In_ HKEY hReg, _In_z_ LPCWSTR pszName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue); /// /// Retrieves the type and data for the specified value name associated with an open registry key and stores the data in a std::vector buffer. /// /// \sa [RegQueryValueEx function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724911.aspx) /// -template -inline LSTATUS RegQueryValueExA(_In_ HKEY hKey, _In_opt_ LPCSTR lpValueName, __reserved LPDWORD lpReserved, _Out_opt_ LPDWORD lpType, _Out_ std::vector<_Ty, _Ax> &aData) -{ - assert(0); // TODO: Test this code. - - LSTATUS lResult; - BYTE aStackBuffer[WINSTD_STACK_BUFFER_BYTES]; - DWORD dwSize = sizeof(aStackBuffer); - - // Try with stack buffer first. - lResult = RegQueryValueExA(hKey, lpValueName, lpReserved, NULL, aStackBuffer, &dwSize); - if (lResult == ERROR_SUCCESS) { - // Copy from stack buffer. - aData.resize((dwSize + sizeof(_Ty) - 1) / sizeof(_Ty)); - memcpy(aData.data(), aStackBuffer, dwSize); - } else if (lResult == ERROR_MORE_DATA) { - // Allocate buffer on heap and retry. - aData.resize((dwSize + sizeof(_Ty) - 1) / sizeof(_Ty)); - if ((lResult = RegQueryValueExA(hKey, lpValueName, lpReserved, lpType, aData.data(), &dwSize)) != ERROR_SUCCESS) - aData.clear(); - } - - return lResult; -} - +template inline LSTATUS RegQueryValueExA(_In_ HKEY hKey, _In_opt_ LPCSTR lpValueName, __reserved LPDWORD lpReserved, _Out_opt_ LPDWORD lpType, _Out_ std::vector<_Ty, _Ax> &aData); /// /// Retrieves the type and data for the specified value name associated with an open registry key and stores the data in a std::vector buffer. /// /// \sa [RegQueryValueEx function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724911.aspx) /// -template -inline LSTATUS RegQueryValueExW(_In_ HKEY hKey, _In_opt_ LPCWSTR lpValueName, __reserved LPDWORD lpReserved, _Out_opt_ LPDWORD lpType, _Out_ std::vector<_Ty, _Ax> &aData) -{ - assert(0); // TODO: Test this code. - - LSTATUS lResult; - BYTE aStackBuffer[WINSTD_STACK_BUFFER_BYTES]; - DWORD dwSize = sizeof(aStackBuffer); - - // Try with stack buffer first. - lResult = RegQueryValueExW(hKey, lpValueName, lpReserved, NULL, aStackBuffer, &dwSize); - if (lResult == ERROR_SUCCESS) { - // Copy from stack buffer. - aData.resize((dwSize + sizeof(_Ty) - 1) / sizeof(_Ty)); - memcpy(aData.data(), aStackBuffer, dwSize); - } else if (lResult == ERROR_MORE_DATA) { - // Allocate buffer on heap and retry. - aData.resize((dwSize + sizeof(_Ty) - 1) / sizeof(_Ty)); - if ((lResult = RegQueryValueExW(hKey, lpValueName, lpReserved, lpType, aData.data(), &dwSize)) != ERROR_SUCCESS) - aData.clear(); - } - - return lResult; -} - +template inline LSTATUS RegQueryValueExW(_In_ HKEY hKey, _In_opt_ LPCWSTR lpValueName, __reserved LPDWORD lpReserved, _Out_opt_ LPDWORD lpType, _Out_ std::vector<_Ty, _Ax> &aData); #if _WIN32_WINNT >= _WIN32_WINNT_VISTA @@ -578,341 +235,108 @@ inline LSTATUS RegQueryValueExW(_In_ HKEY hKey, _In_opt_ LPCWSTR lpValueName, __ /// /// \sa [RegLoadMUIString function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724890.aspx) /// -template -inline LSTATUS RegLoadMUIStringA(_In_ HKEY hKey, _In_opt_ LPCSTR pszValue, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sOut, _In_ DWORD Flags, _In_opt_ LPCSTR pszDirectory) -{ - assert(0); // TODO: Test this code. - - LSTATUS lResult; - _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; - DWORD dwSize; - - Flags &= ~REG_MUI_STRING_TRUNCATE; - - // Try with stack buffer first. - lResult = RegLoadMUIStringA(hKey, pszValue, szStackBuffer, _countof(szStackBuffer), &dwSize, Flags, pszDirectory); - if (lResult == ERROR_SUCCESS) { - // Copy from stack buffer. - sOut.assign(szStackBuffer, dwSize); - } else if (lResult == ERROR_MORE_DATA) { - // Allocate buffer on heap and retry. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize + 1]); - sOut.assign(szBuffer.get(), (lResult = RegLoadMUIStringA(hKey, pszValue, szBuffer.get(), dwSize, &dwSize, Flags, pszDirectory)) == ERROR_SUCCESS ? dwSize : 0); - } - - return lResult; -} - +template inline LSTATUS RegLoadMUIStringA(_In_ HKEY hKey, _In_opt_ LPCSTR pszValue, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sOut, _In_ DWORD Flags, _In_opt_ LPCSTR pszDirectory); /// /// Loads the specified string from the specified key and subkey, and stores it in a std::wstring string. /// /// \sa [RegLoadMUIString function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724890.aspx) /// -template -inline LSTATUS RegLoadMUIStringW(_In_ HKEY hKey, _In_opt_ LPCWSTR pszValue, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sOut, _In_ DWORD Flags, _In_opt_ LPCWSTR pszDirectory) -{ - assert(0); // TODO: Test this code. - - LSTATUS lResult; - _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; - DWORD dwSize; - - Flags &= ~REG_MUI_STRING_TRUNCATE; - - // Try with stack buffer first. - lResult = RegLoadMUIStringW(hKey, pszValue, szStackBuffer, _countof(szStackBuffer), &dwSize, Flags, pszDirectory); - if (lResult == ERROR_SUCCESS) { - // Copy from stack buffer. - sOut.assign(szStackBuffer, dwSize); - } else if (lResult == ERROR_MORE_DATA) { - // Allocate buffer on heap and retry. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize + 1]); - sOut.assign(szBuffer.get(), (lResult = RegLoadMUIStringW(hKey, pszValue, szBuffer.get(), dwSize, &dwSize, Flags, pszDirectory)) == ERROR_SUCCESS ? dwSize : 0); - } - - return lResult; -} +template inline LSTATUS RegLoadMUIStringW(_In_ HKEY hKey, _In_opt_ LPCWSTR pszValue, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sOut, _In_ DWORD Flags, _In_opt_ LPCWSTR pszDirectory); #endif - /// /// Maps a UTF-16 (wide character) string to a std::string. The new character string is not necessarily from a multibyte character set. /// /// \sa [WideCharToMultiByte function](https://msdn.microsoft.com/en-us/library/windows/desktop/dd374130.aspx) /// -template -inline int WideCharToMultiByte(_In_ UINT CodePage, _In_ DWORD dwFlags, _In_z_count_(cchWideChar) LPCWSTR lpWideCharStr, _In_ int cchWideChar, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sMultiByteStr, _In_opt_ LPCSTR lpDefaultChar, _Out_opt_ LPBOOL lpUsedDefaultChar) -{ - _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; - - // Try to convert to stack buffer first. - int cch = ::WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, szStackBuffer, _countof(szStackBuffer), lpDefaultChar, lpUsedDefaultChar); - if (cch) { - // Copy from stack. Be careful not to include zero terminator. - sMultiByteStr.assign(szStackBuffer, cchWideChar != -1 ? strnlen(szStackBuffer, cch) : cch - 1); - } else if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { - // Query the required output size. Allocate buffer. Then convert again. - cch = ::WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, NULL, 0, lpDefaultChar, lpUsedDefaultChar); - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[cch]); - cch = ::WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, szBuffer.get(), cch, lpDefaultChar, lpUsedDefaultChar); - sMultiByteStr.assign(szBuffer.get(), cchWideChar != -1 ? strnlen(szBuffer.get(), cch) : cch - 1); - } - - return cch; -} - +template inline int WideCharToMultiByte(_In_ UINT CodePage, _In_ DWORD dwFlags, _In_z_count_(cchWideChar) LPCWSTR lpWideCharStr, _In_ int cchWideChar, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sMultiByteStr, _In_opt_ LPCSTR lpDefaultChar, _Out_opt_ LPBOOL lpUsedDefaultChar); /// /// Maps a character string to a UTF-16 (wide character) std::wstring. The character string is not necessarily from a multibyte character set. /// /// \sa [MultiByteToWideChar function](https://msdn.microsoft.com/en-us/library/windows/desktop/dd319072.aspx) /// -template -inline int MultiByteToWideChar(_In_ UINT CodePage, _In_ DWORD dwFlags, _In_z_count_(cbMultiByte) LPCSTR lpMultiByteStr, _In_ int cbMultiByte, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sWideCharStr) -{ - _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; - - // Try to convert to stack buffer first. - int cch = ::MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, szStackBuffer, _countof(szStackBuffer)); - if (cch) { - // Copy from stack. - sWideCharStr.assign(szStackBuffer, cch); - } else if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { - // Query the required output size. Allocate buffer. Then convert again. - cch = ::MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, NULL, 0); - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[cch]); - cch = ::MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, szBuffer.get(), cch); - sWideCharStr.assign(szBuffer.get(), cch); - } - - return cch; -} - +template inline int MultiByteToWideChar(_In_ UINT CodePage, _In_ DWORD dwFlags, _In_z_count_(cbMultiByte) LPCSTR lpMultiByteStr, _In_ int cbMultiByte, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sWideCharStr); /// /// Loads a string resource from the executable file associated with a specified module. /// /// \sa [LoadString function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms647486.aspx) /// -template -inline int WINAPI LoadString(_In_opt_ HINSTANCE hInstance, _In_ UINT uID, _Out_ std::basic_string &sBuffer) -{ - // Get read-only pointer to string resource. - LPCSTR pszStr; - int i = LoadStringA(hInstance, uID, (LPSTR)&pszStr, 0); - if (i) { - sBuffer.assign(pszStr, i); - return i; - } else - return 0; -} - +template inline int WINAPI LoadString(_In_opt_ HINSTANCE hInstance, _In_ UINT uID, _Out_ std::basic_string &sBuffer); /// /// Loads a string resource from the executable file associated with a specified module. /// /// \sa [LoadString function](https://msdn.microsoft.com/en-us/library/windows/desktop/ms647486.aspx) /// -template -inline int WINAPI LoadString(_In_opt_ HINSTANCE hInstance, _In_ UINT uID, _Out_ std::basic_string &sBuffer) -{ - // Get read-only pointer to string resource. - LPCWSTR pszStr; - int i = LoadStringW(hInstance, uID, (LPWSTR)&pszStr, 0); - if (i) { - sBuffer.assign(pszStr, i); - return i; - } else - return 0; -} - +template inline int WINAPI LoadString(_In_opt_ HINSTANCE hInstance, _In_ UINT uID, _Out_ std::basic_string &sBuffer); /// /// Formats and sends a string to the debugger for display. /// /// \sa [OutputDebugString function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363362.aspx) /// -inline VOID OutputDebugStrV(_In_ LPCSTR lpOutputString, _In_ va_list arg) -{ - std::string str; - vsprintf(str, lpOutputString, arg); - OutputDebugStringA(str.c_str()); -} - +inline VOID OutputDebugStrV(_In_ LPCSTR lpOutputString, _In_ va_list arg); /// /// Formats and sends a string to the debugger for display. /// /// \sa [OutputDebugString function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363362.aspx) /// -inline VOID OutputDebugStrV(_In_ LPCWSTR lpOutputString, _In_ va_list arg) -{ - std::wstring str; - vsprintf(str, lpOutputString, arg); - OutputDebugStringW(str.c_str()); -} - +inline VOID OutputDebugStrV(_In_ LPCWSTR lpOutputString, _In_ va_list arg); /// /// Formats and sends a string to the debugger for display. /// /// \sa [OutputDebugString function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363362.aspx) /// -inline VOID OutputDebugStr(_In_ LPCSTR lpOutputString, ...) -{ - va_list arg; - va_start(arg, lpOutputString); - OutputDebugStrV(lpOutputString, arg); - va_end(arg); -} - +inline VOID OutputDebugStr(_In_ LPCSTR lpOutputString, ...); /// /// Formats and sends a string to the debugger for display. /// /// \sa [OutputDebugString function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363362.aspx) /// -inline VOID OutputDebugStr(_In_ LPCWSTR lpOutputString, ...) -{ - va_list arg; - va_start(arg, lpOutputString); - OutputDebugStrV(lpOutputString, arg); - va_end(arg); -} - +inline VOID OutputDebugStr(_In_ LPCWSTR lpOutputString, ...); /// /// Formats a date as a date string for a locale specified by the locale identifier. The function formats either a specified date or the local system date. /// /// \sa [GetDateFormat function](https://msdn.microsoft.com/en-us/library/windows/desktop/dd318086.aspx) /// -template inline int GetDateFormatA(_In_ LCID Locale, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpDate, _In_opt_ LPCSTR lpFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sDate) -{ - int iResult = GetDateFormatA(Locale, dwFlags, lpDate, lpFormat, NULL, 0); - if (iResult) { - // Allocate buffer on heap and retry. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[iResult]); - iResult = GetDateFormatA(Locale, dwFlags, lpDate, lpFormat, szBuffer.get(), iResult); - sDate.assign(szBuffer.get(), iResult ? iResult - 1 : 0); - return iResult; - } - - return iResult; -} - +template inline int GetDateFormatA(_In_ LCID Locale, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpDate, _In_opt_ LPCSTR lpFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sDate); /// /// Formats a date as a date string for a locale specified by the locale identifier. The function formats either a specified date or the local system date. /// /// \sa [GetDateFormat function](https://msdn.microsoft.com/en-us/library/windows/desktop/dd318086.aspx) /// -template inline int GetDateFormatW(_In_ LCID Locale, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpDate, _In_opt_ LPCWSTR lpFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sDate) -{ - int iResult = GetDateFormatW(Locale, dwFlags, lpDate, lpFormat, NULL, 0); - if (iResult) { - // Allocate buffer on heap and retry. - auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[iResult]); - iResult = GetDateFormatW(Locale, dwFlags, lpDate, lpFormat, szBuffer.get(), iResult); - sDate.assign(szBuffer.get(), iResult ? iResult - 1 : 0); - return iResult; - } - - return iResult; -} - +template inline int GetDateFormatW(_In_ LCID Locale, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpDate, _In_opt_ LPCWSTR lpFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sDate); /// /// Retrieves the name of the account for this SID and the name of the first domain on which this SID is found. /// /// \sa [LookupAccountSid function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379166.aspx) /// -template -inline BOOL LookupAccountSidA(_In_opt_ LPCSTR lpSystemName, _In_ PSID lpSid, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sName, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sReferencedDomainName, _Out_ PSID_NAME_USE peUse) -{ - assert(0); // TODO: Test this code. - - DWORD dwNameLen = 0, dwRefDomainLen = 0; - - if (LookupAccountSidA(lpSystemName, lpSid, - NULL, sName ? &dwNameLen : NULL, - NULL, sReferencedDomainName ? &dwRefDomainLen : NULL, - peUse)) - { - // Name and domain is blank. - if (sName ) sName ->clear(); - if (sReferencedDomainName) sReferencedDomainName->clear(); - return TRUE; - } else if (GetLastError() == ERROR_MORE_DATA) { - // Allocate on heap and retry. - std::unique_ptr<_Elem[]> bufName (new _Elem[dwNameLen ]); - std::unique_ptr<_Elem[]> bufRefDomain(new _Elem[dwRefDomainLen]); - if (LookupAccountSidA(lpSystemName, lpSid, - bufName .get(), sName ? &dwNameLen : NULL, - bufRefDomain.get(), sReferencedDomainName ? &dwRefDomainLen : NULL, - peUse)) - { - if (sName ) sName ->assign(bufName .get(), dwNameLen - 1); - if (sReferencedDomainName) sReferencedDomainName->assign(bufRefDomain.get(), dwRefDomainLen - 1); - return TRUE; - } - } - - return FALSE; -} - +template inline BOOL LookupAccountSidA(_In_opt_ LPCSTR lpSystemName, _In_ PSID lpSid, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sName, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sReferencedDomainName, _Out_ PSID_NAME_USE peUse); /// /// Retrieves the name of the account for this SID and the name of the first domain on which this SID is found. /// /// \sa [LookupAccountSid function](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379166.aspx) /// -template -inline BOOL LookupAccountSidW(_In_opt_ LPCWSTR lpSystemName, _In_ PSID lpSid, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sName, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sReferencedDomainName, _Out_ PSID_NAME_USE peUse) -{ - assert(0); // TODO: Test this code. - - DWORD dwNameLen = 0, dwRefDomainLen = 0; - - if (LookupAccountSidW(lpSystemName, lpSid, - NULL, sName ? &dwNameLen : NULL, - NULL, sReferencedDomainName ? &dwRefDomainLen : NULL, - peUse)) - { - // Name and domain is blank. - if (sName ) sName ->clear(); - if (sReferencedDomainName) sReferencedDomainName->clear(); - return TRUE; - } else if (GetLastError() == ERROR_MORE_DATA) { - // Allocate on heap and retry. - std::unique_ptr<_Elem[]> bufName (new _Elem[dwNameLen ]); - std::unique_ptr<_Elem[]> bufRefDomain(new _Elem[dwRefDomainLen]); - if (LookupAccountSidW(lpSystemName, lpSid, - bufName .get(), sName ? &dwNameLen : NULL, - bufRefDomain.get(), sReferencedDomainName ? &dwRefDomainLen : NULL, - peUse)) - { - if (sName ) sName ->assign(bufName .get(), dwNameLen - 1); - if (sReferencedDomainName) sReferencedDomainName->assign(bufRefDomain.get(), dwRefDomainLen - 1); - return TRUE; - } - } - - return FALSE; -} +template inline BOOL LookupAccountSidW(_In_opt_ LPCWSTR lpSystemName, _In_ PSID lpSid, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sName, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sReferencedDomainName, _Out_ PSID_NAME_USE peUse); /// @} +#pragma once + namespace winstd { - /// \addtogroup WinStdWinAPI - /// @{ - - /// - /// Windows HANDLE wrapper class - /// class WINSTD_API win_handle : public handle { public: @@ -969,9 +393,6 @@ namespace winstd }; - /// - /// Module handle wrapper - /// class WINSTD_API library : public handle { public: @@ -1011,9 +432,6 @@ namespace winstd }; - /// - /// Process handle wrapper - /// class WINSTD_API process : public win_handle { public: @@ -1038,9 +456,6 @@ namespace winstd }; - /// - /// Heap handle wrapper - /// class WINSTD_API heap : public handle { public: @@ -1089,9 +504,6 @@ namespace winstd }; - /// - /// Activates given activation context in constructor and deactivates it in destructor - /// class WINSTD_API actctx_activator { public: @@ -1116,9 +528,6 @@ namespace winstd }; - /// - /// Lets the calling thread impersonate the security context of a logged-on user - /// class WINSTD_API user_impersonator { public: @@ -1143,9 +552,6 @@ namespace winstd }; - /// - /// Memory in virtual address space of a process handle wrapper - /// class WINSTD_API vmemory : public handle { public: @@ -1248,6 +654,634 @@ namespace winstd protected: HANDLE m_proc; ///< Handle of memory's process }; - - /// @} +} + + +template +inline DWORD GetModuleFileNameA(_In_opt_ HMODULE hModule, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) +{ + assert(0); // TODO: Test this code. + + _Elem szBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; + + // Try with stack buffer first. + DWORD dwResult = ::GetModuleFileNameA(hModule, szBuffer, _countof(szBuffer)); + if (dwResult < _countof(szBuffer)) { + // Copy from stack. + sValue.assign(szBuffer, dwResult); + return dwResult; + } else { + for (DWORD dwCapacity = 2*WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem);; dwCapacity *= 2) { + // Allocate on heap and retry. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwCapacity]); + dwResult = ::GetModuleFileNameA(hModule, szBuffer.get(), dwCapacity); + if (dwResult < dwCapacity) { + sValue.assign(szBuffer.get(), dwResult); + return dwResult; + } + } + } +} + + +template +inline DWORD GetModuleFileNameW(_In_opt_ HMODULE hModule, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) +{ + _Elem szBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; + + // Try with stack buffer first. + DWORD dwResult = ::GetModuleFileNameW(hModule, szBuffer, _countof(szBuffer)); + if (dwResult < _countof(szBuffer)) { + // Copy from stack. + sValue.assign(szBuffer, dwResult); + return dwResult; + } else { + for (DWORD dwCapacity = 2*WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem);; dwCapacity *= 2) { + // Allocate on heap and retry. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwCapacity]); + dwResult = ::GetModuleFileNameW(hModule, szBuffer.get(), dwCapacity); + if (dwResult < dwCapacity) { + sValue.assign(szBuffer.get(), dwResult); + return dwResult; + } + } + } +} + + +template +inline int GetWindowTextA(_In_ HWND hWnd, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) +{ + assert(0); // TODO: Test this code. + + int iResult; + + // Query the final string length first. + iResult = ::GetWindowTextLengthA(hWnd); + if (iResult > 0) { + if (++iResult < WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)) { + // Read string data to stack. + _Elem szBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; + iResult = ::GetWindowTextA(hWnd, szBuffer, _countof(szBuffer)); + sValue.assign(szBuffer, iResult); + } else { + // Allocate buffer on heap and read the string data into it. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[++iResult]); + iResult = ::GetWindowTextA(hWnd, szBuffer.get(), iResult); + sValue.assign(szBuffer.get(), iResult); + } + return iResult; + } + + sValue.clear(); + return 0; +} + + +template +inline int GetWindowTextW(_In_ HWND hWnd, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) +{ + assert(0); // TODO: Test this code. + + int iResult; + + // Query the final string length first. + iResult = ::GetWindowTextLengthW(hWnd); + if (iResult > 0) { + if (++iResult < WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)) { + // Read string data to stack. + _Elem szBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; + iResult = ::GetWindowTextW(hWnd, szBuffer, _countof(szBuffer)); + sValue.assign(szBuffer, iResult); + } else { + // Allocate buffer on heap and read the string data into it. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[++iResult]); + iResult = ::GetWindowTextW(hWnd, szBuffer.get(), iResult); + sValue.assign(szBuffer.get(), iResult); + } + return iResult; + } + + sValue.clear(); + return 0; +} + + +template +inline BOOL GetFileVersionInfoA(_In_ LPCSTR lptstrFilename, __reserved DWORD dwHandle, _Out_ std::vector<_Ty, _Ax> &aValue) +{ + assert(0); // TODO: Test this code. + + // Get version info size. + DWORD dwVerInfoSize = ::GetFileVersionInfoSizeA(lptstrFilename, &dwHandle); + if (dwVerInfoSize != 0) { + // Read version info. + aValue.resize((dwVerInfoSize + sizeof(_Ty) - 1) / sizeof(_Ty)); + return ::GetFileVersionInfoA(lptstrFilename, dwHandle, dwVerInfoSize, aValue.data()); + } else + return FALSE; +} + + +template +inline BOOL GetFileVersionInfoW(_In_ LPCWSTR lptstrFilename, __reserved DWORD dwHandle, _Out_ std::vector<_Ty, _Ax> &aValue) +{ + assert(0); // TODO: Test this code. + + // Get version info size. + DWORD dwVerInfoSize = ::GetFileVersionInfoSizeW(lptstrFilename, &dwHandle); + if (dwVerInfoSize != 0) { + // Read version info. + aValue.resize((dwVerInfoSize + sizeof(_Ty) - 1) / sizeof(_Ty)); + return ::GetFileVersionInfoW(lptstrFilename, dwHandle, dwVerInfoSize, aValue.data()); + } else + return FALSE; +} + + +template +inline DWORD ExpandEnvironmentStringsW(_In_ LPCSTR lpSrc, std::basic_string<_Elem, _Traits, _Ax> &sValue) +{ + assert(0); // TODO: Test this code. + + for (DWORD dwSizeOut = (DWORD)strlen(lpSrc) + 0x100;;) { + DWORD dwSizeIn = dwSizeOut; + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSizeIn + 2]); // Note: ANSI version requires one extra char. + dwSizeOut = ::ExpandEnvironmentStringsA(lpSrc, szBuffer.get(), dwSizeIn); + if (dwSizeOut == 0) { + // Error. + break; + } else if (dwSizeOut <= dwSizeIn) { + // The buffer was sufficient. + sValue.assign(szBuffer.get(), dwSizeOut); + return dwSizeOut; + } + } + + sValue.clear(); + return 0; +} + + +template +inline DWORD ExpandEnvironmentStringsW(_In_ LPCWSTR lpSrc, std::basic_string<_Elem, _Traits, _Ax> &sValue) +{ + assert(0); // TODO: Test this code. + + for (DWORD dwSizeOut = (DWORD)wcslen(lpSrc) + 0x100;;) { + DWORD dwSizeIn = dwSizeOut; + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSizeIn + 1]); + dwSizeOut = ::ExpandEnvironmentStringsW(lpSrc, szBuffer.get(), dwSizeIn); + if (dwSizeOut == 0) { + // Error. + break; + } else if (dwSizeOut <= dwSizeIn) { + // The buffer was sufficient. + sValue.assign(szBuffer.get(), dwSizeOut); + return dwSizeOut; + } + } + + sValue.clear(); + return 0; +} + + +template +inline VOID GuidToStringA(_In_ LPCGUID lpGuid, _Out_ std::basic_string<_Elem, _Traits, _Ax> &str) +{ + assert(0); // TODO: Test this code. + + sprintf(str, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", + lpGuid->Data1, + lpGuid->Data2, + lpGuid->Data3, + lpGuid->Data4[0], lpGuid->Data4[1], + lpGuid->Data4[2], lpGuid->Data4[3], lpGuid->Data4[4], lpGuid->Data4[5], lpGuid->Data4[6], lpGuid->Data4[7]); +} + + +template +inline VOID GuidToStringW(_In_ LPCGUID lpGuid, _Out_ std::basic_string<_Elem, _Traits, _Ax> &str) +{ + assert(0); // TODO: Test this code. + + sprintf(str, L"{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", + lpGuid->Data1, + lpGuid->Data2, + lpGuid->Data3, + lpGuid->Data4[0], lpGuid->Data4[1], + lpGuid->Data4[2], lpGuid->Data4[3], lpGuid->Data4[4], lpGuid->Data4[5], lpGuid->Data4[6], lpGuid->Data4[7]); +} + + +template +inline LSTATUS RegQueryStringValue(_In_ HKEY hReg, _In_z_ LPCSTR pszName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) +{ + assert(0); // TODO: Test this code. + + LSTATUS lResult; + BYTE aStackBuffer[WINSTD_STACK_BUFFER_BYTES]; + DWORD dwSize = sizeof(aStackBuffer), dwType; + + // Try with stack buffer first. + lResult = ::RegQueryValueExA(hReg, pszName, NULL, &dwType, aStackBuffer, &dwSize); + if (lResult == ERROR_SUCCESS) { + if (dwType == REG_SZ || dwType == REG_MULTI_SZ) { + // The value is REG_SZ or REG_MULTI_SZ. + sValue.assign((_Elem*)aStackBuffer, dwSize / sizeof(_Elem)); + } else if (dwType == REG_EXPAND_SZ) { + // The value is REG_EXPAND_SZ. Expand it from stack buffer. + if (::ExpandEnvironmentStringsW((const _Elem*)aStackBuffer, sValue) == 0) + lResult = ::GetLastError(); + } else { + // The value is not a string type. + lResult = ERROR_INVALID_DATA; + } + } else if (lResult == ERROR_MORE_DATA) { + if (dwType == REG_SZ || dwType == REG_MULTI_SZ) { + // The value is REG_SZ or REG_MULTI_SZ. Read it now. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize / sizeof(_Elem)]); + if ((lResult = ::RegQueryValueExA(hReg, pszName, NULL, NULL, (LPBYTE)szBuffer.get(), &dwSize)) == ERROR_SUCCESS) + sValue.assign(szBuffer.get(), dwSize / sizeof(_Elem)); + else + sValue.clear(); + } else if (dwType == REG_EXPAND_SZ) { + // The value is REG_EXPAND_SZ. Read it and expand environment variables. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize / sizeof(_Elem)]); + if ((lResult = ::RegQueryValueExA(hReg, pszName, NULL, NULL, (LPBYTE)szBuffer.get(), &dwSize)) == ERROR_SUCCESS) { + if (::ExpandEnvironmentStringsW(szBuffer.get(), sValue) == 0) + lResult = ::GetLastError(); + } else + sValue.clear(); + } else { + // The value is not a string type. + lResult = ERROR_INVALID_DATA; + } + } + + return lResult; +} + + +template +inline LSTATUS RegQueryStringValue(_In_ HKEY hReg, _In_z_ LPCWSTR pszName, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sValue) +{ + assert(0); // TODO: Test this code. + + LSTATUS lResult; + BYTE aStackBuffer[WINSTD_STACK_BUFFER_BYTES]; + DWORD dwSize = sizeof(aStackBuffer), dwType; + + // Try with stack buffer first. + lResult = ::RegQueryValueExW(hReg, pszName, NULL, &dwType, aStackBuffer, &dwSize); + if (lResult == ERROR_SUCCESS) { + if (dwType == REG_SZ || dwType == REG_MULTI_SZ) { + // The value is REG_SZ or REG_MULTI_SZ. + sValue.assign((_Elem*)aStackBuffer, dwSize / sizeof(_Elem)); + } else if (dwType == REG_EXPAND_SZ) { + // The value is REG_EXPAND_SZ. Expand it from stack buffer. + if (::ExpandEnvironmentStringsW((const _Elem*)aStackBuffer, sValue) == 0) + lResult = ::GetLastError(); + } else { + // The value is not a string type. + lResult = ERROR_INVALID_DATA; + } + } else if (lResult == ERROR_MORE_DATA) { + if (dwType == REG_SZ || dwType == REG_MULTI_SZ) { + // The value is REG_SZ or REG_MULTI_SZ. Read it now. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize / sizeof(_Elem)]); + if ((lResult = ::RegQueryValueExW(hReg, pszName, NULL, NULL, (LPBYTE)szBuffer.get(), &dwSize)) == ERROR_SUCCESS) + sValue.assign(szBuffer.get(), dwSize / sizeof(_Elem)); + else + sValue.clear(); + } else if (dwType == REG_EXPAND_SZ) { + // The value is REG_EXPAND_SZ. Read it and expand environment variables. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize / sizeof(_Elem)]); + if ((lResult = ::RegQueryValueExW(hReg, pszName, NULL, NULL, (LPBYTE)szBuffer.get(), &dwSize)) == ERROR_SUCCESS) { + if (::ExpandEnvironmentStringsW(szBuffer.get(), sValue) == 0) + lResult = ::GetLastError(); + } else + sValue.clear(); + } else { + // The value is not a string type. + lResult = ERROR_INVALID_DATA; + } + } + + return lResult; +} + + +template +inline LSTATUS RegQueryValueExA(_In_ HKEY hKey, _In_opt_ LPCSTR lpValueName, __reserved LPDWORD lpReserved, _Out_opt_ LPDWORD lpType, _Out_ std::vector<_Ty, _Ax> &aData) +{ + assert(0); // TODO: Test this code. + + LSTATUS lResult; + BYTE aStackBuffer[WINSTD_STACK_BUFFER_BYTES]; + DWORD dwSize = sizeof(aStackBuffer); + + // Try with stack buffer first. + lResult = RegQueryValueExA(hKey, lpValueName, lpReserved, NULL, aStackBuffer, &dwSize); + if (lResult == ERROR_SUCCESS) { + // Copy from stack buffer. + aData.resize((dwSize + sizeof(_Ty) - 1) / sizeof(_Ty)); + memcpy(aData.data(), aStackBuffer, dwSize); + } else if (lResult == ERROR_MORE_DATA) { + // Allocate buffer on heap and retry. + aData.resize((dwSize + sizeof(_Ty) - 1) / sizeof(_Ty)); + if ((lResult = RegQueryValueExA(hKey, lpValueName, lpReserved, lpType, aData.data(), &dwSize)) != ERROR_SUCCESS) + aData.clear(); + } + + return lResult; +} + + +template +inline LSTATUS RegQueryValueExW(_In_ HKEY hKey, _In_opt_ LPCWSTR lpValueName, __reserved LPDWORD lpReserved, _Out_opt_ LPDWORD lpType, _Out_ std::vector<_Ty, _Ax> &aData) +{ + assert(0); // TODO: Test this code. + + LSTATUS lResult; + BYTE aStackBuffer[WINSTD_STACK_BUFFER_BYTES]; + DWORD dwSize = sizeof(aStackBuffer); + + // Try with stack buffer first. + lResult = RegQueryValueExW(hKey, lpValueName, lpReserved, NULL, aStackBuffer, &dwSize); + if (lResult == ERROR_SUCCESS) { + // Copy from stack buffer. + aData.resize((dwSize + sizeof(_Ty) - 1) / sizeof(_Ty)); + memcpy(aData.data(), aStackBuffer, dwSize); + } else if (lResult == ERROR_MORE_DATA) { + // Allocate buffer on heap and retry. + aData.resize((dwSize + sizeof(_Ty) - 1) / sizeof(_Ty)); + if ((lResult = RegQueryValueExW(hKey, lpValueName, lpReserved, lpType, aData.data(), &dwSize)) != ERROR_SUCCESS) + aData.clear(); + } + + return lResult; +} + + +#if _WIN32_WINNT >= _WIN32_WINNT_VISTA + +template +inline LSTATUS RegLoadMUIStringA(_In_ HKEY hKey, _In_opt_ LPCSTR pszValue, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sOut, _In_ DWORD Flags, _In_opt_ LPCSTR pszDirectory) +{ + assert(0); // TODO: Test this code. + + LSTATUS lResult; + _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; + DWORD dwSize; + + Flags &= ~REG_MUI_STRING_TRUNCATE; + + // Try with stack buffer first. + lResult = RegLoadMUIStringA(hKey, pszValue, szStackBuffer, _countof(szStackBuffer), &dwSize, Flags, pszDirectory); + if (lResult == ERROR_SUCCESS) { + // Copy from stack buffer. + sOut.assign(szStackBuffer, dwSize); + } else if (lResult == ERROR_MORE_DATA) { + // Allocate buffer on heap and retry. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize + 1]); + sOut.assign(szBuffer.get(), (lResult = RegLoadMUIStringA(hKey, pszValue, szBuffer.get(), dwSize, &dwSize, Flags, pszDirectory)) == ERROR_SUCCESS ? dwSize : 0); + } + + return lResult; +} + + +template +inline LSTATUS RegLoadMUIStringW(_In_ HKEY hKey, _In_opt_ LPCWSTR pszValue, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sOut, _In_ DWORD Flags, _In_opt_ LPCWSTR pszDirectory) +{ + assert(0); // TODO: Test this code. + + LSTATUS lResult; + _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; + DWORD dwSize; + + Flags &= ~REG_MUI_STRING_TRUNCATE; + + // Try with stack buffer first. + lResult = RegLoadMUIStringW(hKey, pszValue, szStackBuffer, _countof(szStackBuffer), &dwSize, Flags, pszDirectory); + if (lResult == ERROR_SUCCESS) { + // Copy from stack buffer. + sOut.assign(szStackBuffer, dwSize); + } else if (lResult == ERROR_MORE_DATA) { + // Allocate buffer on heap and retry. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[dwSize + 1]); + sOut.assign(szBuffer.get(), (lResult = RegLoadMUIStringW(hKey, pszValue, szBuffer.get(), dwSize, &dwSize, Flags, pszDirectory)) == ERROR_SUCCESS ? dwSize : 0); + } + + return lResult; +} + +#endif + + +template +inline int WideCharToMultiByte(_In_ UINT CodePage, _In_ DWORD dwFlags, _In_z_count_(cchWideChar) LPCWSTR lpWideCharStr, _In_ int cchWideChar, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sMultiByteStr, _In_opt_ LPCSTR lpDefaultChar, _Out_opt_ LPBOOL lpUsedDefaultChar) +{ + _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; + + // Try to convert to stack buffer first. + int cch = ::WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, szStackBuffer, _countof(szStackBuffer), lpDefaultChar, lpUsedDefaultChar); + if (cch) { + // Copy from stack. Be careful not to include zero terminator. + sMultiByteStr.assign(szStackBuffer, cchWideChar != -1 ? strnlen(szStackBuffer, cch) : cch - 1); + } else if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { + // Query the required output size. Allocate buffer. Then convert again. + cch = ::WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, NULL, 0, lpDefaultChar, lpUsedDefaultChar); + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[cch]); + cch = ::WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, szBuffer.get(), cch, lpDefaultChar, lpUsedDefaultChar); + sMultiByteStr.assign(szBuffer.get(), cchWideChar != -1 ? strnlen(szBuffer.get(), cch) : cch - 1); + } + + return cch; +} + + +template +inline int MultiByteToWideChar(_In_ UINT CodePage, _In_ DWORD dwFlags, _In_z_count_(cbMultiByte) LPCSTR lpMultiByteStr, _In_ int cbMultiByte, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sWideCharStr) +{ + _Elem szStackBuffer[WINSTD_STACK_BUFFER_BYTES/sizeof(_Elem)]; + + // Try to convert to stack buffer first. + int cch = ::MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, szStackBuffer, _countof(szStackBuffer)); + if (cch) { + // Copy from stack. + sWideCharStr.assign(szStackBuffer, cch); + } else if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { + // Query the required output size. Allocate buffer. Then convert again. + cch = ::MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, NULL, 0); + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[cch]); + cch = ::MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, szBuffer.get(), cch); + sWideCharStr.assign(szBuffer.get(), cch); + } + + return cch; +} + + +template +inline int WINAPI LoadString(_In_opt_ HINSTANCE hInstance, _In_ UINT uID, _Out_ std::basic_string &sBuffer) +{ + // Get read-only pointer to string resource. + LPCSTR pszStr; + int i = LoadStringA(hInstance, uID, (LPSTR)&pszStr, 0); + if (i) { + sBuffer.assign(pszStr, i); + return i; + } else + return 0; +} + + +template +inline int WINAPI LoadString(_In_opt_ HINSTANCE hInstance, _In_ UINT uID, _Out_ std::basic_string &sBuffer) +{ + // Get read-only pointer to string resource. + LPCWSTR pszStr; + int i = LoadStringW(hInstance, uID, (LPWSTR)&pszStr, 0); + if (i) { + sBuffer.assign(pszStr, i); + return i; + } else + return 0; +} + + +inline VOID OutputDebugStrV(_In_ LPCSTR lpOutputString, _In_ va_list arg) +{ + std::string str; + vsprintf(str, lpOutputString, arg); + OutputDebugStringA(str.c_str()); +} + + +inline VOID OutputDebugStrV(_In_ LPCWSTR lpOutputString, _In_ va_list arg) +{ + std::wstring str; + vsprintf(str, lpOutputString, arg); + OutputDebugStringW(str.c_str()); +} + + +inline VOID OutputDebugStr(_In_ LPCSTR lpOutputString, ...) +{ + va_list arg; + va_start(arg, lpOutputString); + OutputDebugStrV(lpOutputString, arg); + va_end(arg); +} + + +inline VOID OutputDebugStr(_In_ LPCWSTR lpOutputString, ...) +{ + va_list arg; + va_start(arg, lpOutputString); + OutputDebugStrV(lpOutputString, arg); + va_end(arg); +} + + +template inline int GetDateFormatA(_In_ LCID Locale, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpDate, _In_opt_ LPCSTR lpFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sDate) +{ + int iResult = GetDateFormatA(Locale, dwFlags, lpDate, lpFormat, NULL, 0); + if (iResult) { + // Allocate buffer on heap and retry. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[iResult]); + iResult = GetDateFormatA(Locale, dwFlags, lpDate, lpFormat, szBuffer.get(), iResult); + sDate.assign(szBuffer.get(), iResult ? iResult - 1 : 0); + return iResult; + } + + return iResult; +} + + +template inline int GetDateFormatW(_In_ LCID Locale, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpDate, _In_opt_ LPCWSTR lpFormat, _Out_ std::basic_string<_Elem, _Traits, _Ax> &sDate) +{ + int iResult = GetDateFormatW(Locale, dwFlags, lpDate, lpFormat, NULL, 0); + if (iResult) { + // Allocate buffer on heap and retry. + auto szBuffer = std::unique_ptr<_Elem[]>(new _Elem[iResult]); + iResult = GetDateFormatW(Locale, dwFlags, lpDate, lpFormat, szBuffer.get(), iResult); + sDate.assign(szBuffer.get(), iResult ? iResult - 1 : 0); + return iResult; + } + + return iResult; +} + + +template +inline BOOL LookupAccountSidA(_In_opt_ LPCSTR lpSystemName, _In_ PSID lpSid, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sName, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sReferencedDomainName, _Out_ PSID_NAME_USE peUse) +{ + assert(0); // TODO: Test this code. + + DWORD dwNameLen = 0, dwRefDomainLen = 0; + + if (LookupAccountSidA(lpSystemName, lpSid, + NULL, sName ? &dwNameLen : NULL, + NULL, sReferencedDomainName ? &dwRefDomainLen : NULL, + peUse)) + { + // Name and domain is blank. + if (sName ) sName ->clear(); + if (sReferencedDomainName) sReferencedDomainName->clear(); + return TRUE; + } else if (GetLastError() == ERROR_MORE_DATA) { + // Allocate on heap and retry. + std::unique_ptr<_Elem[]> bufName (new _Elem[dwNameLen ]); + std::unique_ptr<_Elem[]> bufRefDomain(new _Elem[dwRefDomainLen]); + if (LookupAccountSidA(lpSystemName, lpSid, + bufName .get(), sName ? &dwNameLen : NULL, + bufRefDomain.get(), sReferencedDomainName ? &dwRefDomainLen : NULL, + peUse)) + { + if (sName ) sName ->assign(bufName .get(), dwNameLen - 1); + if (sReferencedDomainName) sReferencedDomainName->assign(bufRefDomain.get(), dwRefDomainLen - 1); + return TRUE; + } + } + + return FALSE; +} + + +template +inline BOOL LookupAccountSidW(_In_opt_ LPCWSTR lpSystemName, _In_ PSID lpSid, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sName, _Out_opt_ std::basic_string<_Elem, _Traits, _Ax> *sReferencedDomainName, _Out_ PSID_NAME_USE peUse) +{ + assert(0); // TODO: Test this code. + + DWORD dwNameLen = 0, dwRefDomainLen = 0; + + if (LookupAccountSidW(lpSystemName, lpSid, + NULL, sName ? &dwNameLen : NULL, + NULL, sReferencedDomainName ? &dwRefDomainLen : NULL, + peUse)) + { + // Name and domain is blank. + if (sName ) sName ->clear(); + if (sReferencedDomainName) sReferencedDomainName->clear(); + return TRUE; + } else if (GetLastError() == ERROR_MORE_DATA) { + // Allocate on heap and retry. + std::unique_ptr<_Elem[]> bufName (new _Elem[dwNameLen ]); + std::unique_ptr<_Elem[]> bufRefDomain(new _Elem[dwRefDomainLen]); + if (LookupAccountSidW(lpSystemName, lpSid, + bufName .get(), sName ? &dwNameLen : NULL, + bufRefDomain.get(), sReferencedDomainName ? &dwRefDomainLen : NULL, + peUse)) + { + if (sName ) sName ->assign(bufName .get(), dwNameLen - 1); + if (sReferencedDomainName) sReferencedDomainName->assign(bufRefDomain.get(), dwRefDomainLen - 1); + return TRUE; + } + } + + return FALSE; }