C CreateFileMapping error 5 Access Denied ALWAYS - winapi

I would like to ask for help with WINAPI function CreateFileMapping (), which returns constantly NULL. After GetLastError() I get 5 - "ERROR_ACCESS_DENIED 5 (0x5) Access is denied". The file has been created after CreateFile with no problem, but following CreateFileMapping never has bee succesful.
int MapDestFile(LPCWSTR fPath)
{
hDestFile = CreateFile(
fPath,
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hSourceFile == NULL)
{
printf("%d\n", GetLastError());
}
hDestMapFile = CreateFileMapping(
hDestFile,
NULL,
PAGE_READWRITE,
0,
10,
NULL
);
if (hDestMapFile == NULL)
{
// here always tell error number 5
printf("%d\n", GetLastError());
}
lpMapAddressDestFile = MapViewOfFile(
hDestMapFile,
FILE_MAP_WRITE,
0,
0,
0);
if (lpMapAddressDestFile == NULL)
{
printf("%d\n", GetLastError());
}
return 1;
}
I would appreciate any suggestions.
Thanks

You need to create the file with GENERIC_WRITE | GENERIC_READ to match PAGE_READWRITE.
That seems self-evident when you think about it. How can you have memory that you can read from backed by a file that you cannot read from? The documentation does call this out explicitly in any case:
PAGE_READWRITE
The file handle that the hFile parameter specifies must be created with the GENERIC_READ and GENERIC_WRITE access rights.
On top of that your error checking on the call to CreateFile is wrong. Take another look at the documentations. Error is indicated by a return value of INVALID_FILE_HANDLE.

Related

Why I get ERROR_INVALID_FUNCTION ( winapi error 1 ), when I execute GetFileSizeEx?

I would like to get file size of my external hard disk.
handle = CreateFile(L"\\\\.\\PhysicalDrive5", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL , NULL);
if (handle == INVALID_HANDLE_VALUE) {
std::cout<<"ERROR!"<<std::endl;
return -1;
}
LARGE_INTEGER size;
if(!GetFileSizeEx(handle, &size))
{
auto lastError = GetLastError();
std::cout<<"Last Error: "<<lastError<<std::endl;
CloseHandle(handle);
return -1;
}
When I execute my application with admin rights ( it is necessary for CreateFile ), I get Last Error: 1.
OS: Windows 10,
Compiler: MinGW 7.3.0
AFAIK, GetFileSizeEx() is the wrong function to use for a "physical disk" object.
Use DeviceIoControl() with IOCTL_DISK_GET_DRIVE_GEOMETRY instead.

Is it possible for a child process to read a file which is locked by parent process?

I have a Parent process which creates a file using CreateFile() and locks it. below is the code:
m_hWriterLockFile = ::CreateFile("C:\\Test.txt",
GENERIC_READ | GENERIC_WRITE,
0, // exclusive
NULL, // default security
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
Now, I want only the child process to access this locked file. I do not want any other process to read this file.
I have created a child process. Below is the sample code:
// Initialize a security attributes structure.
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = pSD;
sa.bInheritHandle = TRUE;
if (!CreateProcess("FileReader.exe", // I want to invoke this exe
"C:\\Test.txt",
&sa,
NULL,
TRUE,
0,
NULL,
NULL,
&si,
&pi))
{
std::cout << "Create Process Faild (%d) " << GetLastError() << '\n';
}
Unfortunately, I am not able to achieve my goal, is there anyone who can help me? Is there any other way to achieve this? I will share more information(code) if needed.
Note: I didn't share the complete code to make the post shorter.
Here is the answer of of my question :
create the file with an inheritable handle and pass that handle to the child process. A simple way to do this is to pass it as a command line parameter. We must pass a SECURITY_ATTRIBUTES structure that specifies TRUE for bInheritHandle to CreateFile and also pass TRUE to the bInheritHandles parameter of the call to CreateProcess.
Create File
Ex:
SECURITY_ATTRIBUTES sa{ sizeof sa, nullptr, TRUE };
HANDLE hFile = CreateFileA("C:\\Test.txt",
GENERIC_READ | GENERIC_WRITE,
0,
&sa,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
Child Process:
UINT_PTR uiHandle = reinterpret_cast<UINT_PTR>(hFile);
sprintf_s(szCmdLine, "\"%s\" %Iu", szExePath, uiHandle);
if (CreateProcessA(nullptr,
szCmdLine,
nullptr,
nullptr,
TRUE,
CREATE_NEW_CONSOLE,
nullptr,
nullptr,
&si,
&pi))
{
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}

How to read a file using readfile on Winapi

I'm learning how to use in Winapi
And I'm trying to read a file from My Computer
But for some reason it doesn't work ...
HANDLE hFile;
//PVOID First_Bytes[2048];
char First_Bytes[2048];
DWORD dbr = 0;
hFile = CreateFile(L"d:\\My-File",GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL , NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("Error %x", GetLastError());
return 1;
}
if (ReadFile(hFile, &First_Bytes, 512, &dbr, NULL) == 0) {
printf("ReadFile error: %x", GetLastError());
return 1;
}
printf("%s", First_Bytes);
CloseHandle(hFile);
The console doesn't print anything.
What am I doing wrong?
I edited the code and add that errors checks.
But still consul does not print anything
The logical conclusion is that the first byte in your file is a zero. You treat the buffer as a null-terminated string, and so nothing is printed.
Do note that there is no guarantee that your buffer is null terminated so you potentially have undefined behaviour.

MapViewOfFile failes with errorCode 6 (Invalid Handle)

Im trying to map the file to the memory and use MapViewOfFile(), but it failes with error code 6. I tried just about anything, I also read about big files being the problem, but the problem happens also with a 1kb file.
my code:
HANDLE hFile = CreateFile(pFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
e = GetLastError();
printf("CreateFile Errorcode %d\n", GetLastError());
if (hFile == INVALID_HANDLE_VALUE)
{
printf("Error: could not create handle to file");
printf("CreateFileMapping error code: %d", e)
return 1;
}
printf("successfully created a Handle to try.txt");
HANDLE pMap = CreateFileMapping(hFile, NULL, PAGE_EXECUTE_READWRITE,0 ,0 ,NULL);
e = GetLastError();
if (pMap == INVALID_HANDLE_VALUE)
{
printf("Error: Unable to CreateFileMapping\n");
printf("CreateFileMapping error code: %d", e)
return 1;
}
printf("CreateFileMapping successfull.")
LPVOID lpBase MapViewOfFile(pMap, FILE_MAP_ACCESS| FILE_MAP_EXECUTE, 0, 0, 0);
e = GetLastError();
if (!lpBase)
{
printf("Error: could not map file to memory");
printf("MapViewOfFile Errorcode %d\n", GetLastError());
CloseHandle(hFile);
UnmapViewOfFile(lpBase);
printf("closed hFile handle and unmapped lpBase.")
return 1;
}
the output is the following:
> successfully created a Handle to try.txt
> createFileMapping successfull
> Error: unable to MapViewOfFile
> MapViewOfFile errorcode: 6
> closed hFile handle and unmapped lpBase.
Here:
HANDLE hFile = CreateFile(pFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
Replace GENERIC_READ with GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE
Also there is no FILE_MAP_ACCESS, but FILE_MAP_ALL_ACCESS.
I tried this code and it maps test file with success, not sure what you want to do with it further. Also for inspecting problems you can also use: Procmon.exe from sysinternals - it will report you what problems occured during file manipulations.

How Can I Get Exclusive Lock On Drive / Partition Win-Api 32?

How to lock lock on specific drive till i perform some operation(read/write) on that drive.
When i have captured lock on drive, no other process should able to write on that drive unitl I release lock on that drive, I have found one API i.e. DeviceIoControl(),
but I want access on drive for my process only, but the above API 'MAY' block access of all the processes. I'm not quite sure how lockfile() and lockfileex() works. Please help me find some way / API/ Logic to do this!
...
...
UPDATED :-
with referrance to your answer i have tried this :-->
HANDLE hdest,hf;
DWORD b,write;
hdest = CreateFile("\\\\?\\E:",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
NULL,
NULL);
if (hdest == INVALID_HANDLE_VALUE)
{
MessageBox(NULL,TEXT("NOT OK"),TEXT("NOT OK"),0);
}
if (DeviceIoControl( hdest,FSCTL_LOCK_VOLUME,NULL,0,NULL,0,&b,NULL))
{
MessageBox(NULL,TEXT("OK"),TEXT("OK"),0);
hf = CreateFile(TEXT("E:\\M_lucky.txt"), GENERIC_WRITE, 0, NULL,CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
MessageBox(NULL,TEXT("NOT OK AFTER LOCK I"),TEXT("NOT OK AFTRE LOCK"),0);
}
WriteFile(hf, TEXT("M very lucky"), 13, &write, NULL);
}
CloseHandle((HANDLE)hdest);
CloseHandle((HANDLE)hf);
DeviceIoControl( hdest,FSCTL_UNLOCK_VOLUME,NULL,0,NULL,0,&b,NULL);
hf = CreateFile(TEXT("E:\\MNOT_lucky.txt"), GENERIC_WRITE, 0, NULL,CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
MessageBox(NULL,TEXT("NOT OK AFTER LOCK"),TEXT("NOT OK AFTRE LOCK"),0);
}
WriteFile(hf, TEXT("M lucky"), 8, &write, NULL);
CloseHandle((HANDLE)hf);
""but........""
after getting exclusive lock on E drive, i am unable to create file.
(i have read that : only hdest(HANDLE) gets exclusive lock on that drive. )
here..!!! i want to create M_LUCKY.txt file..!!
(I need EXLUSIVE access on drive with context to PROCESS)
plz help! thanks a lottt!!
is there any other method for doing this??
Use DeviceIoControl with FSCTL_LOCK_VOLUME control code.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa364575(v=vs.85).aspx

Resources