Reputation: 83
Could you Please provide me any example How to verify that a function X() is getting called from function Y() not from function Z()?
Using 'C' or assembly language?
Thanks in advance.
Update:02-03-2015
Suppose kernel source code there are so many drivers calling the same function, like driver source code of SPI (Serial Phepheral Interface) and GPIO (General Purpose Input Output) is calling same function say "bzero()".
void bzero(void *s, size_t n);
I am going to test SPI and GPIO driver (driver code can not be modified). For that I have written the test driver. I can only call the function exposed from my test driver.
uint8_t SPI_read_write(uint8_t byte_out, char *s) // Function 1 { bzero(s,sizeof(struct_global1)); return byte_in; }
uint8_t GPIO_read_write(uint8_t byte_out, char *s)// Function 2 { bzero(s,sizeof(struct_global2)); return byte_in; }
int main()// Test driver
{
SPI_read_write(arg1,arg2);// When I call this function from test driver it will call bzero
}
Both the finction SPI_read_write() and GPIO_read_write() function calls the "bzero" function. I need to ensure that "bzero" is getting called at any instance from SPI_read_write() function only.
I am not able to get which line is unclear? some function fun1() can be called from N number of other function. how to determine which function called fun1()?
Probably it is related to stack, link register...
Upvotes: -3
Views: 140
Reputation: 726649
There is no way to determine the name of the function that is calling your function. This is entirely by design, because functions are intended to provide an abstraction that encapsulates a computation or an activity that is independent of the invocation site. Therefore, if you want to know which function is calling your function, the caller needs to provide this information.
C99-compliant compilers provide a way to determine the name of the current function, which can be used to pass to the target function, like this:
#define X() x(__func__)
void x(const char* caller) {
printf("x() is called from %s()\n", caller);
}
void y() {
X();
}
void z() {
X();
}
The above prints
x() is called from y()
x() is called from z()
Upvotes: 2
Reputation: 4880
#include <execinfo.h>
#include <stdio.h>
void print_function(void *p) {
char cmd[128];
FILE *fp;
snprintf(cmd, sizeof(cmd), "addr2line -e %s -f %p", "print_caller", p);
fp = popen(cmd, "r");
if (fp) {
char buf[128];
while (fgets(buf, sizeof(buf), fp)) {
printf("%s", buf);
}
}
}
void Y()
{
print_function(__builtin_return_address(0));
}
void X()
{
Y();
}
int main()
{
X();
return 0;
}
$ gcc -g -o print_caller print_caller.c
$ ./print_caller
X
/home/viswesn/print_caller.c:24
I would also recommend you to view the man page of BACKTRACE() which may provide you more insight on how to view the functions that were called before getting in to the current funciton.
Upvotes: 0