Crash Dump generation and analysis issues - c++

I used the example from https://github.com/hdeldar/QtCrashDumper and made us of the same in my application. Lately for actual crashes in the application the stack trace has been a little useless.
Another question is the dmp files generated module version does not match. I have double checked the module version and it is the same however the dump file has different versions. File version is 2.8.0.4 and the dmp file has 2.08.0.4
I have looked into a few answers on stackoverflow to not understand what functions I am missing.
CrashDump Info
The KB link does not exist anymore - KB313109
My implementation
#include "CrashDumpDef.h"
#include "version.h"
#ifdef USE_MINI_DUMP
#include "CrashDump.h"
#include "FileSystem.h"
LPCWSTR CrashDump::m_szAppName;
LPWSTR CrashDump::m_szAppVersion;
LPWSTR CrashDump::m_szAppBuildNumber;
WCHAR CrashDump::m_szMessageText[MAX_WARNING_MESSAGE_PATH];
LPWSTR CrashDump::m_szDumpFilePath;
#define DEFAULT_MESSAGE_TEXT L"%s Designer has experienced an issue. \nCrash dump has been saved in %s."
#define MAX_DUMP_FILE_NUMBER 9999
CrashDump::CrashDump(LPCWSTR szAppName, LPCWSTR szVersion, LPCWSTR szBuildNumber)
{
// if this assert fires then you have two instances of CrashDump
// which is not allowed
Q_ASSERT(m_szAppName == NULL);
const char* sz = VER_PRODUCTVERSION_STR;
std::vector<wchar_t> vec;
size_t len = strlen(sz);
vec.resize(len + 1);
mbstowcs(&vec[0], sz, len);
const wchar_t* productVersion = &vec[0];
std::string version = VER_PRODUCTVERSION_STR;
char build = version.back();
const char* buildNum = new char(build);
std::vector<wchar_t> vec1;
size_t lenA = strlen(buildNum);
vec1.resize(lenA + 1);
mbstowcs(&vec1[0], buildNum, lenA);
const wchar_t* buildNumber = &vec1[0];
m_szAppName = szAppName ? wcsdup(szAppName) : wcsdup(L"Designer");
m_szAppVersion = productVersion ? wcsdup(productVersion) : wcsdup(productVersion);
m_szAppBuildNumber = buildNumber ? wcsdup(buildNumber) : wcsdup(buildNumber);
wcscpy(m_szMessageText, DEFAULT_MESSAGE_TEXT);
m_szDumpFilePath = NULL;
::SetUnhandledExceptionFilter(TopLevelFilter);
}
CrashDump::~CrashDump()
{
}
void CrashDump::SetVersion(LPCWSTR szVersion)
{
if (szVersion)
{
free(m_szAppVersion);
m_szAppVersion = wcsdup(szVersion);
}
}
void CrashDump::SetBuildNumber(LPCWSTR szBuildNumber)
{
if (szBuildNumber)
{
free(m_szAppBuildNumber);
m_szAppBuildNumber = wcsdup(szBuildNumber);
}
}
void CrashDump::SetDumpFilePath(LPCWSTR szFilePath)
{
free(m_szDumpFilePath);
{
m_szDumpFilePath = wcsdup(szFilePath);
}
}
LONG CrashDump::TopLevelFilter(struct _EXCEPTION_POINTERS *pExceptionInfo)
{
//::MessageBoxW(NULL, L"debugging", m_szAppName, MB_OK);
LONG retval = EXCEPTION_CONTINUE_SEARCH;
HWND hParent = NULL; // find a better value for your app
// firstly see if dbghelp.dll is around and has the function we need
// look next to the EXE first, as the one in System32 might be old
// (e.g. Windows 2000)
HMODULE hDll = NULL;
WCHAR szDbgHelpPath[_MAX_PATH];
if (GetModuleFileName(NULL, szDbgHelpPath, _MAX_PATH))
{
WCHAR *pSlash = wcsrchr(szDbgHelpPath, L'\\');
if (pSlash)
{
wcscpy(pSlash + 1, L"DBGHELP.DLL");
hDll = ::LoadLibrary(szDbgHelpPath);
}
}
if (hDll == NULL)
{
// load any version we can
hDll = ::LoadLibrary(L"DBGHELP.DLL");
}
LPCWSTR szResult = NULL;
if (hDll)
{
MINIDUMPWRITEDUMP pDump = (MINIDUMPWRITEDUMP)::GetProcAddress(hDll, "MiniDumpWriteDump");
if (pDump)
{
WCHAR szDumpPath[_MAX_PATH];
WCHAR szDumpRootPath[_MAX_PATH];
WCHAR szScratch[_MAX_PATH];
// work out a good place for the dump file - add the path here
if (m_szDumpFilePath == NULL)
{
if (GetModuleFileName(NULL, szDbgHelpPath, _MAX_PATH))
{
WCHAR *pSlash = wcsrchr(szDbgHelpPath, L'\\');
if (pSlash)
{
wcscpy(pSlash + 1, L"");
wcscpy(szDumpPath, szDbgHelpPath);
}
}
//else if (!GetTempPath(_MAX_PATH, szDumpPath))
std::string dmpFile = filesystem::buildFilename(QStringList()
<< QDir::toNativeSeparators(QDir::homePath()) + "\\AppData\\Roaming\\ABC\\logs\\"
).toStdString();
std::wstring wideDmpFile;
for (int i = 0; i < dmpFile.length(); ++i)
wideDmpFile += wchar_t(dmpFile[i]);
const wchar_t* szName = wideDmpFile.c_str();
wcscpy(szDumpPath, szName);
}
else
{
wcscpy(szDumpPath, m_szDumpFilePath);
}
wcscpy(szDumpRootPath, szDumpPath);
//PrintDebug(L"[CrashDump] Mini Dump file:[%s]",szDumpPath);
// ask the user if they want to save a dump file
//if (::MessageBox( NULL, _T("Crash, would you like to save a diagnostic file?"), m_szAppName, MB_YESNO )==IDYES)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
int i = 1;
WCHAR szFileNumber[_MAX_PATH];
while (hFile == INVALID_HANDLE_VALUE)
{
swprintf(szFileNumber, sizeof(szFileNumber), L"_%04d", i);
wcscpy(szDumpPath, szDumpRootPath);
wcscat(szDumpPath, m_szAppName);
wcscat(szDumpPath, L"_");
wcscat(szDumpPath, m_szAppVersion);
wcscat(szDumpPath, L"_");
wcscat(szDumpPath, m_szAppBuildNumber);
wcscat(szDumpPath, szFileNumber);
wcscat(szDumpPath, L".dmp");
hFile = ::CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_NEW,
FILE_ATTRIBUTE_NORMAL, NULL);
i++;
if (i > MAX_DUMP_FILE_NUMBER)
{
hFile = ::CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
break;
}
}
// create the file
if (hFile != INVALID_HANDLE_VALUE)
{
_MINIDUMP_EXCEPTION_INFORMATION ExInfo;
ExInfo.ThreadId = ::GetCurrentThreadId();
ExInfo.ExceptionPointers = pExceptionInfo;
ExInfo.ClientPointers = NULL;
// write the dump
BOOL bOK = pDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ExInfo, NULL, NULL);
if (bOK)
{
swprintf(szScratch, sizeof(szScratch), L"Saved dump file to '%s'", szDumpPath);
szResult = szScratch;
retval = EXCEPTION_EXECUTE_HANDLER;
}
else
{
swprintf(szScratch, sizeof(szScratch), L"Failed to save dump file to '%s' (error %d)", szDumpPath, GetLastError());
szResult = szScratch;
}
::CloseHandle(hFile);
WCHAR csOutMessage[MAX_WARNING_MESSAGE_PATH];
swprintf(csOutMessage, sizeof(csOutMessage), m_szMessageText, m_szAppName, szDumpPath);
//PrintError(_T("%s"), csOutMessage);
::MessageBoxW(NULL, csOutMessage, m_szAppName, MB_OK);
}
else
{
swprintf(szScratch, sizeof(szScratch), L"Failed to create dump file '%s' (error %d)", szDumpPath, GetLastError());
szResult = szScratch;
}
}
}
else
{
szResult = L"DBGHELP.DLL too old";
}
}
else
{
szResult = L"DBGHELP.DLL not found";
}
if (szResult)
{
//PrintDebug(_T("[CrashDump] Mini Dump result:[%s]"),szResult);
}
return retval;
}
#endif

Related

Win32 CryptProtectData how to save output data?

https://learn.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptprotectdata
How can I save the output key to the windows registry or a file? I've been trying to do this for two days now but no progress. One of the problems is that I am using Unreal Engine and they have their own string type "FString" which does not easily convert to std::string or const char*
This is the code I'm using to save to the registry, but I'm not sure if it's valid:
void SUGH1LoginWidget::SecureSaveJWTToken(FString JWT_Token)
{
#ifdef _WIN32
DATA_BLOB DataIn;
DATA_BLOB DataOut; // Key to decrypt the data. Store in windows registry.
DATA_BLOB EncryptionKey; // Uses define in ShooterGame.h to encrypt the data so that only the UGH1 application can access the token.
DWORD cbDataInput = lstrlenA((char*)TCHAR_TO_ANSI(*JWT_Token)) + 1;
DataIn.pbData = (BYTE*)ConvertFStringToCString(JWT_Token).get();
DataIn.cbData = cbDataInput;
BYTE* pbDataEncryptionKey = (BYTE*)TOKEN_ENCRYPTION_KEY;
DWORD cbDataEncryptionKey = strlen((char*)pbDataEncryptionKey) + 1;
EncryptionKey.pbData = pbDataEncryptionKey;
EncryptionKey.cbData = cbDataEncryptionKey;
// Finally save the data
CryptProtectData(&DataIn, NULL, &EncryptionKey, NULL, NULL, NULL, &DataOut);
SaveJWTDecryptionKeyToRegistry(DataOut);
#endif
}
void SUGH1LoginWidget::SaveJWTDecryptionKeyToRegistry(DATA_BLOB DecryptionKey)
{
FString Base64EncryptionKey = FBase64::Encode(DecryptionKey.pbData, DecryptionKey.cbData);
HKEY CurrentUserKey;
LSTATUS Error;
Error = RegOpenCurrentUser(KEY_ALL_ACCESS, &CurrentUserKey);
if (Error == ERROR_SUCCESS)
{
HKEY SoftwareKey;
Error = RegOpenKeyExA(CurrentUserKey, "SOFTWARE", NULL, KEY_WRITE, &SoftwareKey);
if (Error == ERROR_SUCCESS)
{
HKEY UGHStudiosSubKey;
Error = RegCreateKeyExA(SoftwareKey, "UGH Studios LLC", NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &UGHStudiosSubKey, NULL);
if (Error == ERROR_SUCCESS)
{
Error = RegSetValueExA(UGHStudiosSubKey, "LoginTokenDecryptionKey", NULL, REG_SZ, (BYTE*)TCHAR_TO_ANSI(*Base64EncryptionKey), Base64EncryptionKey.Len());
RegCloseKey(UGHStudiosSubKey);
RegCloseKey(SoftwareKey);
if (Error != ERROR_SUCCESS)
{
UE_LOG(LogLoginWidget, Error, TEXT("The game was unable to save the login token to the registry."));
}
}
}
}
else
{
UE_LOG(LogLoginWidget, Error, TEXT("The game was unable to access the windows registry on this machine. "));
}
RegCloseKey(CurrentUserKey);
}
This is my code for loading from the registry back into an FString but it's not working properly:
std::shared_ptr<char[]> SUGH1LoginWidget::ConvertFStringToCString(const FString InputString)
{
std::shared_ptr<char[]> ptr(new char[InputString.Len()]);
TArray<TCHAR> CharArray = InputString.GetCharArray();
for (int i = 0; i < InputString.Len(); i++)
{
ptr[i] = CharArray[i];
}
return ptr;
}
PRAGMA_DISABLE_OPTIMIZATION
FReply SUGH1LoginWidget::GetJWTTokenFromRegistry()
{
TArray<uint8> DecryptionKeyBytes;
// load base64 string from registry
LSTATUS Error;
HKEY UGHStudiosSubKey;
Error = RegOpenKeyExA(HKEY_CURRENT_USER, "SOFTWARE\\UGH Studios LLC", NULL, KEY_READ, &UGHStudiosSubKey);
if (Error == ERROR_SUCCESS)
{
char buffer[8193] = { 0 };
DWORD dwLen = 8192;
DWORD dwType = 0;
Error = RegQueryValueExA(UGHStudiosSubKey, "LoginTokenDecryptionKey", 0, &dwType, (BYTE*)buffer, &dwLen);
if (Error == ERROR_SUCCESS)
{
std::string outValue = buffer;
FString decoded_string;
//FString reg_value_as_fstring = FString(outValue.length(), outValue.c_str());
uint8* decoded = malloc();
FBase64::Decode(outValue.c_str(), outValue.size(), decoded);
//:Decode(const FString & Source, TArray<uint8>&OutDest
//::Decode(const CharType* Source, uint32 Length, uint8* Dest)
//UE_LOG(LogLoginWidget, Error, TEXT("Out value: %s"), *decoded_string);
}
//Error = RegQueryValueExA(UGHStudiosSubKey, "LoginTokenDecryptionKey", NULL, NULL, buffer, size);
return FReply::Handled();
//return decoded_string;
//std::string outvalue = (char*)buffer;
}
//FBase64::Decode(, DecryptionKeyBytes)
//return FString("");
return FReply::Handled();
}
PRAGMA_ENABLE_OPTIMIZATION
What's the standard way of saving the struct data? I was tying to Base64 encrypt it and save it as a registry key. But this doesn't work.

change the use of SHBrowseForFolder and struct BROWSEINFO TO - IFileOpenDialog

until now- in order to open a dialog box I used SHBrowseForFolder function. It causes some bugs and I was told to use IFileOpenDialog.
here is the code I need to replace:
bool wvFM::SelectFileSystemObjectDialogTree(const WCDialogCreationOptions& in_options,
WCDialogReply& out_Reply)
{
AUTO_FUNC_DEBUG;
DWORD osErr = NO_ERROR;
WTErr wtErr = eNoErr;
out_Reply.accept = false;
if(in_options.m_flags[WCDialogCreationOptions::eSelectFolder]) {
BROWSEINFO bi = {0};
bi.hwndOwner = (HWND)in_options.m_owner;
bi.pidlRoot = NULL; // TBD by callback BrowseCallbackProc
bi.lpszTitle = in_options.m_windowTitle.c_str();
bi.ulFlags = BIF_USENEWUI; // to enable pasting path
bi.lpfn = BrowseCallbackProc; // for initial dir option
WTPathString initialLocationPathString(
in_options.m_InitialDir.GetNativePathString());
bi.lParam = in_options.m_InitialDir.IsValid()
? (LPARAM)initialLocationPathString.c_str()
: NULL;
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
// returns focus to the internal window of the plug
::SetFocus((HWND)in_options.m_owner);
if(pidl != NULL) {
TCHAR szPath[MAX_PATH];
SHGetPathFromIDList(pidl, szPath);
out_Reply.m_filePathRef = wvFM::WCStPath((char*)szPath);
out_Reply.accept = true;
IMalloc* imalloc = 0;
if(SUCCEEDED(SHGetMalloc(&imalloc))) {
imalloc->Free(pidl);
imalloc->Release();
}
}
return true;
}
I am not so sure of how to make that conversion.
Thanks to anyone who will help!
You are clearly using a 3rd party library with some kind of custom string type, but you did not provide any details about what that string type actually is. I'm guessing that string type is char-based, given that you are type-casting the result of SHGetPathFromIDList() to char* when assigning it to out_Reply.m_filePathRef, so you are likely compiling your project with UNICODE undefined so that TCHAR maps to char and not wchar_t. In which case, SHBrowseForFolder() would be calling SHBrowseForFolderA() and not SHBrowseForFolderW().
IFileOpenDialog does not deal with ANSI strings at all, only UNICODE strings, so you will have to convert back and forth between your 3rd party string type and Windows UTF-16 strings as needed.
The conversion of SHBrowseForFolder() to IFileOpenDialog would look roughly like the following (where YourStringType in toWString() is the 3rd party string type - make whatever adjustments you need where indicated):
std::wstring toWString(const YourStringType &str)
{
const char pStr = ... pointer to str's characters ...;
int sLen = ... length of str in chars, not counting the null terminator ...;
std::wstring ws;
int wLen = MultiByteToWideChar(CP_ACP, 0, pStr, slen, NULL, 0);
if (wLen > 0)
{
ws.resize(wLen);
MultiByteToWideChar(CP_ACP, 0, pStr, sLen, ws.data(), wLen);
}
return ws;
}
std::string toString(const wchar_t *ws)
{
std::string s;
int wLen = lstrlenW(s);
int sLen = WideCharToMultiByte(CP_ACP, 0, ws, wLen, NULL, 0, NULL, NULL);
if (sLen > 0)
{
s.resize(sLen);
WideCharToMultiByte(CP_ACP, 0, ws, wLen, s.data(), sLen, NULL, NULL);
}
return s;
}
IShellItem* toShellItem(const YourStringType &path)
{
IShellItem *pItem = NULL;
if (FAILED(SHCreateItemFromParsingName(toWString(path).c_str(), NULL, IID_PPV_ARGS(&pItem))))
pItem = NULL;
return pItem;
}
bool wvFM::SelectFileSystemObjectDialogTree(const WCDialogCreationOptions& in_options,
WCDialogReply& out_Reply)
{
AUTO_FUNC_DEBUG;
out_Reply.accept = false;
if (in_options.m_flags[WCDialogCreationOptions::eSelectFolder]) {
IFileOpenDialog *pFileOpen = NULL;
if (FAILED(CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pFileOpen))))
return false;
FILEOPENDIALOGOPTIONS opts = 0;
pFileOpen->GetOptions(&opts);
pFileOpen->SetTitle(toWString(in_options.m_windowTitle).c_str());
pFileOpen->SetOptions(opts | FOS_PICKFOLDERS);
IShellItem *pItem = toShellItem(in_options.m_InitialDir);
if (pItem)
{
pFileOpen->SetFolder(pItem);
pItem->Release();
}
HWND hwndOwner = (HWND) in_options.m_owner;
HRESULT hr = pFileOpen->Show(hwndOwner);
::SetFocus(hwndOwner);
if (SUCCEEDED(hr))
{
if (SUCCEEDED(pFileOpen->GetResult(&pItem)))
{
PWSTR pszFilePath;
if (SUCCEEDED(pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath)))
{
out_Reply.m_filePathRef = wvFM::WCStPath(toString(pszFilePath).c_str());
out_Reply.accept = true;
CoTaskMemFree(pszFilePath);
}
pItem->Release();
}
}
pFileOpen->Release();
return true;
}
...
}

How to get the specific windows service executable file path from Visual C++

How can i get the executable file path of a running Windows service from another program when i only know the service name?
Use QueryServiceConfig(). The QUERY_SERVICE_CONFIG::lpBinaryPathName field will report the full command line that is used to run the service.
For example:
struct SCHandle
{
private:
SC_HANDLE hValue;
public:
SCHandle(SC_HANDLE Value) : hValue(Value) {}
~SCHandle() { if (hValue != NULL) CloseServiceHandle(hValue); }
operator SC_HANDLE() { return hValue; }
bool operator!() const { return (hValue == NULL); }
};
std::wstring GetServiceBinaryName(const std::wstring &ServiceName)
{
SCHandle hSCManager(OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT));
if (!hSCManager)
return L"";
SCHandle hService(OpenServiceW(hSCManager, ServiceName.c_str(), SERVICE_QUERY_CONFIG));
if (!hService)
return L"";
std::vector<BYTE> buffer;
DWORD dwBytesNeeded = sizeof(QUERY_SERVICE_CONFIGW);
LPQUERY_SERVICE_CONFIGW pConfig;
do
{
buffer.resize(dwBytesNeeded);
pConfig = (LPQUERY_SERVICE_CONFIGW) &buffer[0];
if (QueryServiceConfigW(hService, pConfig, buffer.size(), &dwBytesNeeded))
return pConfig->lpBinaryPathName;
}
while (GetLastError() == ERROR_INSUFFICIENT_BUFFER);
return L"";
}
#include <Psapi.h>
#include <windows.h>
#pragma comment(lib, "psapi.lib")
int wmain()
{
//insert your service PID here instead of 404
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, 404);
if (!hProcess)
return(0);
wchar_t szBuffer[MAX_PATH];
ZeroMemory(szBuffer, sizeof(szBuffer));
DWORD dwSize = sizeof(szBuffer) / sizeof(szBuffer[0]) - 1;
QueryFullProcessImageName(hProcess, 0, szBuffer, &dwSize);
return(0);
}
You have to start your code with the elevated rights to access system service information. Otherwise OpenProcess will return NULL and GetLastError will return ERROR_ACCESS_DENIED code.
Also you could use:
GetProcessImageFileName to get path in the system native
format;
GetModuleFileNameEx with the NULL module handle.
Update: If you have only service name, then you have to use a different approach:
int wmain()
{
LPQUERY_SERVICE_CONFIG lpsc;
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, GENERIC_READ);
if (!hSCManager)
return(0);
SC_HANDLE hService = OpenService(hSCManager, L"Browser", SERVICE_QUERY_CONFIG);
if (!hService)
{
CloseServiceHandle(hSCManager);
return(0);
}
DWORD dwBytesNeeded = 0, dwBufSize;
if (!QueryServiceConfig(hService, NULL, 0, &dwBytesNeeded))
{
DWORD dwError = GetLastError();
if (ERROR_INSUFFICIENT_BUFFER == dwError)
{
dwBufSize = dwBytesNeeded;
lpsc = (LPQUERY_SERVICE_CONFIG)HeapAlloc(GetProcessHeap(), 0, dwBufSize);
}
else
{
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
return(0);
}
}
if (QueryServiceConfig(hService, lpsc, dwBufSize, &dwBytesNeeded))
{
//lpsc->lpBinaryPathName contains exe path
}
HeapFree(GetProcessHeap(), 0, lpsc);
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
return(0);
}

CreateFileMapping for Directory

I have this function which gives the full file name(path) from the file handle. The only problem is CreateFileMapping fails for directory handles. Is there a workaround for it?
I get the handle using NtCreateFile()
ULONG status = NtCreatefile(&f, GENERIC_ALL, &oa, iosb, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_OPEN_BY_FILE_ID , NULL, 0);
printf("status: %X, handle: %x\n", status, f);
AND
BOOL CHouseKeeper::GetFileNameFromHandle(HANDLE hFile)
{
BOOL bSuccess = FALSE;
TCHAR pszFilename[MAX_PATH+1];
HANDLE hFileMap;
// Get the file size.
DWORD dwFileSizeHi = 0;
DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi);
if( dwFileSizeLo == 0 && dwFileSizeHi == 0 )
{
_tprintf(TEXT("Cannot map a file with a length of zero.\n"));
return FALSE;
}
// Create a file mapping object.
//It fails here if a directory handle is passed, it returns 0
hFileMap = CreateFileMapping(hFile,
NULL,
PAGE_READONLY,
0,
1,
NULL);
if (hFileMap)
{
// Create a file mapping to get the file name.
void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
if (pMem)
{
if (GetMappedFileName (GetCurrentProcess(),
pMem,
pszFilename,
MAX_PATH))
{
// Translate path with device name to drive letters.
TCHAR szTemp[BUFSIZE];
szTemp[0] = '\0';
if (GetLogicalDriveStrings(BUFSIZE-1, szTemp))
{
TCHAR szName[MAX_PATH];
TCHAR szDrive[3] = TEXT(" :");
BOOL bFound = FALSE;
TCHAR* p = szTemp;
do
{
// Copy the drive letter to the template string
*szDrive = *p;
// Look up each device name
if (QueryDosDevice(szDrive, szName, MAX_PATH))
{
size_t uNameLen = _tcslen(szName);
if (uNameLen < MAX_PATH)
{
bFound = _tcsnicmp(pszFilename, szName, uNameLen) == 0
&& *(pszFilename + uNameLen) == _T('\\');
if (bFound)
{
// Reconstruct pszFilename using szTempFile
// Replace device path with DOS path
TCHAR szTempFile[MAX_PATH];
StringCchPrintf(szTempFile,
MAX_PATH,
TEXT("%s%s"),
szDrive,
pszFilename+uNameLen);
StringCchCopyN(pszFilename, MAX_PATH+1, szTempFile, _tcslen(szTempFile));
}
}
}
// Go to the next NULL character.
while (*p++);
} while (!bFound && *p); // end of string
}
}
bSuccess = TRUE;
UnmapViewOfFile(pMem);
}
CloseHandle(hFileMap);
}else {
wcout<<GetLastError()<<endl;
}
_tprintf(TEXT("File name is %s\n"), pszFilename);
return(bSuccess);
}
You can use NtQueryInformationFile with FileNameInformation to retrieve the name associated with a file handle.

C++: Get MAC address of network adapters on Vista?

We are currently using the NetBios method, and it works ok under XP. Preliminary tests under Vista show that it also works, but there are caveats - NetBIOS has to be present, for instance, and from what I've been reading, the order of the adapters is bound to change. Our alternative method - with SNMPExtensionQuery - seems to be broken under Vista.
The question is: do you know of a reliable way to get a list of the local MAC addresses on a Vista machine? Backwards compatibility with XP is a plus (I'd rather have one single method than lots of ugly #ifdef's). Thanks!
This will give you a list of all MAC addresses on your computer. It will work with all versions of Windows as well:
void getdMacAddresses(std::vector<std::string> &vMacAddresses;)
{
vMacAddresses.clear();
IP_ADAPTER_INFO AdapterInfo[32]; // Allocate information for up to 32 NICs
DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer
DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo
AdapterInfo, // [out] buffer to receive data
&dwBufLen); // [in] size of receive data buffer
//No network card? Other error?
if(dwStatus != ERROR_SUCCESS)
return;
PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
char szBuffer[512];
while(pAdapterInfo)
{
if(pAdapterInfo->Type == MIB_IF_TYPE_ETHERNET)
{
sprintf_s(szBuffer, sizeof(szBuffer), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x"
, pAdapterInfo->Address[0]
, pAdapterInfo->Address[1]
, pAdapterInfo->Address[2]
, pAdapterInfo->Address[3]
, pAdapterInfo->Address[4]
, pAdapterInfo->Address[5]
);
vMacAddresses.push_back(szBuffer);
}
pAdapterInfo = pAdapterInfo->Next;
}
}
Could you use the WMIService? I used it to get the mac-address of a machine in pre-Vista days though.
Old question, already answered, but this is safer code - in case WMI can't be fully initialized.
For getting access to information about your system, here is a minimalist class that tries to stay safe:
NOTE: ToString, convertToUtf8 and convertFromUtf8 are left as an exercise for the reader. :)
NOTE: I've just shown the safe initialization and tear-down of the WMI system, and the basics of getting values from WMI, and getting the MAC Addresses (the question in the OP).
This came from working code, but was modified as I pasted it in here. So it is possible other things got left out that ought to have been included. Oops.
class WmiAccessor
{
public:
WmiAccessor()
: _pWbemLocator(NULL)
, _pWbemServices(NULL)
, _com_initialized(false)
, _com_need_uninitialize(false)
, _svc_initialized(false)
, _loc_initialized(false)
, _all_initialized(false)
, _errors("")
, m_mutex()
{
HRESULT hr;
hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
switch (hr)
{
case S_OK:
// The COM library was initialized successfully on this thread.
_com_initialized = true;
_com_need_uninitialize = true;
break;
case S_FALSE:
// The COM library is already initialized on this thread.
_com_initialized = true;
_com_need_uninitialize = true;
break;
case RPC_E_CHANGED_MODE:
// A previous call to CoInitializeEx specified the concurrency model
// for this thread as multithread apartment (MTA).
// This could also indicate that a change from neutral-threaded apartment to
// single-threaded apartment has occurred.
_com_initialized = true;
_com_need_uninitialize = false;
break;
default:
_com_initialized = false;
_com_need_uninitialize = false;
_errors += "Failed to initialize COM.\r\n";
return;
}
hr = ::CoInitializeSecurity(NULL, -1, NULL, NULL,
0 /*RPC_C_AUTHN_LEVEL_DEFAULT*/,
3 /*RPC_C_IMP_LEVEL_IMPERSONATE*/,
NULL, EOAC_NONE, NULL);
// RPC_E_TOO_LATE == Security must be initialized before!
// It cannot be changed once initialized. I don't care!
if (FAILED(hr) && (hr != RPC_E_TOO_LATE))
{
_errors += "Failed to initialize COM Security.\r\n";
if (_com_need_uninitialize)
{
::CoUninitialize();
_com_need_uninitialize = false;
}
return;
}
hr = _pWbemLocator.CoCreateInstance(CLSID_WbemLocator);
if (FAILED(hr) || (_pWbemLocator == nullptr))
{
_errors += "Failed to initialize WBEM Locator.\r\n";
return;
}
_loc_initialized = true;
hr = _pWbemLocator->ConnectServer(
CComBSTR(L"root\\cimv2"), NULL, NULL, 0, NULL, 0, NULL, &_pWbemServices);
if (FAILED(hr) || (_pWbemServices == nullptr))
{
_errors += "Failed to connect WBEM Locator.\r\n";
_pWbemLocator.Release();
_loc_initialized = false;
return;
}
else
{
_svc_initialized = true;
// Set security Levels on the proxy
hr = CoSetProxyBlanket(_pWbemServices,
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hr))
{
_errors += "Failed to set proxy blanket.\r\n";
return;
}
}
_all_initialized = true;
}
~WmiAccessor()
{
std::unique_lock<std::mutex> slock(m_mutex);
if (_svc_initialized)
{
if (_pWbemServices)
_pWbemServices.Release();
_svc_initialized = false;
}
if (_loc_initialized)
{
if (_pWbemLocator)
_pWbemLocator.Release();
_loc_initialized = false;
}
if (_com_initialized)
{
if (_com_need_uninitialize)
{
::CoUninitialize();
}
_com_initialized = false;
_com_need_uninitialize = false;
}
_all_initialized = false;
}
// public: must lock
std::string get_and_clear_errors()
{
std::string result = "";
std::unique_lock<std::mutex> slock(m_mutex);
std::swap(result, _errors);
return result;
}
// public: must lock
std::string get_string(const std::string& name, const std::string& dflt /*= ""*/)
{
std::unique_lock<std::mutex> slock(m_mutex);
return _all_initialized ? _string(name) : dflt;
}
// public: must lock
uint32_t get_uint32(const std::string& name, uint32_t dflt /*= 0*/)
{
std::unique_lock<std::mutex> slock(m_mutex);
return _all_initialized ? _uint32(name) : dflt;
}
// similarly for other public accessors of basic types.
private:
CComPtr<IWbemLocator> _pWbemLocator;
CComPtr<IWbemServices> _pWbemServices;
volatile bool _com_initialized;
volatile bool _com_need_uninitialize;
volatile bool _svc_initialized;
volatile bool _loc_initialized;
volatile bool _all_initialized;
std::string _errors;
CComVariant _variant(const std::wstring& name);
std::string _string(const std::string& name);
uint32_t _uint32(const std::string& name);
uint16_t _uint16(const std::string& name);
uint8_t _uint8(const std::string& name);
std::vector<std::string> _macAddresses(bool forceReCalculate = false);
// to protect internal objects, public methods need to protect the internals.
//
mutable std::mutex m_mutex;
std::vector<std::string> _macs; // unlikely to change, so save them once found.
// internal: assumes inside a lock
CComVariant _variant(const std::wstring& name)
{
if (!_all_initialized)
return CComVariant();
CComPtr<IEnumWbemClassObject> pEnum;
CComBSTR cbsQuery = std::wstring(L"Select " + name + L" from Win32_OperatingSystem").c_str();
HRESULT hr = _pWbemServices->ExecQuery(
CComBSTR(L"WQL"), cbsQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum);
CComVariant cvtValue;
if (FAILED(hr) || !pEnum)
{
std::wstring wquery(cbsQuery, SysStringLen(cbsQuery));
_errors += "Failed to exec WMI query: '" + convertToUtf8(wquery) + "'\r\n";
return cvtValue;
}
ULONG uObjectCount = 0;
CComPtr<IWbemClassObject> pWmiObject;
hr = pEnum->Next(WBEM_INFINITE, 1, &pWmiObject, &uObjectCount);
if (FAILED(hr) || !pWmiObject)
{
_errors
+= "Failed to get WMI Next result for: '" + convertToUtf8(name) + "'\r\n";
return cvtValue;
}
hr = pWmiObject->Get(name.c_str(), 0, &cvtValue, 0, 0);
if (FAILED(hr))
{
_errors
+= "Failed to get WMI result value for: '" + convertToUtf8(name) + "'\r\n";
}
return cvtValue;
}
// internal: assumes inside a lock
std::string _string(const std::string& name)
{
if (!_all_initialized)
return "";
CComVariant cvtValue = _variant(convertFromUtf8(name).c_str());
std::wstring wValue(cvtValue.bstrVal, SysStringLen(cvtValue.bstrVal));
std::string sValue = convertToUtf8(wValue);
return sValue;
}
// internal: assumes inside a lock
uint32_t _uint32(const std::string& name)
{
if (!_all_initialized)
return 0;
CComVariant cvtValue = _variant(convertFromUtf8(name).c_str());
uint32_t uValue = static_cast<uint32_t>(cvtValue.lVal);
return uValue;
}
// similarly for other internal access of basic types.
// internal: assumes inside a lock
std::vector<std::string> _macAddresses(bool forceReCalculate /*= false*/)
{
if (!_all_initialized)
{
return _macs; // it will still be empty at this point.
}
if (forceReCalculate)
{
_macs.clear();
}
if (_macs.empty())
{
// hr == 0x80041010 == WBEM_E_INVALID_CLASS
// hr == 0x80041017 == WBEM_E_INVALID_QUERY
// hr == 0x80041018 == WBEM_E_INVALID_QUERY_TYPE
CComBSTR cbsQuery = std::wstring(L"Select * from Win32_NetworkAdapter").c_str();
CComPtr<IEnumWbemClassObject> pEnum;
HRESULT hr = _pWbemServices->ExecQuery(
CComBSTR(L"WQL"), cbsQuery, WBEM_RETURN_IMMEDIATELY, NULL, &pEnum);
if (FAILED(hr))
{
_errors += "error: MacAddresses: ExecQuery('"
+ convertToUtf8((LPWSTR)cbsQuery) + "') returned "
+ ToString(hr) + "\r\n";
}
if (SUCCEEDED(hr))
{
ULONG fetched;
VARIANT var;
IWbemClassObject* pclsObj = NULL;
while (pEnum)
{
hr = pEnum->Next(WBEM_INFINITE, 1, &pclsObj, &fetched);
if (0 == fetched)
break;
std::string theMac = "";
VariantInit(&var);
hr = pclsObj->Get(L"MACAddress", 0, &var, 0, 0);
if (SUCCEEDED(hr))
{
switch (var.vt)
{
case VT_NULL: break;
case VT_BSTR:
theMac = (var.bstrVal == NULL)
? ""
: convertToUtf8(var.bstrVal);
break;
case VT_LPSTR:
theMac = (var.bstrVal == NULL)
? ""
: (const char*)var.bstrVal;
break;
case VT_LPWSTR:
theMac = (var.bstrVal == NULL)
? ""
: convertToUtf8((LPWSTR)var.bstrVal);
break;
// _could_ be array of BSTR, LPSTR, LPWSTR; unlikely, but ....
case VT_ARRAY | VT_BSTR:
case VT_ARRAY | VT_LPSTR:
case VT_ARRAY | VT_LPWSTR:
_errors += "warning: MacAddresses: unexpected array of addresses";
_errors += "\r\n";
// yet another exercise for the reader :)
break;
default:
_errors += "error: MacAddresses: unexpected VARIANT.vt = "
+ ToString(var.vt) + "\r\n";
break;
}
// local loopback has an empty address?
if (!theMac.empty())
{
_macs.push_back(theMac);
}
}
VariantClear(&var);
pclsObj->Release();
}
}
}
return _macs;
}
...
}
GetAdaptersInfo() is the official method, it enumerates all adapters even ones that are disconnected.
See this post for example code codeguru
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <vector>
#include <Windows.h>
#include <Iphlpapi.h>
#include <Assert.h>
#include <string>
#pragma comment(lib, "iphlpapi.lib")
char* getdMacAddresses()
{
IP_ADAPTER_INFO AdapterInfo[32]; // Allocate information for up to 32 NICs
DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer
DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo
AdapterInfo, // [out] buffer to receive data
&dwBufLen); // [in] size of receive data buffer
//Exit When Error
if (dwStatus != ERROR_SUCCESS)
return "ERROR";
PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
char szBuffer[512];
while (pAdapterInfo)
{
if (pAdapterInfo->Type == MIB_IF_TYPE_ETHERNET)
{
sprintf_s(szBuffer, sizeof(szBuffer), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x"
, pAdapterInfo->Address[0]
, pAdapterInfo->Address[1]
, pAdapterInfo->Address[2]
, pAdapterInfo->Address[3]
, pAdapterInfo->Address[4]
, pAdapterInfo->Address[5]
);
return szBuffer;
}
pAdapterInfo = pAdapterInfo->Next;
}
return "ERROR";
}
You can use WMI on both XP and Vista, there are a number of examples online. e.g:
Use Windows Management Instrumentation (WMI) to get a MAC Address