How to read data in a specific memory address in c++ - c++

I have created an integer variable using the following code in first.cpp:
#include <iostream>
using namespace std;
int main()
{
int myvar = 10;
cout << &myvar;
// I only need two steps above.
// The following steps are coded to make this program run continuously.
cout << "Enter your name" << endl;
string name;
cin >> name;
return 0;
}
Output of first.cpp is:
>0x6dfed4
While the above program is running, I also run the following program in second.cpp:
#include <iostream>
using namespace std;
int main()
{
// I this program I want to read the content in myvar variable in first.cpp
// How to do it ?
}
Using the second program, I want to read the content of the myvar variable in first.cpp.
How to do it ?
Thank you.

To elaborate on my comment above:
As I wrote each program will run in a different process.
Each process has a separate adddress space.
Therefore using the address of a variable in another process doesn't make any sense.
In order to communicate between processes, you need some kind of IPC (inter-process communication):
Inter-process communication
If you only need to share a variable, the first mechanism that comes to mind is to use shared memory:
Shared memory
Shared-memory is very much OS dependent.
You didn't mention which OS you are using.
On Windows you can use Win API for managing shared memory:
Windows shared memory
There's an equivalent on Linux, but I am not familiar with the details.
Alternatively you can use the boost solution which is cross platform:
boost shared memory
If you'll delve into that it will be clear that these kind of solutions comes with some compilcations.
So the question is why do you need to do it ? Maybe there's a better solution to your problem
(you haven't described what it actually is, so there's not much more I can say).

Related

Do i need to make a new main function for every thing i do? C++

Intro
Hello! I recently started learning C++. I stopped learning python, because it didn't interest me that much as C++. I am a completely beginner in C++.
Context
My question is that do I need to make a main function for every thing I do?
For example, to print something
#include <iostream>
int main()
{
std::cout <<"Hello World!;
}
So I made it print "Hello World!".
Let's say for something similar do I need to make a new int main()? Or is everything going to be contained inside main()?
Sorry if I made this complicated, every answer is appreciated!
You don't need another main() function.
int main() is the entry point to your program. It is called immediately after initialization of any statically allocated variables.
You should write another function, let's name it add(), and call it from within main(). This lets you split your code up into smaller chunks that are more easily writeable, readable and maintainable.
For example:
We want a program that will print "Hello World!" to the console, then call another function that could print something else.
#include iostream
int main() {
std::cout << "Hello World" << endl; //endl designates the end of a line
printSomethingElse();
}
do i need to make a main function for every thing I do?
No, you do not need to have a main() for everything you do. You just need to have a main() to run your source code.
The main() function is your entry-point into your program in C++; unlike Python which is executed (or run/interpreted) top-down.
For modules like console applications, applications using windows or widgets, dynamic link libraries (Windows) or shared libraries (Linux), you need exactly one main-function. But not for static libraries. Static libraries are linked statically and don't need a main function. They are just collections of functions without a main entry point.
Regards

How can I open several images from a C++ program using terminal commands?

I need to open several images from a website generating the url of the image with a for cycle - all the urls look the same but for the final number.
system("open") works fine for a single url, but I don't know how to pass the variable referring to the number of the image inside the command, being it a string.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
for (int i = 1; i <= 13; i++)
{
system("open http://www.site/images/image-[how do I pass i here??].jpg");
}
}
[Edit] I'm working on MacOS.
You should build dynamically the C string passed to system.
For example:
for (int i=1; i<=13; i++) {
char cmdbuf[80];
snprintf(cmdbuf, sizeof(cmdbuf), "open http://www.site/images/image-%d.jpg", i);
int notok = system(cmdbuf);
if (notok) break;
}
the above is actually C code (which, with appropriate #include-s, would work in C++). If you want genuine C++ code you might use some std::ostringstream to build some std::string (and convert it into a C string using its c_str member function before passing that to system)
Read about snprintf in C and in C++. C and C++ are different languages.
In C++, std::system is provided with <cstdlib> (which you should use instead of <stdlib.h> which is a C standard header).
BTW, you might be interested by HTTP server libraries such as libonion and by HTTP client libraries such as libcurl. You'll better understand much more about the HTTP protocol.
Your above program is better and faster written as a shell script. For your particular case it would be faster (to write), and more robust (even if perhaps it runs a few milliseconds slower). Notice that open is not a standard POSIX program (on Linux, you would use xdg-open instead) and might not exist on Windows (which I don't know at all).
Notice also that neither the C standard nor the POSIX standard guarantee that the user of your program has a screen. If you run your program on some datacenter machine, you might be disappointed.

How to know if std::cin is from redirect?

Let's say I have a small program like:
int main()
{
cout << "Please enter the param >" << endl; // <-- Print only if input from console
std::string param;
cin >> param;
//Doing some calculations...
cout << "result is..."
}
I want to print the request for the parameter only if the input is from the console, but if the program was started with redirect myApp.exe < textfile.txt then I see no point in printing it.
How can I achieve this behavior?
Edit - I'm working on windows.
This answer is based on #JoachimPileborg comment
#include <io.h>
#include <stdio.h>
bool isInputRedirected()
{
return (!(_isatty(_fileno(stdin))))
}
Original source in MSDN
The technical means of detecting redirection depends on the operating system: the C++ standard library has no functionality for that, and AFAIK (though I could be mistaken) neither have Boost.
The best you can do portably is to provide ways for the program invoker to tell it whether it should offer an interactive interface, passing the responsibility to the part that knows enough to take it on.
For examnple, you can use program arguments, and/or you can structure the main functionality as a library invoked from two different front-end programs.

Calling a function from a remote process using injected DLL

I saw a similar, but still different question to this, so just to clarify this is not a dupe of 13428881 (Calling a function in an injected DLL).
What I have at the minute:
A DLL, injected into a target process, displaying a message box and fiddling around doing math.
What I want in the future:
A DLL which can manipulate and toy with the internals of the target process.
The next step towards achieving the desired manipulation is to call a method in a remote thread within the process I'm injecting into.
Let's take an example:
I have a C++ application, which has int main, let's say it looks like this:
int PrintText(string text)
{
cout << text;
return 1;
}
int main()
{
while (true)
{
PrintText("From the DLL");
}
}
Ok, so that's lovely, my target application is currently printing some text, and it seems to be doing so very happily. It's spamming it at an unbelievable rate, but I can slow it down using threads and sleeps etc if I need to. The fact is this isn't an issue, the code here hasn't been compiled or tested, and I've no intention of using this exact code. I'm actually working with a game.
Now, let's say I create a pointer to the method, PrintText, and that I know the address of it within that process. How do I go about calling it, externally, passing in arguments?
Locally, I believe it would look something like this:
int i;
int (*PrintSomeText)(string) = PrintText;
I could then call this function using a reference, like so:
i = operation("Text to be printed", PrintSomeText);
This should, by my theory, declare an integer called i, then define a pointer to a method which returns int, takes one string as a parameter, and the pointer stores the value of the pointer which was in PrintText. (Or something of that nature).
Very nice, so I can call my own functions via pointer, that's great, cracking in fact. I've truly astonished myself with this ability, and I do now feel like superman. I'll go save some babies or something, brb.
Back, so now I want to continue a little further, and take that next step. Let's say I know that the the method is at the address 100 in the target process (decimal, I will likely do it in hexadecimal, as I'm using CheatEngine / OllyDBG to find methods in the target process, but for this example we'll stay simple).
I presume that my injected DLL gets its own space entirely, does it have any higher access to the target process? How can I find this out?
Thanks for your time,
Josh
Edit: A small note, I'm going through the C++ tutorial book, and it's proven so far to be very useful. I've noticed that I forgot to include my operation method, so apologies for that being missing. If it's required, let me know. Thanks!
Edit nr 2: I've just made some compilable code to test this out, since I wrote most of this free hand reading from the book without an IDE, and the IDE has finally configured itself, so here is the code I'm currently working with
#include "stdafx.h"
#include <iostream>
using namespace std;
int PrintText(char * Text)
{
cout << Text << endl;
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
int (*Print)(char*) = PrintText;
char Text[] = "Hello, world!";
PrintText(Text);
int x = (*Print)("Oh my word, it really works!");
cin.get();
return 0;
}
Note I haven't yet made it run indefinitely, so yeah, please excuse that, I'll add it shortly.
Dauphic is pretty much bang on, I have full control, as wildly was I'd like, to the target process. So, here's what I'm doing to call the target processes method (for any future readers interest):
Locate the method in memory. To do this, I first disabled ASLR (Address space layout randomization), then created a pointer to my method locally within the target program, before using the iostream to dump the pointer to screen, now I know the address of the method.
Create a typedef in the dll to be injected. This is where I got kinda stuck, but I know some guys who do this quite a lot, so I've managed to get it out of them. In my case, this is how the typedef looks:
typedef int __printPrototype(char* text);
Bind the address of the method in the target application, to a reproduction of it in the injected dll:
int (*Print)(char*);
Print = (__printPrototype*)0x0041121C;
Print("I'm injecting myself into you.");
Perfect!
Thanks to dauphic and a good friend named DarkstaR.

How to return the name of a variable stored at a particular memory address in C++

first time posting here after having so many of my Google results come up from this wonderful site.
Basically, I'd like to find the name of the variable stored at a particular memory address. I have a memory editing application I wrote that edits a single value, the problem being that every time the application holding this value is patched, I have to hardcode in the new memory address into my application, and recompile, which takes so much time to upkeep that its almost not worthwhile to do.
What I'd like to do is grab the name of the variable stored at a certain memory address, that way I can then find its address at runtime and use that as the memory address to edit.
This is all being written in C++.
Thanks in advance!
Edit:
Well I've decided I'd like to stream the data from a .txt file, but I'm not sure how to convert the string into an LPVOID for use as the memory address in WriteProcessMemory(). This is what I've tried:
string fileContents;
ifstream memFile("mem_address.txt");
getline(memFile, fileContents);
memFile.close();
LPVOID memAddress = (LPVOID)fileContents.c_str();
//Lots of code..
WriteProcessMemory(WindowsProcessHandle, memAddress, &BytesToBeWrote, sizeof(BytesToBeWrote), &NumBytesWrote);
The code is all correct in terms of syntax, it compiles and runs, but the WriteProcessMemory errors and I can only imagine it has to do with my faulty LPVOID variable. I apologize if extending the use of my question is against the rules, I'll remove my edit if it is.
Compile and generate a so called map file. This can be done easily with Visual-C++ (/MAP linker option). There you'll see the symbols (functions, ...) with their starting address. Using this map file (Caution: has to be updated each time you recompile) you can match the addresses to names.
This is actually not so easy because the addresses are relative to the preferred load address, and probably will (randomization) be different from the actual load address.
Some old hints on retrieving the right address can be found here: http://home.hiwaay.net/~georgech/WhitePapers/MapFiles/MapFiles.htm
In general, the names of variables are not kept around when the program is compiled. If you are in control of the compilation process, you can usually configure the linker and compiler to produce a map-file listing the locations in memory of all global variables. However, if this is the case, you can probably acheive your goals more easily by not using direct memory accesses, but rather creating a proper command protocol that your external program can call into.
If you do not have control of the compilation process of the other program, you're probably out of luck, unless the program shipped with a map file or debugging symbols, either of which can be used to derive the names of variables from their addresses.
Note that for stack variables, deriving their names will require full debugging symbols and is a very non-trivial process. Heap variables have no names, so you will have no luck there, naturally. Further, as mentioned in #jdehaan's answer, map files can be a bit tricky to work with in the best of times. All in all, it's best to have a proper control protocol you can use to avoid any dependence on the contents of the other program's memory at all.
Finally, if you have no control over the other program, then I would recommend putting the variable location into a separate datafile. This way you would no longer need to recompile each time, and could even support multiple versions of the program being poked at. You could also have some kind of auto-update service pulling new versions of this datafile from a server of yours if you like.
Unless you actually own the application in question, there is no standard way to do this. If you do own the application, you can follow #jdehaan answer.
In any case, instead of hardcoding the memory address into your application, why not host a simple feed somewhere that you can update at any time with the memory address you need to change for each version of the target application? This way, instead of recompiling your app every time, you can just update that feed when you need to be able to manipulate a new version.
You cannot directly do this; variable names do not actually exist in the compiled binary. You might be able to do that if the program was written, in say, Java or C#, which do store information about variables in the compiled binary.
Further, this wouldn't in general be possible, because it's always possible that the most up to date copy of a value inside the target program is located inside of a CPU register rather than in memory. This is more likely if the program in question is compiled in release mode, with optimizations turned on.
If you can ensure the target program is compiled in debug mode you should be able to use the debugging symbols emitted by the compiler (the .pdb file) in order to map addresses to variables, but in that case you would need to launch the target process as if it were being debugged -- the plain Read Process Memory and Write Process Memory methods would not work.
Finally, your question ignores a very important consideration -- there need not be a variable corresponding to a particular address even if such information is stored.
If you have the source to the app in question and optimal memory usage is not a concern, then you can declare the interesting variables inside a debugging-friendly structure similar to:
typedef struct {
const char head_tag[15] = "VARIABLE_START";
char var_name[32];
int value;
const char tail_tag[13] = "VARIABLE_END";
} debuggable_int;
Now, your app should be able to search through the memory space for the program and look for the head and tail tags. Once it locates one of your debuggable variables, it can use the var_name and value members to identify and modify it.
If you are going to go to this length, however, you'd probably be better off building with debugging symbols enabled and using a regular debugger.
Billy O'Neal started to head in the right direction, but didn't (IMO) quite get to the real target. Assuming your target is Windows, a much simpler way would be to use the Windows Symbol handler functions, particularly SymFromName, which will let you supply the symbol's name, and it will return (among other things) the address for that symbol.
Of course, to do any of this you will have to run under an account that's allowed to do debugging. At least for global variables, however, you don't necessarily have to stop the target process to find symbols, addresses, etc. In fact, it works just fine for a process to use these on itself, if it so chooses (quite a few of my early experiments getting to know these functions did exactly that). Here's a bit of demo code I wrote years ago that gives at least a general idea (though it's old enough that it uses SymGetSymbolFromName, which is a couple of generations behind SymFromName). Compile it with debugging information and stand back -- it produces quite a lot of output.
#define UNICODE
#define _UNICODE
#define DBGHELP_TRANSLATE_TCHAR
#include <windows.h>
#include <imagehlp.h>
#include <iostream>
#include <ctype.h>
#include <iomanip>
#pragma comment(lib, "dbghelp.lib")
int y;
int junk() {
return 0;
}
struct XXX {
int a;
int b;
} xxx;
BOOL CALLBACK
sym_handler(wchar_t const *name, ULONG_PTR address, ULONG size, void *) {
if (name[0] != L'_')
std::wcout << std::setw(40) << name
<< std::setw(15) << std::hex << address
<< std::setw(10) << std::dec << size << L"\n";
return TRUE;
}
int
main() {
char const *names[] = { "y", "xxx"};
IMAGEHLP_SYMBOL info;
SymInitializeW(GetCurrentProcess(), NULL, TRUE);
SymSetOptions(SYMOPT_UNDNAME);
SymEnumerateSymbolsW(GetCurrentProcess(),
(ULONG64)GetModuleHandle(NULL),
sym_handler,
NULL);
info.SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
for (int i=0; i<sizeof(names)/sizeof(names[0]); i++) {
if ( !SymGetSymFromName(GetCurrentProcess(), names[i], &info)) {
std::wcerr << L"Couldn't find symbol 'y'";
return 1;
}
std::wcout << names[i] << L" is at: " << std::hex << info.Address << L"\n";
}
SymCleanup(GetCurrentProcess());
return 0;
}
WinDBG has a particularly useful command
ln
here
Given a memory location, it will give the name of the symbol at that location. With right debug information, it is a debugger's (I mean person doing debugging :)) boon!.
Here is a sample output on my system (XP SP3)
0:000> ln 7c90e514 (7c90e514)
ntdll!KiFastSystemCallRet |
(7c90e520) ntdll!KiIntSystemCall
Exact matches:
ntdll!KiFastSystemCallRet ()