How to watch a variable? - c

I have a code base of almost 16000 lines of C code in which I am performing different operations (on a Raspberry Pi). After each operation, I am updating the value of dc. dc is initially 0 and if through some error my controller loses its connection with my laptop it becomes 1.
I need to call a function whenever it goes 1. I heard of a function in JavaScript called Object.prototype.watch() and unwatch(). Basically what it does is watches a variable and whenever its value changes, it calls a function. I need to implement a similar function or statement or anything that calls a function when my dc value changes.
I cannot use if-else after each update of dc because it is not a good way of coding and there are going to be a lot of if-else if I use it.

Nothing like this exists. Interpreted or managed languages have completely different rules. There is no other way than if.
You can wrap it into some kind of assertion or function but there is no other way than if in that wrapper

The sad answer is: No, there's no reliable way to watch a variable in C this way.
Depending on how the code works there are some workarounds.
One way is to hide (yes I know, it's hard to hide stuff completely in C) the variable. Define functions:
int noConnection() { return _noConnection; }
void lostConnection() { _noConnection = 1; myFunction(); }
Another way is to code some monitor that checks the variable at regular intervals. A drawback is if you really need this function to be run every time it changes, because it will not catch the event that a variable is changed and changed back between checks.

If the variable is not referenced by any pointers then you already know the places where it is updated, so you can use visibleman's method. There won't be a lot of if-elses like you anticipated. Just create a function like this
inline void update_dc(int new_dc) // or a macro if you want,
{ // but inline functions are more preferrable
#ifdef DEBUG_DC
if (new_dc == 1) // or if (new_dc != dc)
{
trap();
}
#endif
dc = new_dc;
}
and replace all assignments to dc with this function. You can do that easily with a regex in any text editors' find/replace command, or find/sed in the terminal
However in the general case when you don't know exactly at what point it can be updated, the easiest way is using a separate thread for watching it. You'll do some kind of polling by using a timer, or by checking the value and then sleep for some time to avoid wasting CPU usage. But you won't get the exact place where the change happens, unless you insert a value check after every instruction, which slows down your app many times.
You may also run a debugger like gdb and attach it to your own process to watch. It'll be a lot more flexible this way, but you'll need more memory. You can also try some debugging library if available
See Is is possible to set a gdb watchpoint programatically?
Many architectures do have hardware watch points, so debuggers will try to use them up before turning up to software watching (which is extremely slow). If you know about the architecture you can also set up the debug registers manually like that instead of running a full-fledged debugger. Of course most of the time you'll need to run in privileged mode to set those registers
On x86 there are 3 breakpoints stored in DR0-DR3 which will break on execution, data write, data read/write and IO read/write. I don't know the situation on ARM but it seems to have 6 hardware breakpoints. You can check those on ARM's documentation if you want to go that way.

The most straightforward solution seems to be to stop changing the variable directly and write a getter and setter function, that will call some callback.

Related

How to handle changes to settings during runtime of a embedded c project?

I'm playing around with an esp32 (c with esp-idf, not with arduino) for a hobby project of mine. I'm currently programming a little drone that I can control with my smartphone. All works well.
But now I need to create system for persistent settings and parameters. For example pid-tuning parameters or what sensors are enabled and more. The general idea was to have a settings file in flash that is read on startup. The settings can then be used in the individual modules of the program. Now I'd also like to change those settings during runtime. For example pid tuning parameters. I don't want to reboot the system only to change a small parameter.
So now my question: How can I handle changes to those settings during runtime?
An idea was to have the module periodically ask a special
"settings-module" if there are any changes. It would then change its
internal settings accordingly. As settings shouldn't change that
often I think the overhead of constantly asking for updates is rather
unnecessary.
A more extreme idea was, to give a pointer to the variable in
question to the "settings-module". If any changes have to be made the
settings module would change the variable directly.
Or maybe a callback system?
The ideas seem feasible but I don't know if there are any best-practices or better options.
Does anyone of you know a name of a technique I can google or maybe an library that provides something similar?
Thanks!
ESP ISF already has 90% of your requirements covered with the non-volatile storage library - string keys, int/string values, wear levelling etc. Just use this to store all your settings and parameters. Read from it every time you want to get a value (unless you go to the sub-millisecond latency land, in which case it's perhaps best to cache the settings in RAM).
Reading a value from NVS can fail (e.g. if the parameter is not stored, the NVS partition got wiped, etc) which would introduce cumbersome error handling into every code block where you read a parameter. A common trick to avoid this error handling is to add a thin wrapper which takes a fallback value of the parameter and returns it every time reading the parameter from NVS fails. Something like this:
uint32_t fetchU32(const char* key, const uint32_t fallback) {
uint32_t ret;
if (ESP_OK != nvs_get_u32(g_nvs_hnd, key, &ret)) {
ret = fallback;
}
return ret;
}
Note that you need to be careful when using such wrappers - occasionally a critical parameter value must be found from NVS and not replaced with a fallback blindly.
Adding to what Tarmo suggested, you should also take not there are write limits to the ESP32's NVS. But do take note that the limits are set by what flash you are using.
I am placing this link where they discuss the write limits of the ESP32.

How to save state and return to a deep C function?

Background
I am porting an existing C program to work as an online game using Emscripten.
The problem is that Emscripten wants the program to be organised around a single function that is called 60 times a second. This is okay for the main game loop, except that there are quite a few places where the code displays a set of options and then waits for a key to be pressed to select the option. This is expressed as a function deep in a calling hierarchy using getch() to wait for a keypress. I find it hard to see how to fit this into the required Emscripten style of a function that runs and then completes.
Question
When the code has called a function, which has called a function, which has called a function, is there an easy way of saving the entire state of the callstack so that I can return to the same place at a later time?
What I've tried
The approach I am currently using is to set a global state variable to indicate my current location and to write all the things on the stack that seem important into static variables. I then return from all the functions. To reenter I use the global variable to decide which function to call and which variables to reload from saved data. However, this involves writing a lot of extra code and is very error-prone.
I wondered about using a thread for the game logic and just sending messages from the GUI thread, but the current thread API inside Emscripten seems to require me to try and copy all of the game data into a message so this feels like a lot more work for little benefit.
Emscripten supports setjmp/longjmp but as far as I understand, this only does half the job. I think I can use a longjmp to simply return from a deep function back to the upper level, but I don't see anyway that I can use it to later go back to where I was.
Any better ideas on how I can do this?
you cannot return from a callstack and re-enter it again. You can only make deeper calls to still be able to return to the current state. Once the function returns, the same stack (same physical memory locations) is reused for the following calls, and values get overwritten.
I don't know Emscripten; could a getch() wrapper recursively drive the loop until a key is pressed?
setjmp/longjmp saves the stack offset, but not the values on the stack. It's only useful for popping multiple frames off the stack; it's the closest C comes to a thrown exception.
You can try to use asyncify (https://github.com/kripken/emscripten/wiki/Asyncify) but it is not recommended. A quite better way would be the use of the emterpreter (https://github.com/kripken/emscripten/wiki/Emterpreter) or doppio instead (https://github.com/plasma-umass/doppio). However there might be a quite better solution in future, if you could use an evolved standard of WebAssembly. Until now the only certain ways to get such a programm running is to eliminate all recursions or to implement your own callstack. Nevertheless you will have to save your state outside of the JavaScript stack because it can not be manipulated by the programm itself. That is also the reason why longjmp does not work in this case.

How to view variables during program execution

I am writing a relatively simple C program in Visual C++, and have two global variables which I would like to know the values of as the program runs. The values don't change once they are assigned, but my programming ability is not enough to be able to quickly construct a text box that displays the values (I'm working in Win32) so am looking for a quick routine that can perhaps export the values to a text file so I can look at them and check they are what they ought to be. Values are 'double'.
I was under the impression that this was the purpose of the debugger, but for me the debugger doesn't run as the 'file not found' is always the case.
Any ideas how I can easily check the value of a global variable (double) in a Win32 app?
Get the debugger working. You should maybe post another question with information about why it won't work - with as much info as possible.
Once you have done that, set a breakpoint, and under Visual C++ (I just tried with 2010), hover over the variable name.
You could also use the watch window to enter expressions and track their values.
If your debugger isn't working try using printf statements wherever the program iterates.
Sometimes this can be a useful way of watching a variable without having to step into it.
If however you wish to run through the program in debug mode set a breakpoint as suggested (in VS2010 you can right click on the line you want to set a breakpoint on).
Then you just need to go to Toolbars -> Debug Toolbar.
I usually like to put #ifdef _DEBUG (or write an appropriate macro or even extra code) to do the printing, and send to the output everything that can help me tracking what the program's doing. Since your variables are never changing, I would do so.
However, flooding the console with lots of values is bad imo, and in such cases I would rely on assertions and the debugger - you should really see why it's not working.
I've done enough Python and Ruby to tell you that debugging a complex program when all you have is a printf, although doable, is extremely frustrating and takes way longer than what it should.
Finally, since you mention your data type is double (please make sure you have a good reason for not using floats instead), in case you add some assertion, remember that == is to be avoided unless you know 100% that == is what you really really want (which is unlikely if your data comes from calculations).

Detecting code blocks when executing a Lua script line by line

This may sound like a silly question but I could see no mention anywhere of this particular problem. Basically:
I want to execute a Lua script line by line, primarily to have the ability to pause/resume execution anytime and anywhere I want. What I do is simple: load a chunk with luaL_loadbuffer() and then issue a lua_pcall().
Thing is... How can I properly detect Lua blocks in order to execute them atomically?
For instance, suppose there's a function in the script -- by executing the file line by line with the method described above, I can't seem to have a way to properly recognize the function, and in consequence its contents are loaded and called one by one.
I can imagine that one solution would be to manually handle a stack where I push control keywords I can recognize in the script ("function", "if", "do", etc) and their corresponding "end" clause if I find nested blocks. Once I push the final "end" I call the entire block, but that sounds simply awful. Surely there must be a better way of doing this.
Hope it makes some sense, and thank you!
Please take a look at Lua coroutines to implement that functionality for scripting game entities. The idea is to yield the coroutine in the sleep() and waitforevent() routines you mentioned, and then resume later (e.g. after a timeout or event occurs).
Use lua_sethook().
Note that you probably do want to experiment with what exact hook call granularity you need. I'd recommend executing chunks of bytecode instructions instead. One really long line may contain many instructions.

Advanced Memory Editing/Function Calling

I've gotten extremely interested into coding trainers (Program that modifies value of a different process) for video games. I've done the simple 'god-mode' and 'unlimited money' things, but I want to do alot more than that. (Simple editing using WriteProcessMemory)
There are memory addresses of functions on the internet of the video game I'm working on, and one of functions is like "CreateCar" and I'm wanting to call that function from an external program.
My question: How can I call a function from an external process in C/C++, provided the function address, using a process handle or other method.
PS: If anyone could link me to tools (I've got debuggers, no need for more..) that help with this sort of thing, that'd be nice.
You can't, at least not safely. If the function has exactly one parameter, you can create a new thread in that process at the function address. If it has more, you might want to inject a DLL to do it.
But neither of these solutions are safe because creating a new thread to run the function can and will corrupt data structures if other threads are currently using them. The only safe way to call a function in another process is to somehow insert the call in exactly the right place in that process so that it's logically correct for that program. Never mind the technical hurdles (inserting hooks at arbitrary locations); you need to know exactly how the program works, which basically means you have a lot of reverse engineering ahead of you (or you need to get the source code).

Resources