84 lines
2.3 KiB
C
84 lines
2.3 KiB
C
#include <windows.h>
|
|
|
|
#include <crc32.h>
|
|
#include <msg.h>
|
|
|
|
#include <utils.h>
|
|
|
|
void utils_map_file(const wchar_t *path, struct file_mapping *map) {
|
|
map->file = CreateFileW(path, FILE_READ_ACCESS, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
|
|
if (map->file == INVALID_HANDLE_VALUE) {
|
|
msg_err_w(L"Could not open file: %ls", path);
|
|
}
|
|
|
|
map->mapping = CreateFileMappingA(map->file, NULL, PAGE_READONLY, 0, 0, NULL);
|
|
map->data = MapViewOfFile(map->mapping, FILE_MAP_READ, 0, 0, 0);
|
|
if (!map->data) {
|
|
msg_err_w(L"Could not map view of file %ls", path);
|
|
}
|
|
}
|
|
|
|
void utils_unmap_file(struct file_mapping *map) {
|
|
UnmapViewOfFile(map->data);
|
|
CloseHandle(map->mapping);
|
|
CloseHandle(map->file);
|
|
}
|
|
|
|
int utils_path_exists(const wchar_t *filePath) {
|
|
return GetFileAttributesW(filePath) != INVALID_FILE_ATTRIBUTES;
|
|
}
|
|
|
|
uint32_t utils_file_crc32c(const wchar_t *filePath) {
|
|
struct file_mapping map;
|
|
utils_map_file(filePath, &map);
|
|
|
|
LARGE_INTEGER fileSize;
|
|
GetFileSizeEx(map.file, &fileSize);
|
|
|
|
uint32_t crc = crc32c(0, map.data, fileSize.QuadPart);
|
|
|
|
utils_unmap_file(&map);
|
|
return crc;
|
|
}
|
|
|
|
// https://stackoverflow.com/a/16719260
|
|
void utils_create_parent_dirs(const wchar_t *path) {
|
|
wchar_t dir[MAX_PATH];
|
|
ZeroMemory(dir, sizeof(dir));
|
|
|
|
const wchar_t *end = path - 1;
|
|
|
|
while((end = wcschr(++end, L'\\')) != NULL) {
|
|
wcsncpy(dir, path, end - path + 1);
|
|
|
|
if (!utils_path_exists(dir) && !CreateDirectoryW(dir, NULL)) {
|
|
msg_err_w(L"Failed to create directory: %ls", dir);
|
|
}
|
|
}
|
|
}
|
|
|
|
void utils_save_to_file(const wchar_t *filePath, const void *buf, size_t length) {
|
|
HANDLE file = CreateFileW(filePath, FILE_WRITE_ACCESS, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
|
|
if (file == INVALID_HANDLE_VALUE) {
|
|
msg_err_w(L"Could not create file: %ls", filePath);
|
|
}
|
|
|
|
WriteFile(file, buf, length, NULL, FALSE);
|
|
|
|
CloseHandle(file);
|
|
}
|
|
|
|
char utils_env_enabled(const char *env) {
|
|
char *envText = getenv(env);
|
|
return envText && *envText;
|
|
}
|
|
|
|
void utils_write_protected_memory(void *addr, const void *buf, size_t size) {
|
|
DWORD oldProtect;
|
|
VirtualProtect(addr, size, PAGE_READWRITE, &oldProtect);
|
|
|
|
memcpy(addr, buf, size);
|
|
|
|
VirtualProtect(addr, size, oldProtect, &oldProtect);
|
|
}
|