Enumerating all subkeys and values in a Windows registry key

19,156

Solution 1

Enumerating the keys this way is overkill. This would simply waste the system resources, memory, call-stack and put pressure on registry sub-system. Do not do unless needed.

Are you going to have "search registry" in your application? If yes, enumerate only when user demands so. Or, if you are developing "Registry Viewer/Editor", do expand and open sub-keys only when needed.

If you absolutely need to retrieve and store all keys/values, you can use multiple threads to enumerate the keys. The number of threads would initially be the HKEY-major-keys, and then you can have more threads, depending on number of sub keys and runtime heuristics you perform while enumerating the keys.

Recursion may or may not be good approach for "recursive-enumeration" of sub-keys - you must keep number of arguments to recursive implementation minimum - put the arguments into one struct or put them in class. You may also like to use std::stack for the same.

Solution 2

It appears that you are calling RegEnumValue() without setting the lpcchValueName parameter to a proper value. This parameter is an [in] parameter as well as an [out] parameter. Try this:

for (int i = 0; i < numValues; i++)
 {
  DWORD valNameLen = 64; //added this line to match valueName buffer size
  RegEnumValue(hKey,
     dwIndex,
     valueName,
     &valNameLen,
     NULL,
     &dataType,
     (BYTE*)&data,
     &dataSize);

Documentation for RegEnumValue() : http://msdn.microsoft.com/en-us/library/ms724865(v=vs.85).aspx

Solution 3

I tried your code on a key with a very small number of subkeys.

In the function EnumerateValues after calling RegEnumValue once, the value of numValues is getting filled with some random junk. The solution is to change the parameters of RegEnumValue to

    RegEnumValueA(hKey,
               dwIndex,
               valueName,
               &valNameLen,
               nullptr,
               nullptr,
               nullptr,
               nullptr);

This is the function finally,

void EnumerateValues(HKEY hKey, DWORD numValues)
{
    DWORD dwIndex = 0;
    LPSTR valueName = new CHAR[64];
    DWORD valNameLen;

    DWORD numback = numValues;

    for (int i = 0; i < numValues; i++)
    {
        // printf("%lu, %d\n", numValues, i);
        RegEnumValueA(hKey,
                      dwIndex,
                      valueName,
                      &valNameLen,
                      nullptr,
                      nullptr,
                      nullptr,
                      nullptr);

        dwIndex++;

        if (i > numback)
        {
            RegCloseKey(hKey);
            printf("Inf loop exiting...\n");
            exit(-1);
        }

        // printf("Code: 0x%08X, %lu, %d\n", data, numValues, i);
        // printf("Code: %lu, %d\n", numValues, i);
    }
    RegCloseKey(hKey);
}
Share:
19,156
8bitcartridge
Author by

8bitcartridge

Updated on June 04, 2022

Comments

  • 8bitcartridge
    8bitcartridge about 2 years

    I am trying to write a Windows application that gives me back all the subkeys and values given a certain key. I've written code that appears to work as far as providing subkeys within the given key, but doesn't work at properly enumerating the values; it successfully enumerates subkeys without values and returns the results in kind of tabbed tree arrangement. However, when enumerating values, the program gives back a random value for each value present (the same random value each time), and then crashes afterwards with a debug error.

    It's intended output is basically:

    (1) KEY
        (1) SUBKEY
        (1) SUBKEYWITHINSUBKEY
            Code: value1data
            Code: value2data
            Code: value3data
    (2) SUBKEY
        (1) SUBKEYWITHINSUBKEY
    (3) SUBKEY
    

    ...and so on.

    The output I get instead is something like:

    (1) KEY
    (1) SUBKEY
        (1) SUBKEYWITHINSUBKEY
            Code: someValue
            Code: someValue
            Code: someValue
    

    (...and then the crash)

    This is followed with the following error:
    "Debug Error! "Run-Time Check Failure #2 - Stack around the variable 'valNameLen' was corrupted."

    The code is a bit messy currently (I'm a Windows API newbie), but if anyone could show me what I'm doing wrong, or critique my coding style in anyway they feel fit, that would be great.

    Thanks!

    -R

    /*
    Windows Registry Subkey Enumeration Example
    Based on example found at code-blue.org
    */
    
    #include <windows.h>
    #include <stdio.h>
    
    void EnumerateValues(HKEY hKey, DWORD numValues)
    {
     DWORD dwIndex = 0;
        LPSTR valueName = new CHAR[64];
     DWORD valNameLen;
     DWORD dataType;
     DWORD data;
     DWORD dataSize;
    
        for (int i = 0; i < numValues; i++)
     {
      RegEnumValue(hKey,
         dwIndex,
         valueName,
         &valNameLen,
         NULL,
         &dataType,
         (BYTE*)&data,
         &dataSize);
    
      dwIndex++;
    
            printf("Code: 0x%08X\n", data);
     }
    }
    
    
    void EnumerateSubKeys(HKEY RootKey, char* subKey, unsigned int tabs = 0) 
    {
     HKEY hKey;
        DWORD cSubKeys;        //Used to store the number of Subkeys
        DWORD maxSubkeyLen;    //Longest Subkey name length
        DWORD cValues;        //Used to store the number of Subkeys
        DWORD maxValueLen;    //Longest Subkey name length
        DWORD retCode;        //Return values of calls
    
     RegOpenKeyEx(RootKey, subKey, 0, KEY_ALL_ACCESS, &hKey);
    
        RegQueryInfoKey(hKey,            // key handle
                        NULL,            // buffer for class name
                        NULL,            // size of class string
                        NULL,            // reserved
                        &cSubKeys,        // number of subkeys
                        &maxSubkeyLen,    // longest subkey length
                        NULL,            // longest class string 
                        &cValues,        // number of values for this key 
                        &maxValueLen,    // longest value name 
                        NULL,            // longest value data 
                        NULL,            // security descriptor 
                        NULL);            // last write time
    
        if(cSubKeys>0)
     {
            char currentSubkey[MAX_PATH];
    
            for(int i=0;i < cSubKeys;i++){
       DWORD currentSubLen=MAX_PATH;
    
                retCode=RegEnumKeyEx(hKey,    // Handle to an open/predefined key
                i,                // Index of the subkey to retrieve.
                currentSubkey,            // buffer to receives the name of the subkey
                &currentSubLen,            // size of that buffer
                NULL,                // Reserved
                NULL,                // buffer for class string 
                NULL,                // size of that buffer
                NULL);                // last write time
    
                if(retCode==ERROR_SUCCESS)
       {
                    for (int i = 0; i < tabs; i++)
                        printf("\t");
                    printf("(%d) %s\n", i+1, currentSubkey);
    
                    char* subKeyPath = new char[currentSubLen + strlen(subKey)];
                    sprintf(subKeyPath, "%s\\%s", subKey, currentSubkey);
        EnumerateSubKeys(RootKey, subKeyPath, (tabs + 1));
       }
      }
     }
        else
     {
      EnumerateValues(hKey, cValues);
     }
    
     RegCloseKey(hKey); 
    }
    
    
    int main()
    {
        EnumerateSubKeys(HKEY_CURRENT_USER,"SOFTWARE\\MyKeyToSearchIn");
        return 0;
    }
    
    • Phani Rithvij
      Phani Rithvij over 4 years
      Were you able to figure it out? Can you share your code please.
    • 8bitcartridge
      8bitcartridge over 4 years
      I'm sorry, I believe I did figure it out, but it was a very long time ago :(
  • 8bitcartridge
    8bitcartridge almost 13 years
    I rewrote the code from scratch and it does everything I need it to. The algorithm should be okay I think- the whole point of the utility is to get this information and some other stuff and the keys I search are specific and don't contain all that much subkeys or values. Thank you for the pointers!
  • Phani Rithvij
    Phani Rithvij over 4 years
    I wasn't able to find the source of what's causing the numValues to become junk
  • Brain2000
    Brain2000 over 4 years
    Wow, going back a number of years. I see that I'm missing something, namely filling data and setting valNameLen. I believe Ajay it correct got above. I must have been drunk when I wrote this, and may delete my answer...