Skip to main content

HDD enumeration and info retreive - another way

In this part I tried to enumerate all physical hard disk drive (HDD) attached to the system and tried to query to those attached physical drive to get the disk information like Vendor ID, Product ID, Product Revision, Serial number etc.

In my last blog, I've tried to get physical hard disk drive count through volume map, but in this post, I tried get it through "SetupDiGetClassDevs" API. All the SetupDiXXX APIs are very powerful APIs. These APIs along with DeviceIoControl API helps to retrieve very useful information regarding devices. So, I'm not going to talk much on this rather let MSDN to speak about this APIs.

Let's see what are other information that we can get on HDD attached to the system through the usage of this API:

void printStorageDeviceProperty(UCHAR *outBuf, const DWORD returnedLength)
{
    PSTORAGE_DEVICE_DESCRIPTOR            devDesc;
    PUCHAR                              pUbuffer;

    devDesc = (PSTORAGE_DEVICE_DESCRIPTOR) outBuf;
           
    pUbuffer = (PUCHAR) outBuf;
    if ( devDesc->VendorIdOffset && pUbuffer[devDesc->VendorIdOffset] )
    {
        wprintf(L"Vendor ID       : " );
        for ( DWORD i = devDesc->VendorIdOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }

    if ( devDesc->ProductIdOffset && pUbuffer[devDesc->ProductIdOffset] )
    {
        wprintf(L"Product ID       : " );
        for ( DWORD i = devDesc->ProductIdOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }

    if ( devDesc->ProductRevisionOffset && pUbuffer[devDesc->ProductRevisionOffset] )
    {
        wprintf(L"Product Revision       : " );
        for ( DWORD i = devDesc->ProductRevisionOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }

    if ( devDesc->SerialNumberOffset && pUbuffer[devDesc->SerialNumberOffset] )
    {
        wprintf(L"Serial Number       : " );
        for ( DWORD i = devDesc->SerialNumberOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }
   
    wprintf(L"Removable Media : %s\n", ((devDesc->RemovableMedia) ? L"Yes..." : L"No..."));
}

void printMediaType(HANDLE hDevice)
{
    PGET_MEDIA_TYPES MediaTypes = {0};
    BOOL    status = FALSE;
    UCHAR   buffer[2048];
    ULONG    returnedLength;

    status = DeviceIoControl(hDevice, IOCTL_STORAGE_GET_MEDIA_TYPES_EX, NULL, 0, buffer, sizeof(buffer), &returnedLength, FALSE);

    if (!status)
    {
        wprintf(L"IOCTL_STORAGE_GET_MEDIA_TYPES_EX failed with error code%d.\n\n", GetLastError());
        return;
    }

    MediaTypes = (PGET_MEDIA_TYPES) buffer;
    switch(MediaTypes->DeviceType)
    {
        case FILE_DEVICE_DISK:
            wprintf(L"Media Type: Device Disk\n");
            break;
        case FILE_DEVICE_DISK_FILE_SYSTEM:
            wprintf(L"Media Type: Device Disk File System\n");
            break;
        case FILE_DEVICE_FILE_SYSTEM:
            wprintf(L"Media Type: File Device File System\n");
            break;
        default:
            wprintf(L"Media Type: Unknown");
            break;
    }

    // Device Media Info
    for (DWORD i = 0; i < MediaTypes->MediaInfoCount; i++)
    {
        wprintf(L"Bytes/Sector:        %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.BytesPerSector);
        wprintf(L"No. of Cylinders: %I64d\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.Cylinders);
        // wprintf(L"Media Characteristics: %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.MediaCharacteristics);
        switch(MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.MediaType)
        {
        case FixedMedia:
            wprintf(L"Media Type:    FixedMedia\n");
            break;
        default:
            wprintf(L"Media Type:    Unknown...\n");
            break;
        }
        wprintf(L"No. of sides:        %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.NumberMediaSides);
        wprintf(L"Sectors/track:    %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.SectorsPerTrack);
        wprintf(L"Tracks/Cylinder:    %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.TracksPerCylinder);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    HDEVINFO hDevInfo;
    SP_DEVINFO_DATA DeviceInfoData;
    DWORD i;

    // Create a HDEVINFO with all HDD present in system.
    hDevInfo = SetupDiGetClassDevs((LPGUID)&GUID_DEVINTERFACE_DISK,
       0, // Enumerator
       0, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE );

    if (hDevInfo == INVALID_HANDLE_VALUE)
    {
       return 1;
    }
   
    // Enumerate through all physical drive in Set.
    DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    for(i=0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++)
    {
        LPTSTR buffer = NULL;
        DWORD buffersize = 0;

        SP_DEVICE_INTERFACE_DATA                interfaceData;
        PSP_DEVICE_INTERFACE_DETAIL_DATA        interfaceDetailData = NULL;
        HANDLE                                    hDevice;
        BOOL                                    status;
        DWORD                                    interfaceDetailDataSize;
        DWORD                                    reqBufSize;
        DWORD                                    errorCode;

        interfaceData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA);

        status = SetupDiEnumDeviceInterfaces (
            hDevInfo,                    // Interface Device Info handle
            0,                            // Device Info data
            (LPGUID)&DiskClassGuid,        // Interface registered by driver
            i,                            // Member
            &interfaceData                // Device Interface Data
        );

        status = SetupDiGetDeviceInterfaceDetail(hDevInfo, &interfaceData, NULL, 0, &reqBufSize, NULL);
        if(status == FALSE)
        {
            errorCode = GetLastError();
            if(errorCode != ERROR_INSUFFICIENT_BUFFER)
            {
                wprintf( L"SetupDiGetDeviceInterfaceDetail failed with error: %d\n", errorCode   );
                return FALSE;
            }
        }

        interfaceDetailDataSize = reqBufSize;
        interfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, reqBufSize);

        interfaceDetailData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);

        status = SetupDiGetDeviceInterfaceDetail(hDevInfo, &interfaceData, interfaceDetailData,
            interfaceDetailDataSize, &reqBufSize, NULL);

        if ( status == FALSE )
        {
            wprintf(L"Error in SetupDiGetDeviceInterfaceDetail failed with error: %d\n", GetLastError());
            return FALSE;
        }

        wprintf( L"Interface: %s\n", interfaceDetailData->DevicePath);

        hDevice = CreateFile(
                interfaceDetailData->DevicePath,    // device interface name
                GENERIC_READ | GENERIC_WRITE,       // dwDesiredAccess
                FILE_SHARE_READ | FILE_SHARE_WRITE, // dwShareMode
                NULL,                               // lpSecurityAttributes
                OPEN_EXISTING,                      // dwCreationDistribution
                0,                                  // dwFlagsAndAttributes
                NULL                                // hTemplateFile
                );

        if (interfaceDetailData)
            LocalFree(interfaceDetailData);

        if (hDevice == INVALID_HANDLE_VALUE)
        {
            wprintf(L"CreateFile failed with error: %d\n", GetLastError());
            return TRUE;
        }

        STORAGE_PROPERTY_QUERY                query;
        UCHAR                                outBuf[512];
        DWORD                                returnedLength;

       query.PropertyId = StorageDeviceProperty;
       query.QueryType = PropertyStandardQuery;
      
       status = DeviceIoControl( hDevice,               
                        IOCTL_STORAGE_QUERY_PROPERTY,
                        &query, sizeof( STORAGE_PROPERTY_QUERY ),
                        &outBuf, 512, &returnedLength, NULL
                        );

        if ( !status )
        {
            wprintf(L"IOCTL failed with error code: %d.\n\n", GetLastError() );
        }
        else
        {
            printStorageDeviceProperty(outBuf, returnedLength);
            printMediaType(hDevice);

            wprintf(L"\n\n");
        }

        if ( !CloseHandle(hDevice) )    
        {
            wprintf( L"Failed to close device.\n");
        }
    }    // End of for loop...

    if ( GetLastError() != NO_ERROR && GetLastError() != ERROR_NO_MORE_ITEMS )
    {
       return 1;
    }

    //  Cleanup
    SetupDiDestroyDeviceInfoList(hDevInfo);

    return 0;
}


The output looks like below:




Comments

Popular posts from this blog

XOR (Exclusive OR) for branchless coding

The following example shows the array reversing using the  XOR operator . No need to take any additional variable to reverse the array.   int main(int argc, _TCHAR* argv[]) { char str[] = "I AM STUDENT"; int length = strlen(str); for(int i = 0; i < ((length/2)); i++) { str[i] ^= str[length - (1+i)]; str[length - (1+i)] ^= str[i]; str[i] ^= str[length - (1+i)]; } cout << str << endl; return 0; } The above example is one of the uses of XOR but XOR comes in handy when we can do branchless coding  methods like butterfly switch etc. Sometimes this is very effective in speeding up the execution.  Let's see one of the uses of XOR in branchless coding. I am taking a simple example of Y = | X |.  Yes, I am generating abs of a supplied number. So, my function signature/definition in C++ looks like below: int absoluteBranch( int x) {     if (x < 0 ) {         return ...

Reversing char array without splitting the array to tokens

 I was reading about strdup, a C++ function and suddenly an idea came to my mind if this can be leveraged to aid in reversing a character array without splitting the array into words and reconstructing it again by placing spaces and removing trailing spaces. Again, I wanted an array to be passed as a function argument and an array size to be passed implicitly with the array to the function. Assumed, a well-formed char array has been passed into the function. No malformed array checking is done inside the function. So, the function signature and definition are like below: Below is the call from the client code to reverse the array without splitting tokens and reconstructing it. Finally, copy the reversed array to the destination.  For GNU C++, we should use strdup instead _strdup . On run, we get the following output: Demo code

Power of Two

  I n this post will be discussing how to calculate if a number is a power of two or not. As an example, 8 is a power of two but the number 10 is not. There are many ways we can solve this. First , we will take an approach which is simple and iterative. In this case, we will calculate the power of two one by one and check with the supplied number. The below code illustrates it. bool isPowerofTwo(unsigned num) { auto y = 1; while (0 != y) { if (num == y) return true; if (num < y) return false; y <<= 1; } return false; } Second , assuming, the number is a 32-bit number, this is also an iterative solution. In this scenario, iterating all bits and counting the set bits. Any number which is a power of 2 will have only one bit set and the rest will be zeros. As an example, 8 in binary representation is 1000. Using this observation, we can implement an iterative solution. bool isPowerofTwo(unsigned num) { auto one_count = 0; for (auto index = 0; index < ...