Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinApi: Cant read registry

Tags:

c++

winapi

Im trying to read a registry using the winapi and c++.

The code runs, but the result is not the contents of the registry After a hexdump is just 0xCD repeated over and over. (So, as if the data hasnt been modified by RegQueryValueEx, and is just the result of the malloc) I tried running as admin too, with no luck.

This is the code im using:

HKEY hKey;
if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\Shell\\Bags\\1\\Desktop", 0, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
    return;

//Read & save
DWORD BufferSize = TOTALBYTES;
DWORD cbData;
DWORD dwRet;

LPBYTE data = (LPBYTE)malloc(BufferSize);
cbData = BufferSize;

DWORD type = REG_BINARY;

dwRet = RegQueryValueEx(hKey, "IconLayouts", NULL, &type, data, &cbData);

while (dwRet == ERROR_MORE_DATA) {

    BufferSize += BYTEINCREMENT;
    data = (LPBYTE)realloc(data, BufferSize);
    cbData = BufferSize;

    dwRet = RegQueryValueEx(hKey, "IconLayouts", NULL, &type, data, &cbData);
}

if (dwRet == ERROR_SUCCESS)
{
    //Write current registry to a file
    std::ofstream currentRegistryFile(DIRECTORY + currentDesktop + ".bin");
    if (!currentRegistryFile) {
        log(currentDesktop + " file couldn't be opened.");
        return;
    }
    for (int i = 0; i < cbData; i++)
        currentRegistryFile << (data)[cbData];
}
else
    log("Couldnt read registry");


//Close registry
RegCloseKey(hKey);
like image 265
Nicolas de Pineda Gutiérrez Avatar asked Mar 31 '26 21:03

Nicolas de Pineda Gutiérrez


1 Answers

Your saving code is the problem. It’s actually accessing the array out of bounds:

for (int i = 0; i < cbData; i++)
    currentRegistryFile << (data)[cbData];

Note you’re indexing data with constant value of cbData and not loop variable i. Change that.

like image 103
Sami Kuhmonen Avatar answered Apr 02 '26 11:04

Sami Kuhmonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!