Read bytes of hard drive - c++

Using the hex editor HxDen one can read (and edit) the bytes on the hard drive or a USB key or the RAM. That is, one can read/change the first byte on the hard disk.
I understand how to read the bytes from a file using C++, but I was wondering how one might do this for the hard disk.
To make it simple, given a positive integer n, how can I read byte number n on the hard drive using C++? (I would like to do C++, but if there is an easier way, I would like to hear about that.)
I am using MinGW on Windows 7 if that matters.

It is documented in the MSDN Library article for CreateFile, section "Physical Disks and Volumes". This code worked well to directly read the C: drive:
HANDLE hdisk = CreateFile(L"\\\\.\\C:",
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
0, NULL);
if (hdisk == INVALID_HANDLE_VALUE) {
int err = GetLastError();
// report error...
return -err;
}
LARGE_INTEGER position = { 0 };
BOOL ok = SetFilePointerEx(hdisk, position, nullptr, FILE_BEGIN);
assert(ok);
BYTE buf[65536];
DWORD read;
ok = ReadFile(hdisk, buf, 65536, &read, nullptr);
assert(ok);
// etc..
Admin privileges are required, you must run your program elevated on Win7 or you'll get error 5 (Access denied).

Related

Read/Write to unformatted SD Card on Windows

I am trying to read/write to an SD card that is unformatted and I am having issues. I am using the windows API to open a handle to the SD card and read/write to it, however I get various errors depending on my approach.
Below is me trying to access the SD card by volume label:
HANDLE sdCardHandle = CreateFile("\\\\.\\E:", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(sdCardHandle == INVALID_HANDLE_VALUE)
{
CloseHandle(sdCardHandle);
return;
}
// I have also tried using VirtualAlloc() to get a sector aligned buffer
unit8_t buffer[512] = { 0 };
DWORD bytesWritten = 0;
if(WriteFile(sdCardHandle, buffer, 512, &bytesWritten, NULL) != TRUE)
{
DWORD lastError = GetLastError();
CloseHandle(sdCardHandle);
return;
}
However the WriteFile fails and the last error is 87 which is invalid parameter. I have tried locking the volume and also unmounting the volume before writing also and it failed.
The next attempt was to try and write to the physical drive instead by running the following in administrator mode:
HANDLE sdCardHandle = CreateFile("\\\\.\\PhysicalDrive1", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(sdCardHandle == INVALID_HANDLE_VALUE)
{
CloseHandle(sdCardHandle);
return;
}
// I have also tried using VirtualAlloc() to get a sector aligned buffer
unit8_t buffer[512] = { 0 };
DWORD bytesWritten = 0;
if(WriteFile(sdCardHandle, buffer, 512, &bytesWritten, NULL) != TRUE)
{
DWORD lastError = GetLastError();
CloseHandle(sdCardHandle);
return;
}
Which also fails but return error 23 which is a bad CRC error. I have also tried unmounting and locking the volume first but nothing changed. If there is any thing else I need to do or try please let me know.
Thank you everyone for all of your help and suggestions. It turns out I was doing the operation correct the entire time. However the SD card reader was causing the error. The issue I believe is that BitDefender might not be allowing the read/write operations to go out to the physical disk. I instead used a USB adapter that shows the SD card as USB drive and my read/write works! Hopefully this helps anyone having a similar issue.
from CreateFile
Volume handles can be opened as noncached at the discretion of the
particular file system, even when the noncached option is not
specified in CreateFile. You should assume that all Microsoft file
systems open volume handles as noncached. The restrictions on
noncached I/O for files also apply to volumes.
so we need assume that FILE_FLAG_NO_BUFFERING (FILE_NO_INTERMEDIATE_BUFFERING) will be used:
Specifying this flag places the following restrictions on the caller's
parameters to other ZwXxxFile routines.
Any optional ByteOffset passed to NtReadFile or NtWriteFile must be a multiple of the sector size.
The Length passed to NtReadFile or NtWriteFile must be an integral of the sector size. Note that specifying a read operation to
a buffer whose length is exactly the sector size might result in a
lesser number of significant bytes being transferred to that buffer
if the end of the file was reached during the transfer.
Buffers must be aligned in accordance with the alignment requirement of the underlying device. To obtain this information,
call NtCreateFile to get a handle for the file object that
represents the physical device, and pass that handle to NtQueryInformationFile. For a list of the system's FILE_XXX_ALIGNMENT values, see DEVICE_OBJECT.
note, that here - Alignment and File Access Requirements was wrong information:
File access buffer addresses for read and write operations should be
physical sector-aligned, which means aligned on addresses in memory
that are integer multiples of the volume's physical sector size.
Depending on the disk, this requirement may not be enforced.
this is false - buffer addresses for read and write operations must not be physical sector-aligned. it must be aligned in accordance with the alignment requirement of the underlying device. this is absolute different things.
we can get this align from FILE_ALIGNMENT_INFO (win 8+) or by using FILE_ALIGNMENT_INFORMATION via NtQueryInformationFile with FileAlignmentInformation
in your current code you hardcode buffer size to 512. however sector size of device can be bigger size.
// I have also tried using VirtualAlloc() to get a sector aligned
buffer
how i say - you not need sector aligned buffer (usual device align 2-4 bytes). but you need buffer integral of the sector size. so before read data - you need first query sector size and device align required
HANDLE sdCardHandle = CreateFile(L"\\\\.\\PhysicalDrive1", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (sdCardHandle != INVALID_HANDLE_VALUE)
{
FILE_ALIGNMENT_INFO fai;
if (GetFileInformationByHandleEx(sdCardHandle, FileAlignmentInfo, &fai, sizeof(fai)))
{
ULONG BytesReturned;
STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR saad;
STORAGE_PROPERTY_QUERY spq = { StorageAccessAlignmentProperty, PropertyStandardQuery };
if (DeviceIoControl(sdCardHandle, IOCTL_STORAGE_QUERY_PROPERTY, &spq, sizeof(spq), &saad, sizeof(saad), &BytesReturned, 0))
{
if (PBYTE pb = new BYTE[saad.BytesPerPhysicalSector + fai.AlignmentRequirement])
{
PBYTE buf = (PBYTE)(((ULONG_PTR)pb + fai.AlignmentRequirement) & ~(ULONG_PTR)fai.AlignmentRequirement);
if (ReadFile(sdCardHandle, buf, saad.BytesPerPhysicalSector, &BytesReturned, 0))
{
__nop();
}
else
{
GetLastError();//RtlGetLastNtStatus();
}
delete [] pb;
}
}
}
CloseHandle(sdCardHandle);
}
also as separate note - when you use OPEN_EXISTING - any file attributes is ignored (it used only when you create new file). as result use FILE_ATTRIBUTE_NORMAL - senseless (but not error - simply will be ignored)

What is the fastest way to read a file in disk in c++?

I am writing a program to check whether a file is PE file or not. For that, I need to read only the file headers of files(which I guess do not occupy more than first 1024 bytes of a file).
I tried using creatfile() + readfile() combination which turns out be slower because I am iterating through all the files in system drive. It is taking 15-20 minutes just to iterate through them.
Can you please tell some alternate approach to open and read the files to make it faster?
Note : Please note that I do NOT need to read the file in whole. I just need to read the initial part of the file -- DOS header, PE header etc which I guess do not occupy more than first 512 bytes of the file.
Here is my code :
bool IsPEFile(const String filePath)
{
HANDLE hFile = CreateFile(filePath.c_str(),
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
DWORD dwBytesRead = 0;
const DWORD CHUNK_SIZE = 2048;
BYTE szBuffer[CHUNK_SIZE] = {0};
LONGLONG size;
LARGE_INTEGER li = {0};
if (hFile != INVALID_HANDLE_VALUE)
{
if(GetFileSizeEx(hFile, &li) && li.QuadPart > 0)
{
size = li.QuadPart;
ReadFile(hFile, szBuffer, CHUNK_SIZE, &dwBytesRead, NULL);
if(dwBytesRead > 0 && (WORDPTR(szBuffer[0]) == ('M' << 8) + 'Z' || WORDPTR(szBuffer[0]) == ('Z' << 8) + 'M'))
{
LONGLONG ne_pe_header = DWORDPTR(szBuffer[0x3c]);
WORD signature = 0;
if(ne_pe_header <= dwBytesRead-2)
{
signature = WORDPTR(szBuffer[ne_pe_header]);
}
else if (ne_pe_header < size )
{
SetFilePointer(hFile, ne_pe_header, NULL, FILE_BEGIN);
ReadFile(hFile, &signature, sizeof(signature), &dwBytesRead, NULL);
if (dwBytesRead != sizeof(signature))
{
return false;
}
}
if(signature == 0x4550) // PE file
{
return true;
}
}
}
CloseHandle(hFile);
}
return false;
}
Thanks in advance.
I think you're hitting the inherent limitations of mechanical hard disk drives. You didn't mention whether you're using a HDD or a solid-state disk, but I assume a HDD given that your file accesses are slow.
HDDs can read data at about 100 MB/s sequentially, but seek time is a bit over 10 ms. This means that if you seek to a certain location (10 ms), you might as well read a megabyte of data (another 10 ms). This also means that you can access only less than 100 files per second.
So, in your case it doesn't matter much whether you're reading the first 512 bytes of a file or the first hundred kilobytes of a file.
Hardware is cheap, programmer time is expensive. Your best bet is to purchase a solid-state disk drive if your file accesses are too slow. I predict that eventually all computers will have solid-state disk drives.
Note: if the bottleneck is the HDD, there is nothing you can do about it other than to replace the HDD with better technology. Practically all file access mechanisms are equally slow. The only thing you can do about it is to read only the initial part of a file if the file is really really large such as multiple megabytes. But based on your code example you're already doing that.
For faster file IO, you need to use CreateFile and ReadFile APIs of Win32.
If you want to speed up, you can use file buffering and make file non-blocking by using overlapped IO or IOCP.
See this example for help: https://msdn.microsoft.com/en-us/library/windows/desktop/bb540534%28v=vs.85%29.aspx
And I think that FILE and fstream of C and C++ respectively are not faster than Win32.

Reading data off of a cluster

I need help reading data off of the last cluster of a file using CreateFile() and then using ReadFile(). First I'm stuck with a zero result for my ReadFile() because I think I have incorrect permissions set up in CreateFile().
/**********CreateFile for volume ********/
HANDLE hDevice = INVALID_HANDLE_VALUE;
hDevice = CreateFile(L"\\\\.\\C:",
0,
FILE_SHARE_READ |
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
wcout << "error at hDevice at CreateFile "<< endl;
system("pause");
}
/******* Read file from the volume *********/
DWORD nRead;
TCHAR buff[4096];
if (BOOL fileFromVol = ReadFile(
hDevice,
buff,
4096,
&nRead,
NULL
) == 0) {
cout << "Error with fileFromVol" << "\n\n";
system("pause");
}
Next, I have all the cluster information and file information I need (file size, last cluster location of the file,# of clusters on disk, cluster size,etc). How do I set the pointer on the volume to start at a specfied cluster location so I can read/write data from it?
The main problem is that you specify 0 for dwDesiredAccess. In order to read the data you should specify FILE_READ_DATA.
On top of that I seriously question the use of TCHAR. That's appropriate for text when you need to support Windows 9x. On top of not needing to support Windows 9x, the data is not text. Your buffer should be of type unsigned char.
Obviously you need the buffer to be a multiple of the cluster size. You've hard coded 4096, but the real code should surely query the cluster size.
When either of these API calls fail, they indicate a failure reason in the last error value. You can obtain that by calling GetLastError. When your ReadFile fails it will return ERROR_ACCESS_DENIED.
You can seek in the volume by calling SetFilePointerEx. Again, you will need to seek to multiples of the cluster size.
LARGE_INTEGER dist;
dist.QuadPart = ClusterNum * ClusterSize;
BOOL res = SetFilePointerEx(hFile, dist, nullptr, FILE_BEGIN);
if (!res)
// handle error
If you are reading sequentially that there's no need to set the file pointer. The call to ReadFile will advance it automatically.
When doing random-access I/O, just don't mess with the file pointer stored in the file handle at all. Instead, use an OVERLAPPED structure and specify the location for each and every I/O operation.
This works even for synchronous I/O (if the file is opened without FILE_FLAG_OVERLAPPED).
Of course, as David mentioned you will get ERROR_ACCESS_DENIED if you perform operations using a file handle opened without sufficient access.

how to directly read/write usb (disk) like winhex?

My goal is to read /write usb.
First Must open and read usb low -level like 'program'
I used visual c++ with winAPI
below is my test code
char path[64];
sprintf(path,"\\\\.\\%c:",volume);//
/////MOST case, user's input is F or G ......
HANDLE usb;
usb=CreateFile(TEXT(path),
GENERIC_ALL,//
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, //serail I/O
NULL);
if(usb==INVALID_HANDLE_VALUE) cout<<"fail to createfile()"<<endl;
cout<<usb<<endl;
char buf[128];
DWORD dwBytesRead=0;
ReadFile(usb,buf,sizeof(buf),&dwBytesRead,NULL);
cout<<buf<<endl;
cout<<GetLastError()<<endl;
CloseHandle(usb);
I wonder CreateFile was correct And ReadFile
GetLastError() of ReadFile() was 87 that means Invalid Input...
what is the wrong??
I referenced MSDN many times...But any page doesn't solve this problem....
What Should I know? fix it?
Size of buffer must be equal to N * (sector size of drive) where N is DWORD value. Sector size can be received with DeviceIoControl(Handle, IOCTL_DISK_GET_DRIVE_GEOMETRY, ..., DISK_GEOMETRY, ...).

Reading large binary files in small parts

I want to read a file from hard disk in size up to ~4-5GB. But not whole at once but in parts of ~100MB in sequence. I want to make it simple and fast as possible, but now I see that that the standard methods from C++ will not work for files bigger than 2GB.
I use Visual Studio 2008, C++/CLI. Any suggestions? I try to use CreateFile, ReadFile but for me it makes more problems than really works, or I use them wrong for reading a big file in parts.
EDIT: Sample code:
Creating handle
hFile = CreateFile(result,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL
|FILE_FLAG_NO_BUFFERING
| FILE_FLAG_OVERLAPPED,
0);
Reading
lpOverlapped = new OVERLAPPED;
lpOverlapped->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
lpOverlapped->Offset=10;
lpOverlapped->OffsetHigh=0;
DWORD howMuchWasRead;
BOOLEAN error = false;
do {
this->lastError = NO_ERROR;
BOOL bRet = ReadFile(this->hFile,this->fileBuffer,this->currentBufferSize,&howMuchWasRead,lpOverlapped);
this->lastError = GetLastError();
if (this->lastError == ERROR_IO_PENDING){
while(!HasOverlappedIoCompleted(this->lpOverlapped)){}
error = true;
} else {
error = false;
}
} while (error == true);
This version now returns me ERROR_INVALID_PARAMETER 87 (0x57), for 4GB .iso file, buffer size is 100MB.
You can map parts of the file into the address space of your process using CreateFile, CreateFileMapping and MapViewOfFile.
You can read the file sequentially without any problems.
The limitations is that fseek uses a long parameter for the offset when you want to seek. If you don't reposition in the file, or the offset is always less than 2GB, there is no problem.
ReadFile will handle files larger than 2GB, maybe you can rephrase your question so we can help you figure out the problems you are having with that.