Я пытаюсь выполнить сопоставление файлов моего текущего процесса, следуя документации MSDN: https://docs.microsoft.com/en-us/windows/win32/memory/creating-a-view-within-a-file
Похоже, что сопоставление работает, когда я компилирую в режиме выпуска (в visual studio), но выдает ошибку, когда я работаю в режиме отладки:
> .\my_bin.exe
File path is : C:\Users\myuser\source\repos\my_bin\x64\Debug\my_bin.exe
Copying file using file mapping
error lpMapAddress is NULL : 5
5 - это код ошибки для ACCESS_DENIED. Интересно, почему мне было отказано в доступе к двоичному файлу, который я выполняю сам и к которому я запрашиваю разрешения READ_ONLY.
Если у кого-то есть идея, я был бы благодарен!
Здесь это код:
#define handle_error(msg) \
do { \
printf("error %s : %d\n", msg, GetLastError()); exit(EXIT_FAILURE); \
} while (0)
void file_mapping_copy(TCHAR* file_path) {
HANDLE hFile;
HANDLE hMapFile;
LPVOID lpMapAddress; // pointer to the base address of the
BOOL bFlag;
DWORD dwSysGran; // system allocation granularity
DWORD dwFileMapStart; // where to start the file map view
DWORD dwMapViewSize;
DWORD dwFileMapSize;
SYSTEM_INFO SysInfo; // system information; used to get granularity
hFile = CreateFile(file_path,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL);
#ifdef _DEBUG
if (hFile == INVALID_HANDLE_VALUE) {
handle_error("Create File error");
}
#endif
GetSystemInfo(&SysInfo);
dwSysGran = SysInfo.dwAllocationGranularity;
dwFileMapStart = 0;
dwMapViewSize = MAP_BUFF_SIZE;
dwFileMapSize = MAP_BUFF_SIZE;
hMapFile = CreateFileMapping(hFile, // current file handle
NULL, // default security
PAGE_READONLY, // read/write permission
0, // size of mapping object, high
dwFileMapSize, // size of mapping object, low
NULL); // name of mapping object
#ifdef _DEBUG
if (hMapFile == INVALID_HANDLE_VALUE) {
handle_error("Create File error");
}
#endif
lpMapAddress = MapViewOfFile(hMapFile,
FILE_MAP_ALL_ACCESS, // read/write
0, // high-order 32
// bits of file
// offset
dwFileMapStart, // low-order 32
// bits of file
// offset
dwMapViewSize); // number of bytes
// to map
#ifdef _DEBUG
if (lpMapAddress == NULL) {
handle_error("lpMapAddress is NULL");
}
#endif
puts("should be ok");
bFlag = UnmapViewOfFile(lpMapAddress);
bFlag = CloseHandle(hFile);
#ifdef _DEBUG
if (!bFlag) {
handle_error("Close File error");
}
#endif
}
int main() {
WCHAR path[MAX_PATH];
GetModuleFileNameW(NULL, path, MAX_PATH);
printf("File path is : %ls\n", path);
#ifdef _DEBUG
puts("Copying file using file mapping");
#endif
file_mapping_copy(path);
}
EDIT : я ошибаюсь с разрешениями MapViewOfFile
, которые требовали разрешения FILE_MAP_READ. И все же ошибка странная.