1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
|
/*
* Copyright (C) 2023-2026 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/built_ins/built_ins.h"
#include "shared/source/compiler_interface/compiler_cache.h"
#include "shared/source/debug_settings/debug_settings_manager.h"
#include "shared/source/helpers/file_io.h"
#include "shared/source/helpers/non_copyable_or_moveable.h"
#include "shared/source/helpers/path.h"
#include "shared/source/os_interface/windows/sys_calls.h"
#include "shared/source/utilities/directory.h"
#include "shared/source/utilities/io_functions.h"
#include "elements_struct.h"
#include "os_inc.h"
#include <algorithm>
#include <queue>
namespace NEO {
bool CompilerCache::compareByLastAccessTime(const ElementsStruct &a, const ElementsStruct &b) {
return CompareFileTime(&a.lastAccessTime, &b.lastAccessTime) < 0;
}
bool CompilerCache::createCacheDirectories(const std::string &cacheFile) {
std::string path = config.cacheDir;
for (int i = 0; i < maxCacheDepth; i++) {
path = joinPath(path, std::string(1, cacheFile[i]));
if (!NEO::SysCalls::createDirectoryA(path.c_str(), NULL)) {
DWORD error = NEO::SysCalls::getLastError();
if (error != ERROR_ALREADY_EXISTS) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Create cache directories failed! error code: %lu\n", NEO::SysCalls::getProcessId(), error);
return false;
}
}
}
return true;
}
bool CompilerCache::getFiles(const std::string &startPath, const std::function<bool(const std::string_view &)> &filter, std::vector<ElementsStruct> &foundFiles) {
struct DirectoryEntry {
std::string path;
int depth;
};
foundFiles.clear();
std::queue<DirectoryEntry> directoriesToProcess;
directoriesToProcess.push({startPath, 0});
while (!directoriesToProcess.empty()) {
auto currentEntry = std::move(directoriesToProcess.front());
directoriesToProcess.pop();
WIN32_FIND_DATAA ffd{0};
HANDLE hFind = INVALID_HANDLE_VALUE;
std::string newPath = joinPath(currentEntry.path, "*");
hFind = NEO::SysCalls::findFirstFileA(newPath.c_str(), &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
DWORD error = NEO::SysCalls::getLastError();
if (error == ERROR_FILE_NOT_FOUND) {
continue;
}
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: File search failed! error code: %lu\n", NEO::SysCalls::getProcessId(), error);
return false;
}
do {
if (strcmp(ffd.cFileName, ".") != 0 && strcmp(ffd.cFileName, "..") != 0) {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (currentEntry.depth < maxCacheDepth) {
std::string subDirPath = joinPath(currentEntry.path, ffd.cFileName);
directoriesToProcess.push({subDirPath, currentEntry.depth + 1});
}
} else {
auto fileName = joinPath(currentEntry.path, ffd.cFileName);
if (filter(fileName)) {
uint64_t fileSize = (ffd.nFileSizeHigh * (MAXDWORD + 1)) + ffd.nFileSizeLow;
foundFiles.push_back({ffd.ftLastAccessTime, fileSize, fileName});
}
}
}
} while (NEO::SysCalls::findNextFileA(hFind, &ffd) != 0);
DWORD error = NEO::SysCalls::getLastError();
if (error != ERROR_NO_MORE_FILES) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Finding next file failed! error code: %lu\n", NEO::SysCalls::getProcessId(), error);
NEO::SysCalls::findClose(hFind);
return false;
}
NEO::SysCalls::findClose(hFind);
}
return true;
}
void unlockFileAndClose(UnifiedHandle handle) {
OVERLAPPED overlapped = {0};
auto result = NEO::SysCalls::unlockFileEx(std::get<void *>(handle), 0, MAXDWORD, MAXDWORD, &overlapped);
if (!result) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Unlock file failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
}
NEO::SysCalls::closeHandle(std::get<void *>(handle));
}
bool CompilerCache::evictCache(uint64_t &bytesEvicted) {
bytesEvicted = 0;
std::vector<ElementsStruct> cacheFiles;
if (!getCachedFiles(cacheFiles)) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Get cached files failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
return false;
}
const auto evictionLimit = config.cacheSize / 3;
for (const auto &file : cacheFiles) {
auto res = NEO::SysCalls::deleteFileA(file.path.c_str());
if (!res) {
continue;
}
bytesEvicted += file.fileSize;
if (bytesEvicted > evictionLimit) {
return true;
}
}
return true;
}
void CompilerCache::lockConfigFileAndReadSize(const std::string &configFilePath, UnifiedHandle &handle, size_t &directorySize) {
bool countDirectorySize = false;
std::get<void *>(handle) = NEO::SysCalls::createFileA(configFilePath.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (std::get<void *>(handle) == INVALID_HANDLE_VALUE) {
if (SysCalls::getLastError() != ERROR_FILE_NOT_FOUND) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Open config file failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
return;
}
std::get<void *>(handle) = NEO::SysCalls::createFileA(configFilePath.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (std::get<void *>(handle) == INVALID_HANDLE_VALUE) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Create config file failed! error code: %lu\n", GetCurrentProcessId(), GetLastError());
std::get<void *>(handle) = NEO::SysCalls::createFileA(configFilePath.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
} else {
countDirectorySize = true;
}
}
OVERLAPPED overlapped = {0};
auto result = NEO::SysCalls::lockFileEx(std::get<void *>(handle),
LOCKFILE_EXCLUSIVE_LOCK,
0,
MAXDWORD,
MAXDWORD,
&overlapped);
if (!result) {
std::get<void *>(handle) = INVALID_HANDLE_VALUE;
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Lock config file failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
return;
}
if (countDirectorySize) {
std::vector<ElementsStruct> cacheFiles;
if (!getCachedFiles(cacheFiles)) {
directorySize = 0;
unlockFileAndClose(std::get<void *>(handle));
std::get<void *>(handle) = INVALID_HANDLE_VALUE;
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Get cached files failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
return;
}
for (const auto &file : cacheFiles) {
directorySize += static_cast<size_t>(file.fileSize);
}
} else {
DWORD fPointer = NEO::SysCalls::setFilePointer(std::get<void *>(handle),
0,
NULL,
FILE_BEGIN);
if (fPointer != 0) {
directorySize = 0;
unlockFileAndClose(std::get<void *>(handle));
std::get<void *>(handle) = INVALID_HANDLE_VALUE;
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: File pointer move failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
return;
}
DWORD numOfBytesRead = 0;
result = NEO::SysCalls::readFile(std::get<void *>(handle),
&directorySize,
sizeof(directorySize),
&numOfBytesRead,
NULL);
if (!result) {
directorySize = 0;
unlockFileAndClose(std::get<void *>(handle));
std::get<void *>(handle) = INVALID_HANDLE_VALUE;
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Read config failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
}
}
}
bool CompilerCache::createUniqueTempFileAndWriteData(char *tmpFilePath, const char *pBinary, size_t binarySize) {
auto result = NEO::SysCalls::getTempFileNameA(config.cacheDir.c_str(), "TMP", 0, tmpFilePath);
if (result == 0) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Creating temporary file name failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
return false;
}
auto hTempFile = NEO::SysCalls::createFileA((LPCSTR)tmpFilePath, // file name
GENERIC_WRITE, // open for write
0, // do not share
NULL, // default security
CREATE_ALWAYS, // overwrite existing
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no template
if (hTempFile == INVALID_HANDLE_VALUE) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Creating temporary file failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
return false;
}
DWORD dwBytesWritten = 0;
auto result2 = NEO::SysCalls::writeFile(hTempFile,
pBinary,
(DWORD)binarySize,
&dwBytesWritten,
NULL);
if (!result2) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Writing to temporary file failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
} else if (dwBytesWritten != (DWORD)binarySize) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Writing to temporary file failed! Incorrect number of bytes written: %lu vs %lu\n", NEO::SysCalls::getProcessId(), dwBytesWritten, (DWORD)binarySize);
}
NEO::SysCalls::closeHandle(hTempFile);
return true;
}
bool CompilerCache::renameTempFileBinaryToProperName(const std::string &oldName, const std::string &kernelFileHash) {
return NEO::SysCalls::moveFileExA(oldName.c_str(), kernelFileHash.c_str(), MOVEFILE_REPLACE_EXISTING);
}
class HandleGuard : NonCopyableAndNonMovableClass {
public:
HandleGuard() = delete;
explicit HandleGuard(void *&h) : handle(h) {}
~HandleGuard() {
if (handle) {
unlockFileAndClose(handle);
}
}
private:
void *handle = nullptr;
};
static_assert(NonCopyableAndNonMovable<HandleGuard>);
void writeDirSizeToConfigFile(void *hConfigFile, size_t directorySize) {
DWORD sizeWritten = 0;
OVERLAPPED overlapped = {0};
auto result = NEO::SysCalls::writeFile(hConfigFile,
&directorySize,
(DWORD)sizeof(directorySize),
&sizeWritten,
&overlapped);
if (!result) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Writing to config file failed! error code: %lu\n", NEO::SysCalls::getProcessId(), SysCalls::getLastError());
} else if (sizeWritten != (DWORD)sizeof(directorySize)) {
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Writing to config file failed! Incorrect number of bytes written: %lu vs %lu\n", NEO::SysCalls::getProcessId(), sizeWritten, (DWORD)sizeof(directorySize));
}
}
bool CompilerCache::cacheBinary(const std::string &kernelFileHash, const char *pBinary, size_t binarySize) {
if (pBinary == nullptr || binarySize == 0 || binarySize > config.cacheSize) {
return false;
}
std::unique_lock<std::mutex> lock(cacheAccessMtx);
constexpr std::string_view configFileName = "config.file";
std::string configFilePath = joinPath(config.cacheDir, configFileName.data());
std::string cacheFileName = kernelFileHash + config.cacheFileExtension;
std::string cacheFilePath = getCachedFilePath(cacheFileName);
if (cacheFileName.length() < maxCacheDepth + config.cacheFileExtension.length()) {
DEBUG_BREAK_IF(true);
PRINT_STRING(NEO::debugManager.flags.PrintDebugMessages.get(), stderr, "PID %d [Cache failure]: Cache binary failed - cache file name is too short!\n", NEO::SysCalls::getProcessId());
return false;
}
UnifiedHandle hConfigFile{INVALID_HANDLE_VALUE};
size_t directorySize = 0u;
lockConfigFileAndReadSize(configFilePath, hConfigFile, directorySize);
if (std::get<void *>(hConfigFile) == INVALID_HANDLE_VALUE) {
return false;
}
HandleGuard configGuard(std::get<void *>(hConfigFile));
DWORD cacheFileAttr = 0;
cacheFileAttr = NEO::SysCalls::getFileAttributesA(cacheFilePath.c_str());
if ((cacheFileAttr != INVALID_FILE_ATTRIBUTES) &&
(SysCalls::getLastError() != ERROR_FILE_NOT_FOUND)) {
return true;
}
const size_t maxSize = config.cacheSize;
if (maxSize < (directorySize + binarySize)) {
uint64_t bytesEvicted{0u};
const auto evictSuccess = evictCache(bytesEvicted);
const auto availableSpace = maxSize - directorySize + bytesEvicted;
directorySize = std::max(static_cast<size_t>(0), directorySize - static_cast<size_t>(bytesEvicted));
if (!evictSuccess || binarySize > availableSpace) {
if (bytesEvicted > 0) {
writeDirSizeToConfigFile(std::get<void *>(hConfigFile), directorySize);
}
return false;
}
}
std::string tmpFileName = "cl_cache.XXXXXX";
std::string tmpFilePath = joinPath(config.cacheDir, tmpFileName);
if (!createUniqueTempFileAndWriteData(tmpFilePath.data(), pBinary, binarySize)) {
return false;
}
if (!createCacheDirectories(cacheFileName)) {
NEO::SysCalls::deleteFileA(tmpFilePath.c_str());
return false;
}
if (!renameTempFileBinaryToProperName(tmpFilePath, cacheFilePath)) {
NEO::SysCalls::deleteFileA(tmpFilePath.c_str());
return false;
}
directorySize += binarySize;
writeDirSizeToConfigFile(std::get<void *>(hConfigFile), directorySize);
return true;
}
} // namespace NEO
|