Можно ли улучшить этот код на C++: #include "pch.h" #include <Windows.h> #include…
- User
Можно ли улучшить этот код на C++: #include "pch.h" #include <Windows.h> #include <tlhelp32.h> #include <psapi.h> #include #include #include #include #include #include #include #include #include
// Specialization for managing HANDLEs through smart pointer struct HandleDeleter { void operator()(HANDLE handle) { if (handle != NULL && handle != INVALID_HANDLE_VALUE) { CloseHandle(handle); } } }; using UniqueHandle = std::unique_ptr<std::remove_pointer::type, HandleDeleter>;
// RAII class for memory protection management class ScopedVirtualProtect { public: ScopedVirtualProtect(HANDLE hProcess, LPCVOID addr, SIZE_T size, DWORD newProtect) : m_hProcess(hProcess), m_addr(const_cast(addr)), m_size(size), m_oldProtect(0) { if (!VirtualProtectEx(hProcess, m_addr, m_size, newProtect, &m_oldProtect)) { throw std::runtime_error("VirtualProtectEx failed to change protection."); } }
// On object destruction, restore old protection without throwing exceptions ~ScopedVirtualProtect() noexcept { DWORD temp; VirtualProtectEx(m_hProcess, m_addr, m_size, m_oldProtect, &temp); }private: HANDLE m_hProcess; LPVOID m_addr; SIZE_T m_size; DWORD m_oldProtect; };
// Logging class class Logger { public: explicit Logger(const std::string& filename) : m_logFile(filename, std::ios::app) { if (!m_logFile.is_open()) { throw std::runtime_error("Failed to open the log file."); } }
void Log(const std::string& message) { std::lock_guard<std::mutex> lock(m_mutex); // Protect from thread racing m_logFile << message << "\n"; }private: std::mutex m_mutex; // Mutex for synchronized writing to the log file std::ofstream m_logFile; };
Logger g_logger("patcher_log.txt");
std::string PtrToStr(const void* ptr) { std::stringstream ss; ss << "0x" << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << reinterpret_cast<uintptr_t>(ptr); return ss.str(); }
bool ApplyPatch(HANDLE hProcess, BYTE* addr, size_t offset, BYTE patchByte) { ScopedVirtualProtect protect(hProcess, addr + offset, 1, PAGE_EXECUTE_READWRITE); SIZE_T bytesWritten; if (!WriteProcessMemory(hProcess, addr + offset, &patchByte, 1, &bytesWritten)) { g_logger.Log("Failed to write the patch at " + PtrToStr(addr + offset) + "."); return false; }
g_logger.Log("Patch applied successfully at " + PtrToStr(addr + offset) + "."); return true;}
bool PatchSignatureInProcessMemory(HANDLE hProcess, const std::vector& signature, BYTE patchByte) { MEMORY_BASIC_INFORMATION mbi{}; std::vector buffer; for (BYTE* addr = nullptr; VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi)) && reinterpret_cast<uintptr_t>(addr) < 0x7FFFFFFF; addr += mbi.RegionSize) { if (mbi.State != MEM_COMMIT || (mbi.Protect != PAGE_EXECUTE_READWRITE && mbi.Protect != PAGE_EXECUTE_READ)) { continue; }
// Reuse the buffer if it’s not large enough if (buffer.size() < mbi.RegionSize) { buffer.resize(mbi.RegionSize); } SIZE_T bytesRead; if (!ReadProcessMemory(hProcess, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) { continue; } for (size_t j = 0; j <= bytesRead - signature.size(); ++j) { if (memcmp(buffer.data() + j, signature.data(), signature.size()) == 0) { if (ApplyPatch(hProcess, addr, j + signature.size() - 1, patchByte)) { g_logger.Log("Signature found and patched at " + PtrToStr(addr + j) + "."); return true; } } } } g_logger.Log("No signature matched for patching."); return false; - Assistant
Ваш код является функциональным и служит конкретной цели, но есть несколько моментов и предложений, которые можно учесть для его улучшения. Предложения по улучшению:
- User
Отправь исправленный код с учетом твоих советов (кроме пункта под номером 8). Для улучшения логирования перед каждым сообщением, которое будет записываться в файл, добавь в начало этого сообщения текущее время вида час:минута:секунда в 24 часовом формате и символ ">" Пример: 19:56:03 > Failed to open the target process.
- Assistant
- User
Отлично, теперь добавь в этот код комментарии, для лучшего понимания происходящего.
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.