启用存储空间后,获取有关物理磁盘的信息

时间:2018-09-03 09:09:15

标签: windows winapi hard-drive

启用Windows 10存储空间后,我需要获取系统中所有物理磁盘的以下信息。

  • 模型
  • 序列号
  • 固件版本
  • 容量
  • 磁盘索引
  • 磁盘的Pnp ID(以使用CM_Get_Parent获取SCSI控制器名称)
  • 位置信息(总线号,目标ID和LUN)

到目前为止,我已经尝试过:

  1. 使用的WMI类MSFT_PhysicalDisk 尽管此类为我提供了适配器号(因此我可以不使用磁盘PNP),但是当磁盘连接到其他PCI存储控制器(例如Marvell 92xx SATA 6g控制器)时,它给出的位置信息并不完整。 / p>

  2. SetupDiGetClassDevsGUID_DEVINTERFACE_DISK一起使用,将句柄传递给SetupDiGetDeviceInterface,并将SetupDiGetDeviceInterfaceDetail用于位置信息(总线/目标ID / LUN),PNP ID,和设备路径。我可以将设备路径传递到CreateFile并获取其余信息(类似于this方法)。问题是它不能给我所有的物理磁盘。存储空间池下的磁盘被省略。

  3. 使用与第二种方法类似的方法,但使用SetupDiEnumDeviceInfoCM_Get_DevNode_Registry_Property(使用here中的磁盘驱动器)代替SetupDiGetDeviceInterface和SetupDiGetDeviceInterfaceDetail。尽管这为我提供了所有物理磁盘的位置和PNP ID,但我无法在此处使用任何(我知道的)调用CreateFile来获取其余详细信息。

启用存储空间后,如何获得每个物理磁盘的上述详细信息?

作为一个旁注,如果有一种方法可以使用CreateFile和DeviceIoControl从磁盘索引中获取磁盘PNP ID,那对我也很有帮助。

1 个答案:

答案 0 :(得分:1)

首先,我们需要使用CM_Get_Device_Interface_ListW调用CM_Get_Device_Interface_List_SizeWGUID_DEVINTERFACE_DISK来枚举系统中的所有磁盘

#include <Shlwapi.h>
#include <cfgmgr32.h>
#undef _NTDDSTOR_H_
#include <ntddstor.h>
#include <ntdddisk.h>

static volatile UCHAR guz;

CONFIGRET EnumDisks(PCSTR prefix, PGUID InterfaceClassGuid)
{
    CONFIGRET err;

    PVOID stack = alloca(guz);
    ULONG BufferLen = 0, NeedLen = 256;

    union {
        PVOID buf;
        PWSTR pszDeviceInterface;
    };

    for(;;) 
    {
        if (BufferLen < NeedLen)
        {
            BufferLen = RtlPointerToOffset(buf = alloca((NeedLen - BufferLen) * sizeof(WCHAR)), stack) / sizeof(WCHAR);
        }

        switch (err = CM_Get_Device_Interface_ListW(InterfaceClassGuid, 
            0, pszDeviceInterface, BufferLen, CM_GET_DEVICE_INTERFACE_LIST_PRESENT))
        {
        case CR_BUFFER_SMALL:
            if (err = CM_Get_Device_Interface_List_SizeW(&NeedLen, InterfaceClassGuid, 
                0, CM_GET_DEVICE_INTERFACE_LIST_PRESENT))
            {
        default:
            return err;
            }
            continue;

        case CR_SUCCESS:

            while (*pszDeviceInterface)
            {
                DbgPrint("Interface=[%S]\n", pszDeviceInterface);

                HANDLE hFile = CreateFileW(pszDeviceInterface, FILE_GENERIC_READ, 
                    FILE_SHARE_VALID_FLAGS, 0, OPEN_EXISTING, 0, 0);

                if (hFile != INVALID_HANDLE_VALUE)
                {
                    GetDiskPropertyByHandle(hFile);
                    CloseHandle(hFile);
                }

                GetPropertyByInterface(prefix, pszDeviceInterface);

                pszDeviceInterface += 1 + wcslen(pszDeviceInterface);
            }

            return CR_SUCCESS;
        }
    }
}

CONFIGRET EnumDisks()
{
    char prefix[256];
    memset(prefix, '\t', sizeof(prefix));
    prefix[sizeof(prefix) - 1] = 0;
    prefix[0] = 0;
    return EnumDisks(prefix + sizeof(prefix) - 1, const_cast<PGUID>(&GUID_DEVINTERFACE_DISK));
}

CM_Get_Device_Interface_ListW返回多个以NULL终止的Unicode字符串,每个字符串代表接口实例的符号链接名称。

可以从一侧将此符号链接名称传递给CreateFileW,以用于打开磁盘设备。之后,我们可以在磁盘上设置一些ioctl-获取

  • 磁盘索引
  • 容量
  • 序列号
  • 分区信息

示例:

void GetDiskPropertyByHandle(HANDLE hDisk)
{
    HANDLE hPartition;
    IO_STATUS_BLOCK iosb;
    STORAGE_DEVICE_NUMBER sdn;
    GET_LENGTH_INFORMATION li;

    NTSTATUS status = NtDeviceIoControlFile(hDisk, 0, 0, 0, &iosb,
        IOCTL_STORAGE_GET_DEVICE_NUMBER, 0, 0, &sdn, sizeof(sdn));

    if (0 <= status && sdn.DeviceType == FILE_DEVICE_DISK && !sdn.PartitionNumber)
    {
        DbgPrint("\\Device\\Harddisk%d\n", sdn.DeviceNumber);

        WCHAR sz[64], *c = sz + swprintf(sz, L"\\Device\\Harddisk%d\\Partition", sdn.DeviceNumber);

        WCHAR szSize[32];

        if (0 <= (status = NtDeviceIoControlFile(hDisk, 0, 0, 0, &iosb,
            IOCTL_DISK_GET_LENGTH_INFO, 0, 0, &li, sizeof(li))))
        {
            DbgPrint("Length = %S (%I64x)\n", 
                StrFormatByteSizeW(li.Length.QuadPart, szSize, RTL_NUMBER_OF(szSize)), 
                li.Length.QuadPart);
        }

        UNICODE_STRING ObjectName;
        OBJECT_ATTRIBUTES oa = { sizeof(oa), 0, &ObjectName, OBJ_CASE_INSENSITIVE };

        PVOID stack = alloca(guz);

        union {
            PVOID buf;
            PDRIVE_LAYOUT_INFORMATION_EX pdli;
            PSTORAGE_DEVICE_DESCRIPTOR psdd;
            PCSTR psz;
        };

        STORAGE_PROPERTY_QUERY spq = { StorageDeviceProperty, PropertyStandardQuery }; 

        ULONG cb = 0, rcb = sizeof(STORAGE_DEVICE_DESCRIPTOR) + 0x40, PartitionCount = 4;

        do 
        {
            if (cb < rcb)
            {
                cb = RtlPointerToOffset(buf = alloca(rcb - cb), stack);
            }

            switch (status = (NtDeviceIoControlFile(hDisk, 0, 0, 0, &iosb, 
                IOCTL_STORAGE_QUERY_PROPERTY, &spq, sizeof(spq), buf, cb)))
            {
            case STATUS_SUCCESS:
            case STATUS_BUFFER_OVERFLOW:
                if (psdd->Version == sizeof(STORAGE_DEVICE_DESCRIPTOR))
                {
                    if (psdd->Size > cb)
                    {
                        rcb = psdd->Size;
                        status = STATUS_BUFFER_OVERFLOW;
                    }
                    else
                    {
                        if (psdd->SerialNumberOffset)
                        {
                            DbgPrint("SerialNumber = %s\n", psz + psdd->SerialNumberOffset);
                        }
                    }
                }
                else
                {
                    status = STATUS_INVALID_PARAMETER;
                }
                break;
            }
        } while (status == STATUS_BUFFER_OVERFLOW);

        for (;;)
        {
            if (cb < (rcb = FIELD_OFFSET(DRIVE_LAYOUT_INFORMATION_EX, PartitionEntry[PartitionCount])))
            {
                cb = RtlPointerToOffset(buf = alloca(rcb - cb), stack);
            }

            if (0 <= (status = NtDeviceIoControlFile(hDisk, 0, 0, 0, &iosb,
                IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, 0, buf, cb)))
            {
                if (PartitionCount = pdli->PartitionCount)
                {
                    PPARTITION_INFORMATION_EX PartitionEntry = pdli->PartitionEntry;

                    do 
                    {
                        if (!PartitionEntry->PartitionNumber)
                        {
                            continue;
                        }

                        _itow(PartitionEntry->PartitionNumber, c, 10);

                        RtlInitUnicodeString(&ObjectName, sz);

                        DbgPrint("%wZ\nOffset=%S ", &ObjectName, 
                            StrFormatByteSizeW(PartitionEntry->StartingOffset.QuadPart, szSize, RTL_NUMBER_OF(szSize)));

                        DbgPrint("Length=%S\n", 
                            StrFormatByteSizeW(PartitionEntry->PartitionLength.QuadPart, szSize, RTL_NUMBER_OF(szSize)));

                        char PartitionName[256], *szPartitionName;

                        switch (PartitionEntry->PartitionStyle)
                        {
                        case PARTITION_STYLE_MBR:
                            DbgPrint("MBR: type=%x boot=%x", PartitionEntry->Mbr.PartitionType, PartitionEntry->Mbr.BootIndicator);
                            break;
                        case PARTITION_STYLE_GPT:

                            if (IsEqualGUID(PartitionEntry->Gpt.PartitionType, PARTITION_ENTRY_UNUSED_GUID))
                            {
                                szPartitionName = "UNUSED";
                            }
                            else if (IsEqualGUID(PartitionEntry->Gpt.PartitionType, PARTITION_SYSTEM_GUID))
                            {
                                szPartitionName = "SYSTEM";
                            }
                            else if (IsEqualGUID(PartitionEntry->Gpt.PartitionType, PARTITION_MSFT_RESERVED_GUID))
                            {
                                szPartitionName = "RESERVED";
                            }
                            else if (IsEqualGUID(PartitionEntry->Gpt.PartitionType, PARTITION_BASIC_DATA_GUID))
                            {
                                szPartitionName = "DATA";
                            }
                            else if (IsEqualGUID(PartitionEntry->Gpt.PartitionType, PARTITION_MSFT_RECOVERY_GUID))
                            {
                                szPartitionName = "RECOVERY";
                            }
                            else if (IsEqualGUID(PartitionEntry->Gpt.PartitionType, PARTITION_MSFT_SNAPSHOT_GUID))
                            {
                                szPartitionName = "SNAPSHOT";
                            }
                            else
                            {
                                sprintf(szPartitionName = PartitionName, "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", 
                                    PartitionEntry->Gpt.PartitionType.Data1,
                                    PartitionEntry->Gpt.PartitionType.Data2,
                                    PartitionEntry->Gpt.PartitionType.Data3,
                                    PartitionEntry->Gpt.PartitionType.Data4[0],
                                    PartitionEntry->Gpt.PartitionType.Data4[1],
                                    PartitionEntry->Gpt.PartitionType.Data4[2],
                                    PartitionEntry->Gpt.PartitionType.Data4[3],
                                    PartitionEntry->Gpt.PartitionType.Data4[4],
                                    PartitionEntry->Gpt.PartitionType.Data4[5],
                                    PartitionEntry->Gpt.PartitionType.Data4[6],
                                    PartitionEntry->Gpt.PartitionType.Data4[7]);
                            }
                            DbgPrint("[%s] %I64x \"%S\"", 
                                szPartitionName,
                                PartitionEntry->Gpt.Attributes,
                                PartitionEntry->Gpt.Name);
                            break;
                        }

                        if (0 <= NtOpenFile(&hPartition, FILE_GENERIC_READ, &oa, &iosb,
                            FILE_SHARE_VALID_FLAGS, FILE_SYNCHRONOUS_IO_NONALERT))
                        {
                            union {
                                BYTE bb[sizeof(FILE_FS_ATTRIBUTE_INFORMATION) + 32*sizeof(WCHAR) ];
                                FILE_FS_ATTRIBUTE_INFORMATION ffai;
                            };

                            switch (NtQueryVolumeInformationFile(hPartition, &iosb, &ffai, sizeof(bb), FileFsAttributeInformation))
                            {
                            case STATUS_SUCCESS:
                            case STATUS_BUFFER_OVERFLOW:
                                DbgPrint(" \"%.*S\"\n", ffai.FileSystemNameLength >> 1 , ffai.FileSystemName);
                                break;
                            }

                            NtClose(hPartition);
                        }

                    } while (PartitionEntry++, --PartitionCount);
                }
                return ;
            }

            switch (status)
            {
            case STATUS_BUFFER_OVERFLOW:
                PartitionCount = pdli->PartitionCount;
                continue;
            case STATUS_INFO_LENGTH_MISMATCH:
            case STATUS_BUFFER_TOO_SMALL:
                PartitionCount <<= 1;
                continue;
            default:
                return ;
            }
        }
    }
}

通过另一种大小,我们可以通过用Device Instance ID调用CM_Get_Device_Interface_PropertyW从接口字符串中获取DEVPKEY_Device_InstanceId。之后,我们调用CM_Locate_DevNodeW获取设备实例句柄。

CONFIGRET GetPropertyByInterface(PCSTR prefix, PCWSTR pszDeviceInterface)
{
    ULONG cb = 0, rcb = 256;

    PVOID stack = alloca(guz);
    DEVPROPTYPE PropertyType;

    CONFIGRET status;

    union {
        PVOID pv;
        PWSTR DeviceID;
        PBYTE pb;
    };

    do 
    {
        if (cb < rcb)
        {
            rcb = cb = RtlPointerToOffset(pv = alloca(rcb - cb), stack);
        }

        status = CM_Get_Device_Interface_PropertyW(pszDeviceInterface, &DEVPKEY_Device_InstanceId, &PropertyType, pb, &rcb, 0);

        if (status == CR_SUCCESS)
        {
            if (PropertyType == DEVPROP_TYPE_STRING)
            {
                DbgPrint("%sDeviceID = %S\n", prefix, DeviceID);

                DEVINST dnDevInst; 

                if (CR_SUCCESS == (status = CM_Locate_DevNodeW(&dnDevInst, DeviceID, CM_LOCATE_DEVNODE_NORMAL)))
                {
                    GetPropertyByDeviceID(prefix, dnDevInst);
                }
            }
            else
            {
                status = CR_WRONG_TYPE;
            }

            break;
        }

    } while (status == CR_BUFFER_SMALL);

    return status;
}

使用设备实例句柄,我们可以通过CM_Get_DevNode_PropertyW查询许多设备属性,例如: DEVPKEY_Device_LocationInfoDEVPKEY_NAMEDEVPKEY_Device_PDONameDEVPKEY_Device_FirmwareVersionDEVPKEY_Device_ModelDEVPKEY_Device_DriverVersion等-在 devpkey.h <中查找完整列表/ em>

最后,我们可以调用CM_Get_Parent并递归查询父设备的所有这些属性,直到我们没有丰富堆栈顶部为止:

#define OPEN_PDO

void GetPropertyByDeviceID(PCSTR prefix, DEVINST dnDevInst)
{
#ifdef OPEN_PDO
    HANDLE hFile;
    IO_STATUS_BLOCK iosb;
    UNICODE_STRING ObjectName;
    OBJECT_ATTRIBUTES oa = { sizeof(oa), 0, &ObjectName, OBJ_CASE_INSENSITIVE };
#endif

    CONFIGRET status;

    ULONG cb = 0, rcb = 0x80;

    PVOID stack = alloca(guz);

    DEVPROPTYPE PropertyType;

    union {
        PVOID pv;
        PWSTR sz;
        PBYTE pb;
    };

    static struct  
    {
        CONST DEVPROPKEY *PropertyKey;
        PCWSTR PropertyName;
    } PropertyKeys[] = {
        { &DEVPKEY_Device_PDOName, L"PDOName"},
        { &DEVPKEY_Device_Parent, L"Parent"},
        { &DEVPKEY_Device_DriverVersion, L"DriverVersion"},
        { &DEVPKEY_Device_LocationInfo, L"LocationInfo"},
        { &DEVPKEY_Device_FirmwareVersion, L"FirmwareVersion"},
        { &DEVPKEY_Device_Model, L"Model"},
        { &DEVPKEY_NAME, L"NAME"},
        { &DEVPKEY_Device_InstanceId, L"DeviceID"}
    };

    do 
    {
        int n = RTL_NUMBER_OF(PropertyKeys);

        do 
        {
            CONST DEVPROPKEY *PropertyKey = PropertyKeys[--n].PropertyKey;

            do 
            {
                if (cb < rcb)
                {
                    rcb = cb = RtlPointerToOffset(pv = alloca(rcb - cb), stack);
                }

                status = CM_Get_DevNode_PropertyW(dnDevInst, PropertyKey, &PropertyType, pb, &rcb, 0);

                if (status == CR_SUCCESS)
                {
                    if (PropertyType == DEVPROP_TYPE_STRING)
                    {
                        DbgPrint("%s%S=[%S]\n", prefix, PropertyKeys[n].PropertyName, sz);

#ifdef OPEN_PDO

                        if (!n)
                        {
                            // DEVPKEY_Device_PDOName can use in NtOpenFile

                            RtlInitUnicodeString(&ObjectName, sz);

                            if (0 <= NtOpenFile(&hFile, FILE_READ_ATTRIBUTES|SYNCHRONIZE, &oa,
                                &iosb, FILE_SHARE_VALID_FLAGS, FILE_SYNCHRONOUS_IO_NONALERT))
                            {
                                NtClose(hFile);
                            }
                        }
#endif
                    }
                }

            } while (status == CR_BUFFER_SMALL);

        } while (n);

        if (!*--prefix) break;

    } while (CM_Get_Parent(&dnDevInst, dnDevInst, 0) == CR_SUCCESS);
}

也是DEVPKEY_Device_PDOName返回的字符串,我们可以在NtOpenFile调用中使用此字符串来打开PDO设备。