• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/files/drive_info.h"
6 
7 #include <windows.h>
8 
9 #include <winioctl.h>
10 
11 #include "base/files/file.h"
12 #include "base/files/file_path.h"
13 
14 namespace base {
15 
GetFileDriveInfo(const FilePath & path)16 std::optional<DriveInfo> GetFileDriveInfo(const FilePath& path) {
17   std::vector<FilePath::StringType> components = path.GetComponents();
18 
19   File volume(FilePath(L"\\\\.\\" + components[0]), File::FLAG_OPEN);
20   if (!volume.IsValid()) {
21     return std::nullopt;
22   }
23   DriveInfo info;
24 
25   STORAGE_PROPERTY_QUERY seek_query = {
26       .PropertyId = StorageDeviceSeekPenaltyProperty,
27       .QueryType = PropertyStandardQuery};
28   DEVICE_SEEK_PENALTY_DESCRIPTOR seek_result;
29   DWORD bytes_returned;
30   BOOL success =
31       DeviceIoControl(volume.GetPlatformFile(), IOCTL_STORAGE_QUERY_PROPERTY,
32                       &seek_query, sizeof(seek_query), &seek_result,
33                       sizeof(seek_result), &bytes_returned, nullptr);
34   if (success == TRUE && bytes_returned >= sizeof(seek_result)) {
35     info.has_seek_penalty = seek_result.IncursSeekPenalty != FALSE;
36   }
37 
38   STORAGE_PROPERTY_QUERY bus_query = {.PropertyId = StorageDeviceProperty,
39                                       .QueryType = PropertyStandardQuery};
40   STORAGE_DEVICE_DESCRIPTOR bus_result;
41   success =
42       DeviceIoControl(volume.GetPlatformFile(), IOCTL_STORAGE_QUERY_PROPERTY,
43                       &bus_query, sizeof(bus_query), &bus_result,
44                       sizeof(bus_result), &bytes_returned, nullptr);
45   if (success == TRUE && bytes_returned >= sizeof(bus_result)) {
46     info.is_usb = bus_result.BusType == BusTypeUsb;
47     info.is_removable = bus_result.RemovableMedia == TRUE;
48   }
49 
50   PARTITION_INFORMATION_EX partition_info;
51   success = DeviceIoControl(
52       volume.GetPlatformFile(), IOCTL_DISK_GET_PARTITION_INFO_EX, nullptr, 0,
53       &partition_info, sizeof(partition_info), &bytes_returned, nullptr);
54   if (success == TRUE && bytes_returned >= sizeof(partition_info)) {
55     info.size_bytes = partition_info.PartitionLength.QuadPart;
56   }
57 
58   return info;
59 }
60 
61 }  // namespace base
62