For some reasons, i'm using the method described here: http://geekswithblogs.net/TechTwaddle/archive/2009/10/16/how-to-embed-an-exe-inside-another-exe-as-a.aspx
It starts off from the first byte of the embedded file and goes through 4.234.925 bytes one by one! It takes approximately 40 seconds to finish.
Is there any other methods for copying an embedded file to the hard-disk? (I maybe wrong here but i think the embedded file is read from the memory)
Thanks.
Once you know the location and size of the embedded exe , then you can do it in one write.
LPBYTE pbExtract; // the pointer to the data to extract
UINT cbExtract; // the size of the data to extract.
HANDLE hf;
hf = CreateFile("filename.exe", // file name
GENERIC_WRITE, // open for writing
0, // no share
NULL, // no security
CREATE_ALWAYS, // overwrite existing
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no template
if (INVALID_HANDLE_VALUE != hf)
{
DWORD cbWrote;
WriteFile(hf, pbExtract, cbExtract, &cbWrote, NULL);
CloseHandle(hf);
}
As the man says, write more of the file (or the whole thing) per WriteFile call. A WriteFile call per byte is going to be ridiculously slow yes.
Related
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)
I have a big file (500mb), I know how to read this file with ReadFile function
but I want to read 100mb by 100mb
I mean I want to read the file in the while loop, in the first loop I read the first 100mb of file, second time read the second 100mb(from 101 to 200), ...
for example I have a file that contains abdcefghijklmnopqrstuvwxyz now I want to read abcd at first, then read efgh, then ijkl and so on...
Thanks for help
As far as I understood you want to read the file chunk by chunk?
in short the logic is:
get the size of the file or read till ReadFile return error
while (a chunk larger than zero could be read)
{
write chunk to output
}
IN other words: The easiest way is first to get the file size :
HANDLE hFile = CreateFile("c:\\myFile", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
DWORD dwFileSize = GetFileSize(hFile, NULL);
and now define your loop. Read chunks up to 1024 bytes. Of course you can use larger buffer.
BYTE buffer[1024];
while(read is less than remain ) {
ReadFile(hFile, buffer, sizeof(buffer), &dwRead, NULL)
// append what you just read to some global buffer
}
Search in google for "read file in chunks" and you will find large amount of examples.
I want to use Writefile to fill up then end of every file until it reaches the end of its last cluster. Then I want to delete what I wrote and repeat the process(attempting to get rid data that might have been there).
I have a 2 issues:
WriteFile gives me an error: ERROR_INVALID_PARAMETER
Depending on the type of file, WriteFile() gives me different results
So for the first issue I realized that the parameter nNumberOfBytesToWrite in the WriteFile() has to be a multiple of bytes per sector(my case is 512 bytes). Is this a limitation of the function or am I doing something wrong?
In my second issue, I'm using two dummy files(.txt and .html) on an external hard drive to write random data to. In the case of the .txt file, the data is written to the end of the file which is what I need. However, the .html file just writes to the beginning of the file and replaces any data that was already there.
Here are some code snippets relevant to my issue:
hFile = CreateFile(result,
GENERIC_READ | GENERIC_WRITE |FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
0);
if (hFile == INVALID_HANDLE_VALUE) {
cout << "File does not exist" << endl;
CloseHandle(hFile);
}
DWORD dwBytesWritten;
char * wfileBuff = new char[512];
memset (wfileBuff,'0',512);
returnz = SetFilePointer(hFile, 0,NULL,FILE_END);
if(returnz ==0){
cout<<"Error: "<<GetLastError()<<endl;
};
LockFile(hFile, returnz, 0, 512, 0)
returnz =WriteFile(hFile, wfileBuff, 512, &dwBytesWritten, NULL);
if(returnz ==0){
cout<<"Error: "<<GetLastError()<<endl;
}
UnlockFile(hFile, returnz, 0, 512, 0);
cout<<dwBytesWritten<<endl<<endl;
I am using static numbers at the moment just to test out the functions. Is there anyway I can always write to the the end of the file no matter what type of file? I also tried SetFilePointer(hFile, 0,(fileSize - slackSpace + 1),FILE_BEGIN); but that didn't work.
You need to heed the information in the documentation concerning FILE_FLAG_NO_BUFFERING. Specifically this section:
As previously discussed, an application must meet certain requirements
when working with files opened with FILE_FLAG_NO_BUFFERING. The
following specifics apply:
File access sizes, including the optional file offset in the OVERLAPPED structure, if specified, must be for a number of bytes that
is an integer multiple of the volume sector size. For example, if the
sector size is 512 bytes, an application can request reads and writes
of 512, 1,024, 1,536, or 2,048 bytes, but not of 335, 981, or 7,171
bytes.
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.
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.
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.