Tracking functions on stack in C - c

I am taking the first dive into the waters of stack memory trace so I need your help. Here is my problem for which I need your tips:
I have two functions: login and logout(). There is one simple condition:
If I call login() to create a session, then somewhere in my program, logout() should be called otherwise there should be an error generated.
I believe that that I can not do it on compile time so I have to do it on runtime(I can be wrong).
The problem is that how do I find out that logout() is called in my program before the main() returns and generate error if it is not called.
I was thinking that at the runtime, Every function that I call after login() should check whether it is the last function call and then look whether the logout() was called ever before or not.
So How would I know at runtime that a certain function is the last function my program called before the main() returns?
Any help would be appreciated.

one way, perhaps not the nicest, is to use a variable loggedIn = 1, and pass a reference to it so logout() can set it to zero. check that it's zero before return from main().
after a function returns, its address has already been popped from the stack.

Related

What is the best way to detect that a recursive function is called by another function, not by function itself?

Suppose I have a recursive function rec_fun() and it have two block of code, block_1 and block_n. block_1 must execute only once when rec_fun() is initially called by another function like main() and block_n must execute every time rec_fun() is called, whether by another function or by function itself.
rec_fun()
{
{
...
//block_1
//must be executed on first call only
...
}
{
...
//block_n
//with recursive call and exit condition
...
}
}
What is the best way to achieve this? I have thought few ways like using a counter i as parameter to rec_fun() initially passed with 0 and incrementing it in subsequent call, so that the function can determine whether it is first call or not. Another approach is to put block_n in another helper function and call it from rec_fun(). But in first approach I have to pass an unnecessary argument 0 and second approach creates an unnecessary function. What is the best way to accomplish this, according to you?
I'll appreciate if you provide some useful links to learn recursion.
Hide it behind a layer of indirection:
func()
{
//block_1
// compute what you need
// and pass it to rec_fun either as value, or as a pointer
rec_func(&block_1_result);
}
And make sure you expose only func for your users.
and second approach creates an unnecessary function
So? Unless you are in an extremely limited environment like an embedded device with very limited memory that's really not an issue. And the function is not "unnecessary". It's unnecessary if you think the user doesn't need 2 functions, but it's necessary if you think from the implementation view: it's needed by the implementation (actually it's one solution, but still the argument holds).
I will go against your intuition completely and will suggest to combine the two approaches you consider inappropriate. Because they are appropriate. I will create a recursive implementation with extra parameter, but for convenience and "hiding" I will also make a wrapper function:
void rec_func(bool init)
{
if (init) {
/* initialization logoc */
}
/* common recursive code */
rec_func(false);
}
void wrapper_func(void)
{
rec_func(true);
}
Note, nothing is "unnecessary" here. The extra parameter helps to keep the function logic in one unit. The wrapper function helps the caller not to mess with unrelated parameters.
Your second solution is usually the correct one.
The second function isn't any less necessary than any other function. You have one function that defines what is needed to implement whatever it is that the external caller expects your code to do. You have another to define whatever it is that you're going to do recursively.
Those apparently do different things and meet different requirements. As such, it's entirely appropriate that they be implemented in different functions.
It's possible to combine these into a single function that varies its behavior depending on a parameter that's passed. If the difference in behavior is small enough, this can be a somewhat reasonable approach--but I would say having one function do two different sorts of things is generally a kludge. The only question is whether it's a small enough kludge that you choose to overlook its being kludgy, or a big enough one that you shouldn't overlook it.
As so ensuring that the second function isn't accidentally called by some "outsider", the usual is to make it a static function, so you'd have a structure on this general order:
foo.h
#pragma once
int foo(int);
foo.c
typedef result_t /* whatever */;
static result_t blocka(int) {
// stuff for block a
}
static int blockb(result_t const *) {
// stuff for block b
}
int foo(int input) {
result_t internal_result = blocka(input);
return blockb(&internal_result);
}
In this case, I've written both blocka and blockb as separate "unnecessary" functions. Since I don't know what either your block a or block b does, it's hard to guess whether that's justified or not. But I would not start by thinking in terms of whether a function is necessary. Rather the opposite, for almost any block of code with a reasonably well defined interface and functionality, writing a function to embody that block of code should be more or less the default.
For example, if you have an if/then/else kind of situation:
if (foo) {
// do foo stuff
} else {
// do not-foo stuff
}
Think about/ask yourself whether you can give a meaningful name to the "do foo stuff" block and/or the "do not-foo stuff" blocks. That is, can you give a name to what they're doing?
If so, there's a reasonable chance that they should be implemented as functions, and then your if/then/else block can become a more readable, higher-level guide to what's going on:
if (data_sorted(input))
process_sorted_data(input);
else
process_random_data(input);
Moving these blocks of code into (reasonably well-named) functions makes it much easier for a reader to understand the intent behind the code, rather than having to divine your intent from the content.
The C language does not give the function any information regarding its caller so there is no portable way to test whether rec_fun() was called from another function or recursively from itself.
Your goal can be achieved by passing an extra argument to the function with a different value for outsider and recursive calls. This is cumbersome and error prone.
The standard approach for your problem is to use an ancillary function rec_fun1(): the main function rec_fun() is called from other functions and the recursive ancillary function is called from rec_fun() and recursively from rec_fun1() itself.
A classic example of this is mergesort() which would allocate the temporary work array and call a recursive mergesort1() that uses the temporary array to perform the top down merge sort algorithm. Upon return from the call to mergesort1(), mergesort() frees the temporary array and returns to the caller.
You can use static variable as counter.
rec_fun()
{
static int i = 0;
if (++i == 1) {
...
//block_1
//must be executed on first call only
...
}
{
...
//block_n
//with recursive call and exit condition
...
}
--i; // internal house keeping to track whether internal, or external caller
}
You can pass a parameter that you change as you move down the recursion and make block 1 ran based on the condition of the parameter. If you use an if/else if for block 1 and 2 then you're good.
your_func(the_param){
if(the_param) {
// the code that only runs on the first call
}
else if(the_param) {
// the code that runs every other call
}

Pin tool: wrap all routines with an entry/exit function via RTN_Replace

Using Pin, I would like to call some instrumentation function before and after each application function call. I've read that RTN_InsertCall to add some entry/exit analysis functions with IPOINT_BEFORE and IPOINT_AFTER is unreliable as the exit may never be called.
My understanding is that the 'correct' way to do this is to replace the routine via RTN_ReplaceSignature, then in my replacement function add the entry and exit calls around a call to the original routine, where the original routine is called using PIN_CallApplicationFunction.
However, as far as I can tell PIN_CallApplicationFunction requires that I state in advance all of the arguments for the routine that I am wrapping, e.g., for malloc I would need to explicitly pass in some size_t argument, whereas for free I would pass in a pointer, and so on.
As I just want to wrap all function calls, I don't know the arguments! Is there some way to simply jump into the original function that I replaced, passing along the arguments for the original signature? Or perhaps some better way to do this?
Thanks for any help!
The problem with IPOINT_BEFORE, IPOINT_AFTER is that IPOINT_AFTER may miss some ret instructions. RTN_Replace functions will require a function pointer having the same signature as original (as you do not want to modify the default code).
A simple solution could be instrument all 'call' and 'ret' instructions. use INS_Rtn function to find out the routine name. This way you can instrument all functions without bothering for each function signature.

Is function invocation at translation time valid?

I'm trying to achive a function to be called only one time. But I want to save the if (firstTime) check.
What I'm thinking about was:
while (1)
{
foo();
}
foo()
{
static int test = 1, srand (test);
test++;
}
But I couldn't find anything in the standard what is covering this.
So I'm not sure about, this is undefined. And if not so, will srand be invoked as expected? If not so, is it (as the main question is) even possible to invoke functioncalls on translationtime (what would more be, behave as if), as I'm doing here?
As an option to a first time flag, you could use a pointer to function that is initially set to the first time function, which in turn would set the pointer to function to the actual function. There's a level of indirection, but it eliminates a conditional branch.
A more general version of this idea is to use the pointer to function as a "state machine", where each function "advances" (sets) the pointer to the next state (the next function as part of a series of functions). This can be handy for event or interrupt driven code. I've used this method for device drivers and embedded code.
Your idea is probably that using a function call as an initializer for a static variable would call that function only once a program startup.
No, this is not possible in C, only constants are allowed in that context. In C++ this would be possible, and the compiler applies some secret wisdom to know in which order such initializations are effected.

Conditionally replacing a C function at runtime

Is it possible to conditionally replace a function at runtime in C (in particular, a function in a dynamically loaded library)?
I know that you can use LD_PRELOAD or just make a function of the same name, such as:
// Silly example intercepting exit
typedef void (*exit_func)(int code);
void exit(int code)
{
exit_func orig_exit = (exit_func)dlsym(RTLD_NEXT, "exit");
NSLog(#"EXIT CALLED WITH CODE %d!!!!", code);
orig_exit(code);
}
However, is it possible to CONDITIONALLY replace a function, at runtime, after the program has loaded and is running?
if(some_condition)
{
swap_impementations(exit, my_exit);
}
Edit: This is somewhat similar to Is it possible to swap C functions? but specifically, I am trying to intercept a call to a function from a different library that was loaded by the operating system.
What this means is that, for example, were I to intercept the exit() function from stdlib, ANY call to exit() from ANYWHERE would call my implementation instead of the original, much like my example above, except controllable at runtime.
There have been suggestions of hooking the call by overwriting the original with a jump instruction, but I was hoping for something that doesn't require stomping on executable memory, like perhaps there was something I could call in the dynamic linker to "re-link" the function after the program starts and point it somewhere else?
Use function pointer for this purpose.

Lua/C binding, binding from lua

I'm currently building a lua event system (in lua), however I want to be able to fire events from C too, I was wanting to bind a C function to a lua function, such that the C function could fire events in lua, I was planning to use the:
lua_register
function; however I can't seem to find a way to bind my lua function like this, it would seem I'm in need of a lua function that does the same, but from the lua side, I was thinking about making some hack, by binding a C function into lua, that simply calls 'lua_register', but this seems a bit unsafe to me.
So what should I do instead?
I'm not fully sure I understand what you've asked for. So allow me to explain what I think your question is.
You have some Lua code. In that Lua code, you have a system. This system is, at some point, given one or more events. For each event that it is given, it calls some function or functions that were registered to be called when that particular event was given.
So, this system has two basic functions:
EventSystem:RegisterEventHandler(EventName, Func);
EventSystem:FireEvent(EventName, ...);
The RegisterEventHandler method will associate the given Func with the given EventName, such that when FireEvent is called later, Func will be called if the EventName given to FireEvent is the same one Func was registered with.
Now you want to have C code be able to register C functions as event handlers. So it's time to talk about registering C functions in Lua.
The C API call lua_register is actually a macro. It creates a C function on the Lua stack, then puts it in the global table, using the string index given to lua_register. These are two separate operations; lua_register is just a convenience function that makes them the same.
What you want is to call RegisterEventHandler from C code, passing the C function as the third parameter (remember: the first parameter is self, because I called RegisterEventHandler with : instead of .. If you're using a global event system rather than an object oriented one, you only have two parameters). This requires two things:
You have to know how to call Lua functions from C code.
You have to know how to pass a C function to Lua code.
Step 1: It's all done via the Lua stack (I'll assume you know how that works. If not, I have a pretty substantial answer that explains most everything you might want to know about it).
The first thing you need to do is get the function you want to call onto the stack. To do that, you need to get an event system object (again, if your event system is global, just get the global table) and push it onto the stack. How you do that depends on where your event system objects are stored. Presumably you can get them through the global table.
Once you have the event system on the stack, you just index it with the "RegisterEventHandler" string, which will return to you the Lua function we need.
Next, we push our parameters onto the stack, from first to last. The first parameter is the event system object; it's probably still on the stack, so we can copy it. The second is the event name, and that's easy to push. The third is the C function. Which leads us to:
Step 2: lua_register is not going to get the job done. It's too heavy handed; it puts the C function in the global table. We need it on the stack. So we must use a lower level function: lua_pushcclosure. Or lua_pushcfunction, if you don't need upvalues.
These functions take a C function, wrap it up in Lua, and push it onto the Lua stack.
Now that the 3 parameters are on the stack, we can call the event registration function with a call to lua_pcall. Or your favorite Lua function calling function; however you wish to do it. Lua will consume the 3 parameters and the function itself, so that they are no longer on the stack.
And since the event registration function probably doesn't return values, the stack will be where it was right before we got the function onto the stack (but not before we started, depending on how much cleanup was done while getting the function).
After this, your C function will be registered with the event handler for that event name.

Resources