• XSS.stack #1 – первый литературный журнал от юзеров форума

Нужна помощь в кодинге c++

Onyx1050

(L3) cache
Пользователь
Регистрация
03.05.2024
Сообщения
175
Реакции
8
Изучаю вот эту статью https://xss.pro/threads/104114/ не получается разобраться в коде с ++ я понимаю там шаблон кода только подставлять свои значения, ноо я не понимаю как оно там функциклирует и работает весь тот код так еще нет опыта в написании и работе с кодом c++ нужна помощь опытного кодера по с++
 
In order to understand templates, one must become familiar with function overloading first. A function is "overloaded" if another function with the same name exists. Overloads are distinguished by the number of arguments, and their types.

Consider you want to write a function that calculates the maximum of two numbers, like this:

C++:
int max(int x, int y)
{
    return (x < y) ? y : x;
}

This code will work for integers and types that can be converted to integers. What happens if you want to get the maximum between two double values? You would have to write an overload:


C++:
double max(double x, double y)
{
    return (x < y) ? y: x;
}

Having to create overloads for each type of parameter we want to implement is a headache. That's why templates were introduced. Instead of manually crafting a set of nearly-identical functions, we create a single template. In a template, we specify a placeholder type. When the compiler sees you use such a function, it will generate an overload itself.


C++:
template <typename Type>
T max(Type x, Type y)
{
    return (x < y) ? y : x;
}

int main()
{
    // You specify <int> so the compiler knows what type you want to use
    // The compiler will generate the overload "int max(int x, int y)" and call it
    std::wcout << max<int>(2,3)
 
    // An overload specifying the type "double" will be generated
    std::wcout< max<double>(3.14, 2.72);
 
}

The idea is that we want the compiler to generate overloads for different data types itself, instead of us having to write "double max(double x, double y)" and "int max(double x, double y)" ourselves! All in all, instead of two functions, we wrote one! This is the exact motivation behind template usage in the thread you sent.

C++:
// Instead of writing these
//void memWrite(DWORD address, unsigned long value)
//{ 
//  Write an unsigned long
//    WriteProcessMemory(targetProc, (PVOID)address, &value, sizeof(unsigned long ), 0);
//}

//void memWrite(DWORD address, double value)
//{
//   WriteProcessMemory(targetProc, (PVOID)address, &value, sizeof(dataType), 0);
//}

// We only need to write this! And it works for all data types: int, long, unsigned long, etc. (excluding structures)
template<class dataType>
void memWrite(DWORD address, dataType value)
{
    WriteProcessMemory(targetProc, (PVOID)address, &value, sizeof(dataType), 0);
}


I hope this example helped you understand the idea better.
 
Последнее редактирование:
In order to understand templates, one must become familiar with function overloading first. A function is "overloaded" if another function with the same name exists. Overloads are distinguished by the number of arguments, and their types.

Consider you want to write a function that calculates the maximum of two numbers, like this:

C++:
int max(int x, int y)
{
    return (x < y) ? y : x;
}

This code will work for integers and types that can be converted to integers. What happens if you want to get the maximum between two double values? You would have to write an overload:


C++:
double max(double x, double y)
{
    return (x < y) ? y: x;
}

Having to create overloads for each type of parameter we want to implement is a headache. That's why templates were introduced. Instead of manually crafting a set of nearly-identical functions, we create a single template. In a template, we specify a placeholder type. When the compiler sees you use such a function, it will generate an overload itself.


C++:
template <typename Type>
T max(Type x, Type y)
{
    return (x < y) ? y : x;
}

int main()
{
    // You specify <int> so the compiler knows what type you want to use
    // The compiler will generate the overload "int max(int x, int y)" and call it
    std::wcout << max<int>(2,3)
 
    // An overload specifying the type "double" will be generated
    std::wcout< max<double>(3.14, 2.72);
 
}

The idea is that we want the compiler to generate overloads for different data types itself, instead of us having to write "double max(double x, double y)" and "int max(double x, double y)" ourselves! All in all, instead of two functions, we wrote one! This is the exact motivation behind template usage in the thread you sent.

C++:
// Instead of writing these
//void memWrite(DWORD address, unsigned long value)
//{
//  Write an unsigned long
//    WriteProcessMemory(targetProc, (PVOID)address, &value, sizeof(unsigned long ), 0);
//}

//void memWrite(DWORD address, double value)
//{
//   WriteProcessMemory(targetProc, (PVOID)address, &value, sizeof(dataType), 0);
//}

// We only need to write this! And it works for all data types: int, long, unsigned long, etc. (excluding structures)
template<class dataType>
void memWrite(DWORD address, dataType value)
{
    WriteProcessMemory(targetProc, (PVOID)address, &value, sizeof(dataType), 0);
}


I hope this example helped you understand the idea better.
Зашибись ты ему прогнал телегу про шаблоны а вот про это "DWORD address" ни слова, какие нах шаблоны, вы с основами разберитесь сначала. Парнишка взял экстремально дряной код и пытается как-то по нему чему-то учиться.
 
Народ поскажите как проделать вот эту всю оперрацию?
взято из этой сылки
https://xss.pro/threads/104114/
Далее начинается самое важное. Нам нужно получить дескриптор окна по его названию, чтобы далее получить идентификатор процесса, а уже с помощью идентификатора получить права доступа к процессу игры.

Давайте эти действия вынесем в отдельную функцию и назовем ее GetAccessProcess. Она будет принимать название окна процесса. P.S. Названия для переменных и функций давайте логичные, чтобы вам было понятно для чего они служит.

Хорошо, теперь при помощи функции из WinApi - FindWindowA найдем дескриптор окна по его названию и сохраним в нашу переменную targetWindow.
Документация по функции FindWindowA из MSDN.


C++:


targetWindow = FindWindowA(0, targetName);


Теперь сделаем проверку об успешном получении дескриптора окна:


C++:


if (targetWindow == NULL)
{
cout << "Не удалось найти окно игры!" << endl;
}


Если успешно смогли получить дескриптор окна приступаем к получению идентификатора(PID) процесса, для этого есть функция GetWindowThreadProcessId.
Документация по GetWindowThreadProcessId из MSDN.


C++:


GetWindowThreadProcessId(targetWindow, &pID);


Полученное значение записывается в переменную pID.
Далее так же нужно сделать проверку:


C++:


if (pID == 0)
{
cout << "Не удалось получить идентификатор процесса!" << endl;
}


При успешном получении идентификатора нам остается последний шаг - это получить права доступа для работы с целевым процессом. Делается это при помощи функции OpenProcess и значение записывается в targetProc.
Документация по OpenProcess из MSDN.


C++:


targetProc = OpenProcess(PROCESS_ALL_ACCESS, false, pID);


Делаем так же проверку, что права доступа получены:


C++:


if (!targetProc)
{
cout << "Не удалось получить права доступа!" << endl;
}


При успешном выполнении, мы получим полный доступ для работы с процессом. Имея доступ мы можем наконец взаимодействовать с памятью процесса, для чего и были сделаны все описанные выше действия.

Еще отмечу, чтобы было удобно нам работать с функциями чтения и записи в память, предлагаю создать шаблоны функций для этого. Шаблоны функций (function template) позволяют определять функции, которые не зависят от конкретных типов. Ведь в памяти могут храниться разные типы данных. Это нам сильно облегчит жизнь =) Создадим два шаблона функций memWrite(Запись в память) и memRead(Чтение из памяти).

Шаблон функции memWrite для записи в память:


C++:


template<class dataType>
void memWrite(DWORD address, dataType value)
{
WriteProcessMemory(hTargetProc, (PVOID)address, &value, sizeof(dataType), 0);
}


Функция memWrite, принимает адрес и значение, которое нужно записать по данному адресу в память. Сама запись происходит при помощи функции из WinApi - WriteProcessMemory.

Шаблон функции memRead для чтения из памяти:


C++:


template <class dataType>
dataType memRead(DWORD address)
{
dataType buffer;
ReadProcessMemory(hTargetProc, (PVOID)address, &buffer, sizeof(dataType), 0);
return buffer;
}

Функция memRead, будет принимать адрес из которого нужно прочитать данные. Прочитанные данные записываются в переменную buffer и возвращаются функцией туда, откуда вызвали memRead. Чтение происходит при помощи функции из WinApi – ReadProcessMemory.
 
Если бы ты прочитал внимательно, то понял бы, что я оставляю ссылки на MSDN для этих функций, если вдруг не будет понятно. Хотя я пытался писать текст очень понятно. Не знаю почему такие вопросы возникают... Может тебе бы стоило изучить сами основы программирования допустим на том же Це?
По сабжу:
При помощи функции из winApi: FindWindowA получаем дескриптор окна по ее названию передав в аргументы функции это название(игры/программы).
Далее при помощи полученного дескриптора ищем PID процесса с помощью функции GetWindowThreadProcessId передав туда дескриптор. Далее записываем значение в переменную PID.
 
Последнее редактирование:


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх