# Conditional dtrace based on stack



## Farhan Khan (Sep 21, 2017)

Is there a way to execute an if-statement only based on if a function exists in the stack?

Something like this:

```
fbt:kernel:ieee80211-whatever-here:entry{
    if (myfunction is in the stack) {
        // Do a print here
    }
}
```
I am trying to monitor a function call in the ieee80211 stack and only want to monitor it when it is called by a certain function or anywhere within a kernel module.

Thanks!


----------



## ralphbsz (Sep 21, 2017)

Looking at it purely from the programming language point of view, ignoring dtrace functionality:

There is no standard C or C++ way to do this.  Matter-of-fact, it is antithetical to good software design.  In object-oriented programming, one could simulate it by using virtual functions and calling via different objects; in non-OO standard C, the same thing could be done by changing the function signatures and passing an extra flag along.

On the other hand, it is possible (although not in a standard-conforming way) for a function to examine the call stack.  It's not even terribly difficult; most software engineers have at some point in their careers had to write a "dump stack trace" module which does exactly that.  One of the complexities is that the stack only contains "numbers" (pointers, integers, and floats), and to translate it into human-readable stuff (like the string "myfunction"), one needs to decode the debugging information that's in the object code.  Doable, but tedious.

Here is my suggestion: Modify "myfunction" to print a message on entry and exit.  Then modify the ieee80211-whatever-here:entry function from able to also print a message.  Now you have too many messages, because sometimes that function will be called without myfunction on the stack.  That's OK, write a little awk script that filters the output to only look for the following pattern: myfunction enters, then iee80211-whatever-here prints, then myfunction exits.


----------



## tobik@ (Sep 22, 2017)

Farhan Khan said:


> Is there a way to execute an if-statement only based on if a function exists in the stack?
> 
> Something like this:
> 
> ...


I don't really know DTrace that well, but can't you do something like this?

```
fbt:kernel:myfunction:entry
{
	self->myfunction_on_stack = 1
}

fbt:kernel:myfunction:return
{
	self->myfunction_on_stack = 0
}

fbt:kernel:ieee80211-whatever-here:entry
/self->myfunction_on_stack/
{
	// Do a print here
}
```


----------



## Farhan Khan (Sep 25, 2017)

That's exactly it! Set a variable to true (1) and later check if its set. Thanks a lot!


----------

