2

Given a C code and a variable in the C code (global or a local variable of a function), is there a way to find the functions which uses this variable? This should also show the accesses to the variable by a function if it is also accessed through a pointer.

Tried to extract info using LLVM IR but seems difficult.


int a = 2;
int array1 = {1,2,3};

int function1(int c, int d) {
   return c + d;
}

int function2 (int arg1[], int * p1, int *p2) {
   int a;
   return arg1[2]+ (*p1) +a + (*p2);
}

int main() {
   int e =2, f=3,g;

   g = function1(e,f);

   int array2[] = {1,2,3,4};

   g = function2(array1,&e,array2);

   return 0;
}
variables and the functions which uses them
globals:
a - none,
array1 - function2, main
local variables :
function2:a - function2,
main:e - main, function2,
main:f - main,
main:g - main,
main:array2 - main,function2
Steve Friedl
  • 3,929
  • 1
  • 23
  • 30
Macow tdy
  • 59
  • 6

1 Answers1

1

is there a way to find the functions which uses this variable

Your best shot will be to use IDE, most of them will be able to trace references to global variables.

Alternatively, you can use static analysis tool like cxref (the one matching https://linux.die.net/man/1/cxref). I used it long time ago, and it was useful. There is a documentation tool with the same name - which might work.

As last resort, if you do not have any other choice, comment the variable declaration, and try building the code. The compiler will raise an error on every bad reference. (Minor exception: locally scoped variables that hides global definitions may not raise an error).

show the accesses to the variable by a function if it is also accessed through a pointer.

This is extremely hard (impossible for real programs) with static analysis. Usually, this is done at runtime. Some debuggers (e.g. gdb watch) allow you to identify when a variable is being modified (including via pointers). With hardware support it is also possible to set 'read watch' in gdb. See gdb rwatch, and Can I set a breakpoint on 'memory access' in GDB?

dash-o
  • 13,723
  • 1
  • 10
  • 37