blob: 37e5bb5f36d259fc6e5ffdeb3170a8d17cfd73b1 [file] [log] [blame]
srs5694add79a62010-01-26 15:59:58 -05001//
2// C++ Interface: diskio (Windows-specific components)
3//
4// Description: Class to handle low-level disk I/O for GPT fdisk
5//
6//
7// Author: Rod Smith <rodsmith@rodsbooks.com>, (C) 2009
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
12// This program is copyright (c) 2009, 2010 by Roderick W. Smith. It is distributed
13// under the terms of the GNU GPL version 2, as detailed in the COPYING file.
14
15#define __STDC_LIMIT_MACROS
16#define __STDC_CONSTANT_MACROS
17
18#include <windows.h>
19#include <winioctl.h>
20#define fstat64 fstat
21#define stat64 stat
srs569408bb0da2010-02-19 17:19:55 -050022#define S_IRGRP 0
srs5694add79a62010-01-26 15:59:58 -050023#define S_IROTH 0
24#include <stdio.h>
25#include <string>
26#include <stdint.h>
27#include <errno.h>
28#include <fcntl.h>
29#include <sys/stat.h>
30#include <iostream>
31
32#include "support.h"
33#include "diskio.h"
34
35using namespace std;
36
37// Returns the official Windows name for a shortened version of same.
38void DiskIO::MakeRealName(void) {
srs5694e321d442010-01-29 17:44:04 -050039 size_t colonPos;
srs5694add79a62010-01-26 15:59:58 -050040
41 colonPos = userFilename.find(':', 0);
42 if ((colonPos != string::npos) && (colonPos <= 3)) {
43 realFilename = "\\\\.\\physicaldrive";
44 realFilename += userFilename.substr(0, colonPos);
srs56940a697312010-01-28 21:10:52 -050045 } else {
46 realFilename = userFilename;
srs5694add79a62010-01-26 15:59:58 -050047 } // if/else
srs5694add79a62010-01-26 15:59:58 -050048} // DiskIO::MakeRealName()
49
50// Open the currently on-record file for reading
51int DiskIO::OpenForRead(void) {
52 int shouldOpen = 1;
53
54 if (isOpen) { // file is already open
55 if (openForWrite) {
56 Close();
57 } else {
58 shouldOpen = 0;
59 } // if/else
60 } // if
61
62 if (shouldOpen) {
srs5694add79a62010-01-26 15:59:58 -050063 fd = CreateFile(realFilename.c_str(),GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
64 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
65 if (fd == INVALID_HANDLE_VALUE) {
66 CloseHandle(fd);
srs569455d92612010-03-07 22:16:07 -050067 cerr << "Problem opening " << realFilename << " for reading!\n";
srs5694add79a62010-01-26 15:59:58 -050068 realFilename = "";
69 userFilename = "";
70 isOpen = 0;
71 openForWrite = 0;
72 } else {
73 isOpen = 1;
74 openForWrite = 0;
75 } // if/else
76 } // if
77
78 return isOpen;
79} // DiskIO::OpenForRead(void)
80
81// An extended file-open function. This includes some system-specific checks.
82// Returns 1 if the file is open, 0 otherwise....
83int DiskIO::OpenForWrite(void) {
84 if ((isOpen) && (openForWrite))
85 return 1;
86
87 // Close the disk, in case it's already open for reading only....
88 Close();
89
90 // try to open the device; may fail....
91 fd = CreateFile(realFilename.c_str(), GENERIC_READ | GENERIC_WRITE,
92 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
93 FILE_ATTRIBUTE_NORMAL, NULL);
srs569408bb0da2010-02-19 17:19:55 -050094 // Preceding call can fail when creating backup files; if so, try
95 // again with different option...
96 if (fd == INVALID_HANDLE_VALUE) {
97 CloseHandle(fd);
98 fd = CreateFile(realFilename.c_str(), GENERIC_READ | GENERIC_WRITE,
99 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
100 FILE_ATTRIBUTE_NORMAL, NULL);
101 } // if
srs5694add79a62010-01-26 15:59:58 -0500102 if (fd == INVALID_HANDLE_VALUE) {
103 CloseHandle(fd);
srs5694add79a62010-01-26 15:59:58 -0500104 isOpen = 0;
105 openForWrite = 0;
srs56940a697312010-01-28 21:10:52 -0500106 errno = GetLastError();
107 } else {
108 isOpen = 1;
109 openForWrite = 1;
srs5694add79a62010-01-26 15:59:58 -0500110 } // if/else
111 return isOpen;
112} // DiskIO::OpenForWrite(void)
113
114// Close the disk device. Note that this does NOT erase the stored filenames,
115// so the file can be re-opened without specifying the filename.
116void DiskIO::Close(void) {
117 if (isOpen)
118 CloseHandle(fd);
119 isOpen = 0;
120 openForWrite = 0;
121} // DiskIO::Close()
122
123// Returns block size of device pointed to by fd file descriptor. If the ioctl
srs569455d92612010-03-07 22:16:07 -0500124// returns an error condition, assume it's a disk file and return a value of
125// SECTOR_SIZE (512). If the disk can't be opened at all, return a value of 0.
srs5694add79a62010-01-26 15:59:58 -0500126int DiskIO::GetBlockSize(void) {
srs569455d92612010-03-07 22:16:07 -0500127 DWORD blockSize = 0, retBytes;
128 DISK_GEOMETRY_EX geom;
srs5694add79a62010-01-26 15:59:58 -0500129
130 // If disk isn't open, try to open it....
131 if (!isOpen) {
132 OpenForRead();
133 } // if
134
135 if (isOpen) {
srs5694699941e2011-03-21 21:33:57 -0400136 if (DeviceIoControl(fd, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0,
137 &geom, sizeof(geom), &retBytes, NULL)) {
srs569455d92612010-03-07 22:16:07 -0500138 blockSize = geom.Geometry.BytesPerSector;
srs5694699941e2011-03-21 21:33:57 -0400139 } else { // was probably an ordinary file; set default value....
srs5694add79a62010-01-26 15:59:58 -0500140 blockSize = SECTOR_SIZE;
srs5694699941e2011-03-21 21:33:57 -0400141 } // if/else
srs5694add79a62010-01-26 15:59:58 -0500142 } // if (isOpen)
143
144 return (blockSize);
145} // DiskIO::GetBlockSize()
146
srs5694bf8950c2011-03-12 01:23:12 -0500147// Returns the number of heads, according to the kernel, or 255 if the
148// correct value can't be determined.
149uint32_t DiskIO::GetNumHeads(void) {
150 return UINT32_C(255);
151} // DiskIO::GetNumHeads();
152
153// Returns the number of sectors per track, according to the kernel, or 63
154// if the correct value can't be determined.
155uint32_t DiskIO::GetNumSecsPerTrack(void) {
156 return UINT32_C(63);
157} // DiskIO::GetNumSecsPerTrack()
158
srs5694add79a62010-01-26 15:59:58 -0500159// Resync disk caches so the OS uses the new partition table. This code varies
160// a lot from one OS to another.
161void DiskIO::DiskSync(void) {
srs56940a697312010-01-28 21:10:52 -0500162 DWORD i;
163 GET_LENGTH_INFORMATION buf;
srs5694add79a62010-01-26 15:59:58 -0500164
165 // If disk isn't open, try to open it....
srs56940a697312010-01-28 21:10:52 -0500166 if (!openForWrite) {
167 OpenForWrite();
srs5694add79a62010-01-26 15:59:58 -0500168 } // if
169
170 if (isOpen) {
srs56940a697312010-01-28 21:10:52 -0500171 if (DeviceIoControl(fd, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, &buf, sizeof(buf), &i, NULL) == 0) {
172 cout << "Disk synchronization failed! The computer may use the old partition table\n"
173 << "until you reboot or remove and re-insert the disk!\n";
174 } else {
175 cout << "Disk synchronization succeeded! The computer should now use the new\n"
176 << "partition table.\n";
177 } // if/else
178 } else {
179 cout << "Unable to open the disk for synchronization operation! The computer will\n"
180 << "continue to use the old partition table until you reboot or remove and\n"
181 << "re-insert the disk!\n";
srs5694add79a62010-01-26 15:59:58 -0500182 } // if (isOpen)
183} // DiskIO::DiskSync()
184
185// Seek to the specified sector. Returns 1 on success, 0 on failure.
186int DiskIO::Seek(uint64_t sector) {
187 int retval = 1;
188 LARGE_INTEGER seekTo;
srs5694add79a62010-01-26 15:59:58 -0500189
190 // If disk isn't open, try to open it....
191 if (!isOpen) {
192 retval = OpenForRead();
193 } // if
194
195 if (isOpen) {
srs56940a697312010-01-28 21:10:52 -0500196 seekTo.QuadPart = sector * (uint64_t) GetBlockSize();
srs5694add79a62010-01-26 15:59:58 -0500197 retval = SetFilePointerEx(fd, seekTo, NULL, FILE_BEGIN);
198 if (retval == 0) {
199 errno = GetLastError();
srs56940a697312010-01-28 21:10:52 -0500200 cerr << "Error when seeking to " << seekTo.QuadPart << "! Error is " << errno << "\n";
srs5694add79a62010-01-26 15:59:58 -0500201 retval = 0;
202 } // if
203 } // if
204 return retval;
205} // DiskIO::Seek()
206
207// A variant on the standard read() function. Done to work around
208// limitations in FreeBSD concerning the matching of the sector
209// size with the number of bytes read.
210// Returns the number of bytes read into buffer.
211int DiskIO::Read(void* buffer, int numBytes) {
212 int blockSize = 512, i, numBlocks;
213 char* tempSpace;
214 DWORD retval = 0;
215
216 // If disk isn't open, try to open it....
217 if (!isOpen) {
218 OpenForRead();
219 } // if
220
221 if (isOpen) {
222 // Compute required space and allocate memory
223 blockSize = GetBlockSize();
224 if (numBytes <= blockSize) {
225 numBlocks = 1;
srs5694cb76c672010-02-11 22:22:22 -0500226 tempSpace = new char [blockSize];
srs5694add79a62010-01-26 15:59:58 -0500227 } else {
228 numBlocks = numBytes / blockSize;
srs5694cb76c672010-02-11 22:22:22 -0500229 if ((numBytes % blockSize) != 0)
230 numBlocks++;
231 tempSpace = new char [numBlocks * blockSize];
srs5694add79a62010-01-26 15:59:58 -0500232 } // if/else
srs56946aae2a92011-06-10 01:16:51 -0400233 if (tempSpace == NULL) {
234 cerr << "Unable to allocate memory in DiskIO::Read()! Terminating!\n";
235 exit(1);
236 } // if
237
srs5694add79a62010-01-26 15:59:58 -0500238 // Read the data into temporary space, then copy it to buffer
srs5694add79a62010-01-26 15:59:58 -0500239 ReadFile(fd, tempSpace, numBlocks * blockSize, &retval, NULL);
srs5694add79a62010-01-26 15:59:58 -0500240 for (i = 0; i < numBytes; i++) {
241 ((char*) buffer)[i] = tempSpace[i];
242 } // for
243
244 // Adjust the return value, if necessary....
245 if (((numBlocks * blockSize) != numBytes) && (retval > 0))
246 retval = numBytes;
247
srs5694cb76c672010-02-11 22:22:22 -0500248 delete[] tempSpace;
srs5694add79a62010-01-26 15:59:58 -0500249 } // if (isOpen)
250 return retval;
251} // DiskIO::Read()
252
253// A variant on the standard write() function. Done to work around
254// limitations in FreeBSD concerning the matching of the sector
255// size with the number of bytes read.
256// Returns the number of bytes written.
257int DiskIO::Write(void* buffer, int numBytes) {
258 int blockSize = 512, i, numBlocks, retval = 0;
259 char* tempSpace;
260 DWORD numWritten;
261
262 // If disk isn't open, try to open it....
263 if ((!isOpen) || (!openForWrite)) {
264 OpenForWrite();
265 } // if
266
267 if (isOpen) {
268 // Compute required space and allocate memory
269 blockSize = GetBlockSize();
270 if (numBytes <= blockSize) {
271 numBlocks = 1;
srs5694cb76c672010-02-11 22:22:22 -0500272 tempSpace = new char [blockSize];
srs5694add79a62010-01-26 15:59:58 -0500273 } else {
274 numBlocks = numBytes / blockSize;
275 if ((numBytes % blockSize) != 0) numBlocks++;
srs5694cb76c672010-02-11 22:22:22 -0500276 tempSpace = new char [numBlocks * blockSize];
srs5694add79a62010-01-26 15:59:58 -0500277 } // if/else
srs56946aae2a92011-06-10 01:16:51 -0400278 if (tempSpace == NULL) {
279 cerr << "Unable to allocate memory in DiskIO::Write()! Terminating!\n";
280 exit(1);
281 } // if
srs5694add79a62010-01-26 15:59:58 -0500282
283 // Copy the data to my own buffer, then write it
284 for (i = 0; i < numBytes; i++) {
285 tempSpace[i] = ((char*) buffer)[i];
286 } // for
287 for (i = numBytes; i < numBlocks * blockSize; i++) {
288 tempSpace[i] = 0;
289 } // for
srs5694add79a62010-01-26 15:59:58 -0500290 WriteFile(fd, tempSpace, numBlocks * blockSize, &numWritten, NULL);
291 retval = (int) numWritten;
292
293 // Adjust the return value, if necessary....
294 if (((numBlocks * blockSize) != numBytes) && (retval > 0))
295 retval = numBytes;
296
srs5694cb76c672010-02-11 22:22:22 -0500297 delete[] tempSpace;
srs5694add79a62010-01-26 15:59:58 -0500298 } // if (isOpen)
299 return retval;
300} // DiskIO:Write()
301
302// Returns the size of the disk in blocks.
303uint64_t DiskIO::DiskSize(int *err) {
304 uint64_t sectors = 0; // size in sectors
srs56940a697312010-01-28 21:10:52 -0500305 DWORD bytes, moreBytes; // low- and high-order bytes of file size
srs5694add79a62010-01-26 15:59:58 -0500306 GET_LENGTH_INFORMATION buf;
307 DWORD i;
308
309 // If disk isn't open, try to open it....
310 if (!isOpen) {
311 OpenForRead();
312 } // if
313
314 if (isOpen) {
315 // Note to self: I recall testing a simplified version of
316 // this code, similar to what's in the __APPLE__ block,
317 // on Linux, but I had some problems. IIRC, it ran OK on 32-bit
318 // systems but not on 64-bit. Keep this in mind in case of
319 // 32/64-bit issues on MacOS....
srs5694add79a62010-01-26 15:59:58 -0500320 if (DeviceIoControl(fd, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &buf, sizeof(buf), &i, NULL)) {
321 sectors = (uint64_t) buf.Length.QuadPart / GetBlockSize();
srs56940a697312010-01-28 21:10:52 -0500322 *err = 0;
323 } else { // doesn't seem to be a disk device; assume it's an image file....
324 bytes = GetFileSize(fd, &moreBytes);
325 sectors = ((uint64_t) bytes + ((uint64_t) moreBytes) * UINT32_MAX) / GetBlockSize();
326 *err = 0;
327 } // if
328 } else {
329 *err = -1;
330 sectors = 0;
331 } // if/else (isOpen)
srs5694add79a62010-01-26 15:59:58 -0500332
srs5694add79a62010-01-26 15:59:58 -0500333 return sectors;
334} // DiskIO::DiskSize()