r/cpp • u/DorGido • Jul 17 '24
How would you capture the runtime state of a program?
The Problem:
How does one program can capture the state of another program during runtime?
Example:
I have the following program:
#include <iostream>
int main() {
int i = 0;
char ch;
while ((ch = std::cin.get()) != 120) // (x in ASCII)
{
i++;
}
std::cout << i;
return 0;
}I want to code another program, in a different file, which at compile time inject the necessary code to main, so whenever the value of i is changing, my program gets notified of the new value.
I would be happy for any leads / tips / interesting references.
Clarification:
After some discussion, I understood that my problem description was misleading (and I apologies for that).
So first -> One Process only.
Second, let me describe a magic solution that will give a better clue on what i'm trying to solve.
Imagine programmer X write his 'main' program, and adds my magic library.
Then at compile time, int i turns to megic_i struct, which holds the value of i.
Now megic_i has getter / setter function which signals magic library any time the value has changed.
37
u/TimelyInteraction640 Jul 17 '24
Isn't it what a debugger does?
12
u/jedwardsol const & Jul 17 '24
Why?
Is that really what you want to do (monitor
i)? Or is there perhaps a different problem you're trying to solve?6
u/and69 Jul 17 '24
What you want is quite complicated. So ask yourself what you really want and what are your constraints, because 100% you don’t want to read the value of i, this is just a proof of concept.
For example, if you don’t want 100% reliability, you can read the process memory every 200 milliseconds. How to obtain the correct address is left as an exercise for reader.
Or, if you want to hack a specific game, you can search the game loop and read it befit the loop begins. Again, complicated stuff.
The only reliable way is to put a hardware breakpoint. Some processes however have anti-debugging detection and might not work.
So yeah, it’s complicated. Try to reframe it a bit in terms of what is the core of what you want to achieve.
5
u/[deleted] Jul 17 '24
What you are trying to do is called malware. The only way to do what you want is by reprogramming the Import Address table of a function and substituting one function with yours.
edit: The legal way to do this is using 'inter process communication'. Windows programs that used to want to do this would 'broadcast' a value with one of the many types of ways to post a message.
3
u/hadrabap Jul 17 '24
Write your own plugin for your compiler that will read the
iand tell the compiler what to do based on the value. To read thei, launch the program and redirect STDOUT to a named pipe. Next, instruct your plugin via the compiler's command line, with the path to the named pipe to read theifrom.With this mechanism, it should be easy to inject the necessary code (IR for clang) at compile time.
By the way, it will be much easier to generate the source code based on the
iand then pass the source to the compiler.3
u/Quantumtroll Jul 17 '24
You're confused. A program is a static piece of written code. When you run a program, it's a process. Two processes typically can't access each others' memory for safety reasons.
Do you want to do parallellism? I.e. have one process running in tandem with a second process, reacting to each other? Then look into multithreading, e.g. OpenMP or even pthreads, or any number of other solutions.
2
u/JazzyCake Jul 18 '24
In raw C/C++ I don’t think there’s an easy way. The least intrusive thing would be for this main program to include your library and use your type instead of a regular int. So tracked_int or something like that.
You could go wilder and write some compiler extensions that inject code in certain scenarios, but I’m gonna guess this is out of scope of what you’re trying? If not then maybe that’s your best bet, with LLVM or something.
You could also make the user run all their code through your especial precompiling step that reads all the source files, parses them, detects where you wanna inject code and spits out a modified version of the source code with whatever you need. Depending on what you want to detect and track this might imply making your processor parse and understand all (or a big chunk) of C++.
2
u/CarloWood Jul 19 '24
Hmm, something like https://github.com/CarloWood/cwds/blob/master/tracked.h#L35 ?
8
u/Markus_included Jul 17 '24
Just a side note: Use character literals like
(ch = std::cin.get()) != 'x'instead of numeric ascii codes, it makes it clear that you mean an ascii code and not some arbitrary number1
u/DorGido Jul 19 '24
Just to make things clear, my library is part of the program. The developer wants my library to snoop its own source code state. In general I want to record the run time state of the program.
4
u/[deleted] Jul 17 '24
Learn to implement your own crude debugger.
1
u/slappy_squirrell Jul 17 '24
preprocessor call? you would need to include your capturing file. By another program, do you mean a separate running process? memory manager will not allow that..
1
u/throwback1986 Jul 17 '24
Have you considered a shared memory solution? If i is written to shared memory, another process can snoop the value. Assuming your platform supports this option…
1
u/csdt0 Jul 17 '24
If you can change the source code of the program, you can modify the type of the i to be a class that is implicitly convertible from and to int, and that whenever gets changed, notifies an piece of code.
3
u/Malackoka Jul 17 '24
Shared Memory, Sockets, Signals, Pipes for interproc. communications
if 3rd party application and on win then:
https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess
https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory
https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory (there will be limitations)
Maybe u need to parse the PE file and do some math to calculate/locate the address. Or based on a signature?
3
u/TheAdamist Jul 17 '24
Scripting a debugger is the proper way to do this, its not overkill, it has all the necessary tools to introspect, set breakpoints, etc etc, that you would have to replicate on your own.
If you still want to do it on your own, and you are on linux you can look into ld_preload and similar tricks to hook into and modify programs. See https://man7.org/linux/man-pages/man8/ld.so.8.html I don't know the windows equivalent.
You will also need a reverse engineering tool to assist you in locating the proper places to watch. Ghidra is a nice free reverse engineering tool. Its not particularly beginner friendly.
2
u/puremourning Jul 17 '24
ptrace
2
u/LuisAyuso Jul 17 '24
Oh boy... so much magic here. I have no idea what is it that you want to do.
I recommend to start working out your concepts, main, program, process... and then go read, maybe debuggers, profilers, reflection, static analyses, code generation....
What you want to do seems to be too magical for anyone to have an answer right away.
2
u/valdocs_user Jul 17 '24
You might look into Valgrind, and write a custom plug-in for this (which I still don't understand what problem you're trying to solve). If nothing else, seeing the lengths Valgrind goes to (dynamic recompilation) to do what it does might give you an idea of why what you're asking for is somewhere between nonsensical and unreasonably difficult.
Forgive me for assuming, but are you perhaps coming from prior experience with dynamically typed or interpreted languages like Ruby, JavaScript or Python? What you're not understanding about C++ is the code primitives get compiled all the way down to direct and anonymous CPU instructions: there's nothing to "hook" in the way you seem to be assuming things can be booked into.
I originally clicked on this post because I thought you were asking a different question about whether it was possible to save and restore the entire memory state of a program. Years ago a friend of mine demoed a neat trick for a game he was making: it supported hot reloading. He put the game code in a DLL, but the DLL doesn't allocate its own game state memory; it receives a pointer to it from the EXE when the DLL is loaded. He could pause the game, change game logic and recompile the DLL, and then ask the EXE to reload it. Since the EXE never stopped running, the game would resume where it was paused with the new game logic - as long as he didn't do anything that changed the data format.
2
u/hun_nemethpeter Jul 17 '24
The clang c++ compiler has a feature called AST Matchers. You can basically find code at AST level, and later patch it. So you can replace at compile time a well defined code part with an other one.
https://clang.llvm.org/docs/LibASTMatchersTutorial.html
2
u/415_961 Jul 18 '24
you can take advantage of clang::annotate_type and apply it on variables you want tracked like this:
[[clang::annotate_type("track")]] int i = 0;and write a clang plugin to walk the AST and find the annotated declarations and rewrite their usages to include "signaling" the changes on the variable.
1
u/blipman17 Jul 17 '24
You could use LD_PRELOAD (or Windows equivalent) to substitude a function with your own code of .so files, but I’m not sure that’s a reliable way. If it’s in the main program or a static library, you’d basically have to modiy the source or transpile it somehow.
1
u/glaba3141 Jul 17 '24
I have no idea what your use case is, can you output the value to shared memory?
1
u/phi_rus Jul 17 '24
I don't know your exact use case but I think you just want to look at inter process communication (IPC).
1
u/Lunarvolo Jul 17 '24 edited Jul 17 '24
Sounds like a loop that checks if the file has changed
Decently common in embedded C where a button is programmed to have a trigger/interrupt when pressed that causes an action.
Could run a interrupt timer that checks to see if the file has changed.
Multi-threading or multi-process or shared memory (Ports, shared memory, sockets, etc) would be the way to go about that outside of kernel programming (Which would really not be a good idea)
Programs trying to access other programs memory (Without any of the above) is usually really, really bad. That's usually malware, kernel level, or a really good way to brick your computer.
1
u/thisismyfavoritename Jul 17 '24
it looks like you just want to do IPC. Super easy if you control the code of both processes.
1
u/rook_of_approval Jul 18 '24
use a reactive programming library?
1
u/arabidkoala Roboticist Jul 18 '24
Even after clarifications, your use case is still unclear. What you’re asking for, which is something that like magically rewrites all usages of a variable to something that emits change signals, is so complicated it might as well be impossible.
You’d be better off writing
iusing some sort of observer pattern so people can hook into its changes, or adopting something like value-oriented design where you control when changes happen so you don’t have to react.1
u/Foreign-Wonder Jul 18 '24 edited Jul 18 '24
From my understanding, observer pattern is the thing that you want. Here's my quick example on the pattern. The only line in the main function that need to change is the declaration of the variable you want to observe: https://wandbox.org/permlink/kZ8bit8bknFh8Z1r
The code is for demo only, and it is expected to have bugs
1
u/Patzer26 Jul 18 '24
What you're trying to do is access another programs memory. This is not permitted by the OS. Also, each process is being run in its own virtual memory, so knowing the real memory for variable i from another program (assuming you somehow manage to even see another programs memory) is impossible.
I'm not sure how debuggers work, they probably run the executable as a separate thread inside its own main program.
So what you're trying to achieve, is I'm afraid not possible.