Identifying system reserved drive using DeviceIoControl function in C++

大城市里の小女人 提交于 2019-12-13 06:07:31

问题


I am trying to identify if a drive is system reserved drive(PhysicalDrive0 or C-Drive) using DeviceIoControl function. However my code is always returning true for all the drives.

HANDLE hDevice;               // handle to the drive to be examined
BOOL bResult;                 // results flag
DWORD junk;                   // discard results

PARTITION_INFORMATION_MBR *pdg

hDevice = CreateFile(TEXT("\\\\.\\C:"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ |
        FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);


bResult = DeviceIoControl(
            hDevice,                        // device to be queried
            IOCTL_DISK_GET_PARTITION_INFO_EX,  // operation to perform
            NULL, 0,                        // no input buffer
            pdg, sizeof(*pdg),              // output buffer
            &junk,                          // # bytes returned
            (LPOVERLAPPED) NULL             // synchronous I/O
        );  
  • bResult isalways returning 0, indicating that the function succeeded.
  • Even pdg->PartitionType has junk information and not returning true.

回答1:


bResult isalways returning 0, indicating that the function succeeded.

Plain wrong, the documentation states If the operation completes successfully, the return value is nonzero. Many things could be wrong, at least your parameters are not right and GetLastError would have returned ERROR_INSUFFICIENT_BUFFER:


You're giving DeviceIoControl a uninitialized pointer, but it expects that pdg points to a buffer, in this case, with the size of a pointer to PARTITION_INFORMATION_MBR. Dereferencing wild pointers invokes undefined behavior. Also, according to the documentation DeviceIoControl with OCTL_DISK_GET_PARTITION_INFO awaits a PARTITION_INFORMATION_EX structure so


Change

PARTITION_INFORMATION_MBR *pdg(;)

to

PARTITION_INFORMATION_EX pdg;

So you got a structure with automatic storage, for which you can give DeviceIoControl a temporary pointer to it, with the & operator.

bResult = DeviceIoControl(
        hDevice,                        // device to be queried
        IOCTL_DISK_GET_PARTITION_INFO_EX,  // operation to perform
        NULL, 0,                        // no input buffer
        &pdg, sizeof(pdg),              // output buffer
        &junk,                          // # bytes returned
        (LPOVERLAPPED) NULL             // synchronous I/O
    );  


来源:https://stackoverflow.com/questions/12488337/identifying-system-reserved-drive-using-deviceiocontrol-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!