i want to stop search the net and think hard on this read the code and improve it this can be done better than what is now the offsets its meant to find from the strings are in the .data section but im not sure its finding the right thing #include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <tlhelp32.h>
#include
#include
#include <psapi.h>
// Function to log messages to console and file
void log_message(FILE* log_file, bool log_to_file, const char* format, ...) {
va_list args;
va_start(args, format);
vprintf(format, args);
if (log_to_file && log_file != NULL) {
vfprintf(log_file, format, args);
fflush(log_file);
}
va_end(args);
}
// Function to get process ID by name
DWORD get_process_id_by_name(const char* process_name, FILE* log_file) {
PROCESSENTRY32 pe32;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
code
if (hSnapshot == INVALID_HANDLE_VALUE) {
log_message(log_file, false, "Error: Unable to create tool help snapshot\n");
return 0;
}
pe32.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hSnapshot, &pe32)) {
CloseHandle(hSnapshot);
log_message(log_file, false, "Error: Unable to retrieve information on the first process\n");
return 0;
}
do {
char exeFile[MAX_PATH];
size_t converted_chars = 0;
wcstombs_s(&converted_chars, exeFile, MAX_PATH, pe32.szExeFile, _TRUNCATE);
if (_stricmp(exeFile, process_name) == 0) {
CloseHandle(hSnapshot);
log_message(log_file, false, "Process '%s' found with PID %u\n", process_name, pe32.th32ProcessID);
return pe32.th32ProcessID;
}
} while (Process32Next(hSnapshot, &pe32));
CloseHandle(hSnapshot);
log_message(log_file, false, "Error: Process '%s' not found\n", process_name);
return 0;
}
// Function to get the base address of the main module
unsigned long long get_base_address(DWORD pid, FILE* log_file) {
MODULEENTRY32 me32;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);
code
Assistant
if (hSnapshot == INVALID_HANDLE_VALUE) {
log_message(log_file, false, "Error: Unable to create module snapshot\n");
return 0;
}
me32.dwSize = sizeof(MODULEENTRY32);
if (!Module32First(hSnapshot, &me32)) {
CloseHandle(hSnapshot);
log_message(log_file, false, "Error: Unable to retrieve information on the first module\n");
return 0;
}
unsigned long long base_address = (unsigned long long)me32.modBaseAddr;
CloseHandle(hSnapshot);
log_message(log_file, false, "Base address of the main module: 0x%llx\n", base_address);
return base_address;
}
// Function to get section limits
bool get_section_limits(HANDLE hProcess, unsigned long long base_addr, const char* section_name, unsigned long long& section_start, unsigned long long& section_end) {
IMAGE_DOS_HEADER dos_header;
if (!ReadProcessMemory(hProcess, (LPCVOID)base_addr, &dos_header, sizeof(dos_header), NULL)) {
return false;
}
code
if (dos_header.e_magic != IMAGE_DOS_SIGNATURE) {
return false;
}
IMAGE_NT_HEADERS nt_headers;
if (!ReadProcessMemory(hProcess, (LPCVOID)(base_addr + dos_header.e_lfanew), &nt_headers, sizeof(nt_headers), NULL)) {
return false;
}
if (nt_headers.Signature != IMAGE_NT_SIGNATURE) {
return false;
}
IMAGE_SECTION_HEADER* section_headers = new IMAGE_SECTION_HEADER[nt_headers.FileHeader.NumberOfSections];
if (!ReadProcessMemory(hProcess, (LPCVOID)((unsigned long long)(base_addr + dos_header.e_lfanew) + sizeof(nt_headers)), section_headers, sizeof(IMAGE_SECTION_HEADER) * nt_headers.FileHeader.NumberOfSections, NULL)) {
delete[] section_headers;
return false;
}
for (int i = 0; i < nt_headers.FileHeader.NumberOfSections; ++i) {
if (strncmp((char*)section_headers[i].Name, section_name, IMAGE_SIZEOF_SHORT_NAME) == 0) {
section_start = base_addr + section_headers[i].VirtualAddress;
section_end = section_start + section_headers[i].Misc.VirtualSize;
delete[] section_headers;
return true;
}
}
delete[] section_headers;
return false;
}
// Function to find string in section
unsigned long long find_string_in_section(HANDLE hProcess, unsigned long long section_start, unsigned long long section_end, const char* string_to_search, FILE* log_file) {
unsigned long long string_addr = 0;
SIZE_T totalBytesSearched = 0;
unsigned long long addr = section_start;
code
while (addr < section_end) {
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQueryEx(hProcess, (LPCVOID)addr, &mbi, sizeof(mbi))) {
break;
}
if (mbi.State == MEM_COMMIT &&
(mbi.Protect == PAGE_READWRITE || mbi.Protect == PAGE_EXECUTE_READWRITE ||
mbi.Protect == PAGE_EXECUTE_WRITECOPY || mbi.Protect == PAGE_WRITECOPY ||
mbi.Protect == PAGE_READONLY || mbi.Protect == PAGE_EXECUTE_READ)) {
char* buffer = new char[mbi.RegionSize];
SIZE_T bytesRead;
if (ReadProcessMemory(hProcess, (LPCVOID)addr, buffer, mbi.RegionSize, &bytesRead) && bytesRead > 0) {
totalBytesSearched += bytesRead;
for (SIZE_T i = 0; i < bytesRead - strlen(string_to_search); i++) {
if (_strnicmp(buffer + i, string_to_search, strlen(string_to_search)) == 0) {
string_addr = addr + i;
delete[] buffer;
log_message(log_file, false, "Found string at address 0x%llx after searching %zu bytes\n", string_addr, totalBytesSearched);
return string_addr;
}
}
}
delete[] buffer;
}
addr += mbi.RegionSize;
log_message(log_file, false, "Searched memory region: 0x%llx - 0x%llx\n", (unsigned long long)mbi.BaseAddress, (unsigned long long)mbi.BaseAddress + mbi.RegionSize);
}
log_message(log_file, false, "Could not find string '%s' in section memory. Total bytes searched: %zu\n", string_to_search, totalBytesSearched);
return 0;
}
// Function to find load address
unsigned long long find_load_address(HANDLE hProcess, unsigned long long string_addr, unsigned long long section_start, unsigned long long section_end, FILE* log_file) {
SIZE_T totalBytesSearched = 0;
unsigned long long addr = section_start;
code
while (addr < section_end) {
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQueryEx(hProcess, (LPCVOID)addr, &mbi, sizeof(mbi))) {
break;
}
if (mbi.State == MEM_COMMIT &&
(mbi.Protect == PAGE_READWRITE || mbi.Protect == PAGE_EXECUTE_READWRITE ||
mbi.Protect == PAGE_EXECUTE_WRITECOPY || mbi.Protect == PAGE_WRITECOPY ||
mbi.Protect == PAGE_READONLY || mbi.Protect == PAGE_EXECUTE_READ)) {
unsigned char* buffer = new unsigned char[mbi.RegionSize];
SIZE_T bytesRead;
if (ReadProcessMemory(hProcess, (LPCVOID)addr, buffer, mbi.RegionSize, &bytesRead) && bytesRead > 0) {
totalBytesSearched += bytesRead;
for (SIZE_T i = 0; i < bytesRead - sizeof(unsigned long long); i++) {
unsigned long long* potential_ptr = (unsigned long long*)(buffer + i);
if (*potential_ptr == string_addr) {
unsigned long long load_addr = addr + i;
delete[] buffer;
log_message(log_file, false, "Found potential load address at 0x%llx after searching %zu bytes\n", load_addr, totalBytesSearched);
return load_addr;
}
}
}
delete[] buffer;
}
addr += mbi.RegionSize;
log_message(log_file, false, "Searched memory region: 0x%llx - 0x%llx\n", (unsigned long long)mbi.BaseAddress, (unsigned long long)mbi.BaseAddress + mbi.RegionSize);
}
log_message(log_file, false, "Could not find load address for string at 0x%llx. Total bytes searched: %zu\n", string_addr, totalBytesSearched);
return 0;
FILE* log_file;
if (fopen_s(&log_file, "memscan.log", "w") != 0) {
printf("Could not open log file for writing\n");
return 1;
}
time_t t = time(NULL);
struct tm tm;
localtime_s(&tm, &t);
log_message(log_file, false, "Memory scan started at: %04d-%02d-%02d %02d:%02d:%02d\n",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
DWORD pid = get_process_id_by_name(process_name, log_file);
if (pid == 0) {
log_message(log_file, false, "Could not find process '%s'\n", process_name);
fclose(log_file);
return 1;
}
unsigned long long base_addr = get_base_address(pid, log_file);
if (base_addr == 0) {
log_message(log_file, false, "Could not get base address of process '%s'\n", process_name);
fclose(log_file);
return 1;
}
HANDLE hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
if (hProcess == NULL) {
log_message(log_file, false, "Could not open process %d. Error: %lu\n", pid, GetLastError());
fclose(log_file);
return 1;
}
unsigned long long data_section_start, data_section_end;
if (!get_section_limits(hProcess, base_addr, ".data", data_section_start, data_section_end)) {
log_message(log_file, false, "Could not find .data section in process\n");
CloseHandle(hProcess);
fclose(log_file);
return 1;
}
unsigned long long rdata_section_start, rdata_section_end;
if (!get_section_limits(hProcess, base_addr, ".rdata", rdata_section_start, rdata_section_end)) {
log_message(log_file, false, "Could not find .rdata section in process\n");
CloseHandle(hProcess);
fclose(log_file);
return 1;
}
fprintf(log_file, "$gameSettings = [\n");
for (const char* string_to_search : gameSettings) {
unsigned long long string_addr = find_string_in_section(hProcess, data_section_start, data_section_end, string_to_search, log_file);
if (string_addr == 0) {
string_addr = find_string_in_section(hProcess, rdata_section_start, rdata_section_end, string_to_search, log_file);
if (string_addr == 0) {
log_message(log_file, false, "String '%s' not found\n", string_to_search);
continue;
}
}
log_message(log_file, false, "Found string '%s' at address 0x%llx\n", string_to_search, string_addr);
unsigned long long load_addr = find_load_address(hProcess, string_addr, data_section_start, data_section_end, log_file);
if (load_addr == 0) {
load_addr = find_load_address(hProcess, string_addr, rdata_section_start, rdata_section_end, log_file);
if (load_addr == 0) {
log_message(log_file, false, "Could not find address that loads string '%s'\n", string_to_search);
continue;
}
}
log_message(log_file, false, "Found address that loads string '%s' at address 0x%llx\n", string_to_search, load_addr);
unsigned long long func_ptr = load_addr - 0x10;
log_message(log_file, false, "Function pointer: 0x%llx\n", func_ptr);
unsigned long long offset = func_ptr - base_addr;
fprintf(log_file, " \"%s\" => 0x%llx,\n", string_to_search, offset);
}
fprintf(log_file, "];\n");
CloseHandle(hProcess);
t = time(NULL);
localtime_s(&tm, &t);
log_message(log_file, false, "Memory scan ended at: %04d-%02d-%02d %02d:%02d:%02d\n",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
fclose(log_file);
return 0;
}
Certainly! Let's go through your code systematically to identify potential improvements, optimizations, and corrections to ensure it functions as intended. Below are detailed observations and recommendations:
1. Logging Function (log_message) Issues
Problem:
Your log_message function uses va_list for both vprintf and vfprintf without resetting or copying the va_list. Once va_list is consumed by vprintf, it cannot be reused by vfprintf, leading to undefined behavior.
Solution:
Use va_copy to create a copy of the va_list before using it multiple times. This ensures each logging operation gets a fresh copy.
Updated log_message Function:
cpp
#include <cstdarg>
// Function to log messages to console and file
void log_message(FILE* log_file, bool log_to_file, const char* format, ...) {
va_list args;
va_start(args, format);
// Print to console
vprintf(format, args);
if (log_to_file && log_file != NULL) {
// Make a copy of args for vfprintf
va_list args_copy;
va_copy(args_copy, args);
vfprintf(log_file, format, args_copy);
va_end(args_copy);
fflush(log_file);
}
va_end(args);
}
2. Handling String Encodings
Problem:
Your current implementation assumes that strings in the target process are ASCII or ANSI encoded. However, many Windows applications, including modern games like Fallout 76, may use Unicode (UTF-16) encoding for strings.
Solution:
Modify your search functions to handle wide strings (wchar_t) if the target process uses Unicode encoding. Alternatively, you can search for both ANSI and Unicode strings based on what you expect.
Approach:
Determine Encoding: Confirm the encoding used by Fallout76.exe. Tools like Dependency Walker or Process Explorer can help inspect the process's loaded strings.
Implement Both Searches: Implement search functions for both ANSI and Unicode strings. Here's an example of how you can modify the find_string_in_section function to handle both encodings.
Updated find_string_in_section Function:
cpp
unsigned long long find_string_in_section(
HANDLE hProcess,
unsigned long long section_start,
unsigned long long section_end,
const char* string_to_search,
bool is_unicode,
FILE* log_file)
{
unsigned long long string_addr = 0;
SIZE_T totalBytesSearched = 0;
unsigned long long addr = section_start;
size_t search_length = is_unicode ? wcslen((wchar_t*)string_to_search) * sizeof(wchar_t) : strlen(string_to_search);
while (addr < section_end) {
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQueryEx(hProcess, (LPCVOID)addr, &mbi, sizeof(mbi))) {
break;
}
if (mbi.State == MEM_COMMIT &&
(mbi.Protect == PAGE_READWRITE || mbi.Protect == PAGE_EXECUTE_READWRITE ||
mbi.Protect == PAGE_EXECUTE_WRITECOPY || mbi.Protect == PAGE_WRITECOPY ||
mbi.Protect == PAGE_READONLY || mbi.Protect == PAGE_EXECUTE_READ))
{
BYTE* buffer = new BYTE[mbi.RegionSize];
SIZE_T bytesRead;
if (ReadProcessMemory(hProcess, (LPCVOID)addr, buffer, mbi.RegionSize, &bytesRead) && bytesRead > 0) {
totalBytesSearched += bytesRead;
for (SIZE_T i = 0; i <= bytesRead - search_length; i += is_unicode ? 2 : 1) {
if (is_unicode) {
if (wcsncmp((wchar_t*)(buffer + i), (wchar_t*)string_to_search, wcslen((wchar_t*)string_to_search)) == 0) {
string_addr = addr + i;
delete[] buffer;
log_message(log_file, false, "Found Unicode string at address 0x%llx after searching %zu bytes\n", string_addr, totalBytesSearched);
return string_addr;
}
} else {
if (strncmp((char*)(buffer + i), string_to_search, strlen(string_to_search)) == 0) {
string_addr = addr + i;
delete[] buffer;
log_message(log_file, false, "Found ANSI string at address 0x%llx after searching %zu bytes\n", string_addr, totalBytesSearched);
return string_addr;
}
}
}
}
delete[] buffer;
}
addr += mbi.RegionSize;
log_message(log_file, false, "Searched memory region: 0x%llx - 0x%llx\n", (unsigned long long)mbi.BaseAddress, (unsigned long long)mbi.BaseAddress + mbi.RegionSize);
}
log_message(log_file, false, "Could not find string '%s' in section memory. Total bytes searched: %zu\n", string_to_search, totalBytesSearched);
return 0;
}
Usage in main:
You need to specify whether each string is Unicode or ANSI. If unsure, you might need to try both.
Problem:
Both find_string_in_section and find_load_address perform similar region-by-region searches, which can be inefficient.
Solution:
Implement a generalized memory scanning function or reuse code to reduce redundancy. Additionally, consider reading larger blocks or using more efficient search algorithms like the Boyer-Moore algorithm for faster string searching.
Example:
You can abstract the memory scanning into a single function that takes a callback or a pattern matching lambda.
However, for simplicity, ensuring that find_string_in_section and find_load_address are as optimized as possible is key. Caching the read memory regions or parallelizing searches could also help, but be cautious with thread safety and synchronization.
4. Understanding and Correcting Offset Calculations
Problem:
The logic behind calculating func_ptr as load_addr - 0x10 is unclear. Offsets should be derived based on known patterns or structures within the target process's memory.
Solution:
Ensure that the offset subtraction (- 0x10) correctly aligns with the function structure or the data structure referencing the string. This magic number should be justified with context from the target application. If possible, use symbols or debug information to calculate these offsets more accurately.
Recommendation:
Instead of using hardcoded offsets, consider:
Analyzing the disassembly of the target process to understand how strings are referenced.
Using signature scanning to find specific patterns near the string references.
Employing debugging tools or frameworks to dynamically determine these offsets.
Example Correction:
If 0x10 is supposed to align with a known instruction or structure, ensure it's consistently applicable across all target scenarios.
cpp
// Example: Determine offset based on analysis
const long long OFFSET_ADJUSTMENT = 0x10; // Ideally, this should be based on analysis
unsigned long long func_ptr = load_addr - OFFSET_ADJUSTMENT;
5. Handling Different Architectures (32-bit vs. 64-bit)
Problem:
The code assumes a 64-bit architecture by using unsigned long long for addresses and pointers. If the target process is 32-bit, this will lead to incorrect address calculations.
Solution:
Determine the architecture of the target process and adjust the data types accordingly. You can use the IsWow64Process function to check if a process is running under WOW64 (i.e., a 32-bit process on a 64-bit OS).
Implementation:
Add a function to determine if the target process is 64-bit or 32-bit.
cpp
bool is_process_64_bit(HANDLE hProcess, bool& is64Bit) {
BOOL bIsWow64 = FALSE;
if (!IsWow64Process(hProcess, &bIsWow64)) {
return false;
}
SYSTEM_INFO systemInfo;
GetNativeSystemInfo(&systemInfo);
if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ||
systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64) {
is64Bit = !bIsWow64;
}
else {
is64Bit = false; // Assuming 32-bit if not AMD64 or ARM64
}
return true;
}
Usage in main:
Adjust address types based on architecture.
cpp
bool is64Bit = false;
if (!is_process_64_bit(hProcess, is64Bit)) {
log_message(log_file, false, "Failed to determine process architecture.\n");
// Handle accordingly
}
typedef uintptr_t address_t;
Throughout your code, replace unsigned long long with address_t to handle both 32-bit and 64-bit addresses seamlessly.
6. Error Handling and Resource Management
Recommendations:
Ensure All Handles Are Closed Properly:
Utilize RAII (Resource Acquisition Is Initialization) principles to manage handles and memory automatically, reducing the risk of leaks.
Check Return Values:
Always check the return values of functions like ReadProcessMemory, VirtualQueryEx, Module32First, etc., and handle errors appropriately.
Use Smart Pointers:
For dynamic memory allocations, consider using smart pointers like std::unique_ptr to manage memory automatically.
Example:
Using std::unique_ptr for section headers.
cpp
#include <memory>
// ...
std::unique_ptr<IMAGE_SECTION_HEADER[]> section_headers(new IMAGE_SECTION_HEADER[nt_headers.FileHeader.NumberOfSections]));
if (!ReadProcessMemory(
hProcess,
(LPCVOID)((unsigned long long)(base_addr + dos_header.e_lfanew) + sizeof(nt_headers)),
section_headers.get(),
sizeof(IMAGE_SECTION_HEADER) * nt_headers.FileHeader.NumberOfSections,
NULL))
{
return false;
}
// No need to delete manually
7. Enhancing main Function Structure
Recommendations:
Modularize the Code:
Break down the main function into smaller, reusable functions to improve readability and maintainability.
Add Detailed Comments:
Explain each step and the reasoning behind calculations, especially for critical operations like offset calculations.
Validate Offsets:
After calculating offsets, validate them to ensure they point to meaningful memory locations or functions.
Refactored main Example:
cpp
int main() {
const char* process_name = "Fallout76.exe";
const char* gameSettings[] = { /* Your strings */ };
const size_t numSettings = sizeof(gameSettings) / sizeof(gameSettings[0]);
FILE* log_file;
if (fopen_s(&log_file, "memscan.log", "w") != 0) {
printf("Could not open log file for writing\n");
return 1;
}
// Log start time
// ...
DWORD pid = get_process_id_by_name(process_name, log_file);
if (pid == 0) {
// Handle error
}
unsigned long long base_addr = get_base_address(pid, log_file);
if (base_addr == 0) {
// Handle error
}
HANDLE hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
if (hProcess == NULL) {
// Handle error
}
bool is64Bit = false;
if (!is_process_64_bit(hProcess, is64Bit)) {
log_message(log_file, false, "Failed to determine process architecture.\n");
CloseHandle(hProcess);
fclose(log_file);
return 1;
}
unsigned long long data_section_start, data_section_end;
if (!get_section_limits(hProcess, base_addr, ".data", data_section_start, data_section_end)) {
// Handle error
}
unsigned long long rdata_section_start, rdata_section_end;
if (!get_section_limits(hProcess, base_addr, ".rdata", rdata_section_start, rdata_section_end)) {
// Handle error
}
fprintf(log_file, "$gameSettings = [\n");
for (size_t i = 0; i < numSettings; ++i) {
const char* string_to_search = gameSettings[i];
unsigned long long string_addr = find_string_in_section(hProcess, data_section_start, data_section_end, string_to_search, false, log_file);
if (string_addr == 0) {
// Optionally, try Unicode search
string_addr = find_string_in_section(hProcess, rdata_section_start, rdata_section_end, string_to_search, false, log_file);
if (string_addr == 0) {
log_message(log_file, false, "String '%s' not found\n", string_to_search);
continue;
}
}
// Find load address
unsigned long long load_addr = find_load_address(hProcess, string_addr, data_section_start, data_section_end, log_file);
if (load_addr == 0) {
load_addr = find_load_address(hProcess, string_addr, rdata_section_start, rdata_section_end, log_file);
if (load_addr == 0) {
log_message(log_file, false, "Could not find address that loads string '%s'\n", string_to_search);
continue;
}
}
// Calculate function pointer and offset
const long long OFFSET_ADJUSTMENT = 0x10; // Justify this value
unsigned long long func_ptr = load_addr - OFFSET_ADJUSTMENT;
unsigned long long offset = func_ptr - base_addr;
fprintf(log_file, " \"%s\" => 0x%llx,\n", string_to_search, offset);
}
fprintf(log_file, "];\n");
// Log end time
// ...
CloseHandle(hProcess);
fclose(log_file);
return 0;
}
8. Verifying and Testing
Recommendations:
Unit Testing: Create unit tests for your functions, especially find_string_in_section and find_load_address, using mock processes or memory regions to ensure they work as expected.
Use Debugging Tools: Attach a debugger to Fallout76.exe to verify that the addresses and offsets your tool identifies are correct.
Validate Results: Cross-reference the found offsets with known structures or configuration files within the game to ensure accuracy.
9. Additional Enhancements
Concurrency: Implement multi-threading to search multiple sections or strings in parallel, reducing overall scan time.
Progress Reporting: Provide more detailed progress logs or a progress bar for long-running scans.
Configuration File: Allow specifying process names, strings to search, and other parameters via a configuration file or command-line arguments for greater flexibility.
Error Resilience: Implement retry mechanisms or fallback strategies if certain memory regions cannot be read due to access restrictions.
10. Final Improved Code
Here's a consolidated version of the critical parts of your code with the discussed improvements. Due to space constraints, not all functions are fully included, but key functions like log_message and find_string_in_section are updated.
cpp
11. Final Thoughts
By addressing the above points, your program will become more robust, efficient, and accurate in finding the desired offsets. Ensure thorough testing against the target process to validate the correctness of each component.
If you need further assistance with specific parts of the code or additional features, feel free to ask!