Making a program see another program's memory - c++

There are tools such as TSearch, Cheat Engine, etc. These are hacking programs for viewing and modifying parts of memory of another program.
If I am to create a C++ program that can see and modify other program's memory, how can I do that? What are some of the things I should be looking for?

This is not a feature of C++, it's under the control of the OS itself.
For example, Windows provides the ReadProcessMemory() API call so that you can get your grubby little hands on the memory of another process. And of course, the equivalent for writing as well so you can cause even more damage :-)
All this depends on having the correct privileges as well.
I'm not sure how Linux provides this but earlier UNIXes had "memory mapping" files like /dev/mem so you could get at the memory. There may be a per-process variant in the procfs file system which can give you access to the virtual memory of a specific process. That'd be the first place I'd start looking although others here will undoubtedly know more about that than I.

One way to do that is to write your own debugger.
That won't be easy, though. Good luck.

Related

How (and why?) do memory editors work

Memory editors such as Cheat Engine are able to read the memory of other processes and modify it.
How do they do it?(a code snippet would be interesting!) A process does typically not have the ability to access the memory of another one, the only cases that I've heard of are in sub-processes/threading, but memory editors are typically not related to the target process in any way.
Why do they work? In what scenario is this ability useful aside from using it to hack other processes, why wouldn't the operating system simply disallow unrelated processes from reading the memory of each other?
On Windows, the function typically used to alter the memory of another process is called WriteProcessMemory:
https://learn.microsoft.com/en-in/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory
If you search the Cheat Engine source code for WriteProcessMemory you can find it both in their Pascal code and the C kernel code. It needs PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process which basically means you need to run Cheat Engine as admin.
WriteProcessMemory is used any time you want to alter the runtime behavior of another process. There are legitimate uses, such as with Cheat Engine or ModOrganizer, and of course lots of illegitimate ones. It's worth mentioning that anti-virus software is typically trained to look for this API call (among others) so unless your application has been whitelisted it might get flagged because of it.
Operating systems typically expose system calls that allow a userspace program to inspect a target process's memory using said system calls.
For instance, the linux kernel supports the ptrace system call. This system call is primarily used by the well known debugger gdb and by popular system call tracing utilities such as strace.
The ptrace system call allows for the inspection of memory contents of the target process, code injection, register manipulation and much more. I would suggest this as a resource if you are interested in learning more.
On Linux, you can either run a binary from within gdb, or attach to a process. In case of the latter, you need elevated privileges. There are other protections that try to limit what you can do with ptrace, such as the one mentioned here.
On Windows you can achieve the same effect by using the following functions in order : OpenProcess, GetProcAddress, VirtualAllocEx, WriteProcessMemory and CreateRemoteThread. I would suggest this as a resource if you are interested in knowing more. You might need elevated privileges to do this on newer Windows versions.

Clean up RAM (Maybe win32 api)?

Every so often I see "Speed Up Your PC" programs that offer a RAM cleaning feature.
They claim to defrag and free up unused memory like a garbage collector or something... not sure.
Here are some examples:
http://www.softpedia.com/get/Tweak/Memory-Tweak/Clean-Ram.shtml
http://download.cnet.com/Instant-Memory-Cleaner/3000-2086_4-10571833.html
http://www.uniblue.com/software/speedupmypc/
I'm interested in learning about the Win32 C API's that they are using, if anyone has knowledge.
I've heard about the ProcessIdleTasks() in advapi32.dll trick, but doesn't look too legit looking at the documentation on that function.
If you really insist on doing this, you could enumerate processes, open a handle to each, and call SetProcessWorkingSetSize(process_handle, -1, -1); for each (but you really don't want to do this).
I don't know how those particular programs work, but in the past I saw the source to a similar program.
It basically allocated a ton of RAM in one shot and then released it.
System RAM was "freed" because other programs had to swap to the disk.

How to retrieving variable value in C++ if you know the variable address

Greetings,
I have recently started to code in C++ and have come across a problem to which I was unable to find the answer, so I thought maybe somebody else might know the answer.
Is it possible to retrieve a variable value from another program if you know a variable address? Imagine that I have a memory address displayed in a program, something like: 0x7fff5fbff758 and I would like (in my own program which is not related to the first one) to get the value stored in that memory address.
Is that possible? If so, could somebody please explain me how.
Thank you in advance.
On today operating systems, the programs handle virtual addresses, not physical ones. Shortly, a specific address for one programs will not point to the same physical location for other programs.
To do what you want on modern operating systems, you can, for instance, set up a shared memory location.
But there is a lot of easier way to pass a value from one program to another.
If you are just wondering that out of curiosity, that's a good question, you can look at what "virtual memory" is.
C++ has no comment on this, one way or the other. It depends entirely on the platform on which your program is running. If you're using Windows, for example, you can use the ReadProcessMemory() function to read the memory of another process (assuming you have adequate permissions).
Note that modern operating systems are designed to protect processes from interfering with each other. One of the ways they do this is by giving each process its own address space. Processes can't access memory outside this space without using special APIs.
It is possible, but it is OS-specific (there is no common C support for it). In general, your second program needs to have the permission that debugger has, and use the same kind of OS calls that a debugger uses.
On most modern general-purpose OSes (Windows, Linux, etc), you cannot do that. Different programs run in different processes, and each process has its very own memory space. Address 0x7fff5fbff758 in one probably points to a very different place in RAM than address 0x7fff5fbff758 in another (if that address even exists in the other).
This is why modern OSes have interprocess communications mechanisims, like pipes, shared memory, COM, etc.
Edit: This obsolete, because the question has changed.
If you know the type of the variable, its possible.
For an int variable, you need to insert lines like
int* addr = (int*)0x7fff5fbff758;
std::cout << *addr << std::endl;
somewhere in the affected program.
Accessing the variable from a different program is generally not easily done in a modern operating system, each process has it's own address space so the same address in different processes may map to different physical memory location.
It depends on the OS, for example in linux you need to trace a process if you want to do it from a different process, see man ptrace. You can read the data in this case with PTRACE_PEEKDATA.

Keeping memory usage within available amount

I'm writing a program (a theorem prover as it happens) whose memory requirement is "as much as possible, please"; that is, it can always do better by using more memory, for practical purposes without upper bound, so what it actually needs to do is use just as much memory as is available, no more and no less. I can figure out how to prioritize data to delete the lowest value stuff when memory runs short; the problem I'm trying to solve is how to tell when this is happening.
Ideally I would like a system call that returns "how much memory is left" or "are we out of memory yet?"; as far as I can tell, no such thing exists?
Of course, malloc can signal out of memory by returning 0 and new can call a handler; these aren't ideal signals, but would be better than nothing. A problem, however, is that I really want to know when physical memory is running out, so I can avoid going deep into swap and thereby making everything grind to a halt; I don't suppose there's any way to ask "are we having to swap yet?" or tell the operating system "don't swap on my account, just fail my requests if it comes to that"?
Another approach would be to find out how much RAM is in the machine, and monitor how much memory the program is using at the moment. As far as I know, there is generally no way to tell the former? I also get the impression there is no reliable way to tell the latter except by wrapping malloc/free with a bookkeeper function (which is then more problematic in C++).
Are there any approaches I'm missing?
The ideal would be a portable solution, but I suspect that's not going to happen. Failing that, a solution that works on Windows and another one that works on Unix would be nice. Failing that, I could get by with a solution that works on Windows and another one that works on Linux.
I think the most useful and flexible way to use all the memory available is to let the user specify how much memory to use.
Let the user write it in a config file or through an interface, then create an allocator (or something similar) that will not provide more than this memory.
That way, you don't have to find statistics about the current computer as this will allways be biased by the fact that the OS could also run other programs as well. Don't even talk about the way the OS will manage cache, the differences between 32 and 64 bit making adress space limit your allocations etc.
In the end, human intelligence (assuming the user know about the context of use) is cheaper to implement when provided by the user.
To find out how much system memory is still unused, under Linux you can parse the file /proc/meminfo and look for a line starting with "MemFree:". Under Windows you can use GlobalMemoryStatusEx http://msdn.microsoft.com/en-us/library/aa366589%28VS.85%29.aspx
Relying on malloc to return 0 when no memory is available might cause problems on Linux, because Linux overcommits memory allocations. malloc will usually return a valid pointer (unless the process is out of virtual address space), but accessing the memory it points to may trigger the "OOM killer", a mechanism that kills your process or another process on the system. The system administrator can tune this behavior.
The best solution I can think of might be to query how many page faults have occurred within, say, the last second. If there's a lot of swapping going on, you should probably release some memory, and if not, you can try allocating more memory.
On Windows, WMI can probably give you some statistics you can use.
But it's a tough problem, since there is no hard limit you can ask the OS for and then stay below. You can keep allocating memory far beyond the point where you've run out of physical memory, which just means you'll cripple your process with excessive swapping.
So the best you can really do is some kind of approximation.
You can keep allocating memory beyond the point where it is useful to do so - i.e. that which requires the OS to swap, or page out important things. The trouble is, it is not necessarily easy to tell where this is.
Also, if your task does any (significant) IO, you will need to have some left for the OS buffers.
I recommend just examining how much there is in the machine, then allocating an amount as a function of that (proportion, or leave some free etc).

On Sandboxing a memory-leaky 3rd-Party DLL

I am looking for a way to cure at least the symptoms of a leaky DLL i have to use. While the library (OpenCascade) claims to provides a memory manager, i have as of yet being unable to make it release any memory it allocated.
I would at least wish to put the calls to this module in a 'sandbox', in order to keep my application from not losing memory while the OCC-Module isn't even running any more.
My question is: While I realise that it would be an UGLY HACK (TM) to do so, is it possible to preallocate a stretch of memory to be used specifically by the libraries, or to build some kind of sandbox around it so i can track what areas of memory they used in order to release them myself when i am finished?
Or would that be to ugly a hack and I should try to resolve the issues otherwise?
The only reliable way is to separate use of the library into a dedicated process. You will start that process, pass data and parameters to it, run the library code, retrieve results. Once you decide the memory consumption is no longer tolerable you restart the process.
Using a library that isn't broken would probably be much easier, but if a replacement ins't available you could try intercepting the allocation calls. If the library isn't too badly 'optimized' (specifically function inlining) you could disassemble it and locate the malloc and free functions; on loading, you could replace every 4 (or 8 on p64 system) byte sequence that encodes that address with one that points to your own memory allocator. This is almost guaranteed to be a buggy, unreadable timesink, though, so don't do this if you can find a working replacement.
Edit:
Saw #sharptooth's answer, which has a much better chance of working. I'd still advise trying to find a replacement though.
You should ask Roman Lygin's opinion - he used to work at occ. He has at least one post that mentions memory management http://opencascade.blogspot.com/2009/06/developing-parallel-applications-with_23.html.
If you ask nicely, he might even write a post that explains mmgt's internals.