Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function call and parameter tracing - test case and mock generation

I have a large code base of quite old C code on an embedded system and unfortunately there are no automated test cases/suites. This makes restructuring and refactoring code a dangerous task.

Manually writing test cases is very time consuming, so I thought that it should be possible to automate at least some part of this process for instance by tracing all the function calls and recording of the input and output values. I could then use these values in the test cases (this would not work for all but at least for some functions). It would probably also be possible to create mock functions based on the gathered data.

Having such test cases would make refactoring a less dangerous activity.

Are there any solutions that already can do this? What would be the easiest way to get this to work if I had to code it myself?

I thought about using ctags to find the function definitions, and wrapping them in a function that records the parameter values. Another possibility would probably be a gcc compiler plugin.

like image 223
trenki Avatar asked Feb 23 '12 15:02

trenki


1 Answers

There is a gcc option "-finstrument-functions", which mechanism you can use to define your own callbacks for each funtion's entry/exit.

Google it and you can find many good examples.

[Edit] with this gcc option's call back you can only track the function's entry/exit,not the params. but with some tricks you may also track the params. (walk through the current frame pointer to get the param on the stack).

Here is an article talk about the idea of the implementation:

http://linuxgazette.net/151/melinte.html

Furthermore, depends on your embedded system, on linux you can try something like ltrace to show the params(like the strace way). There are many tools do the function trace work either in userspace or kernelspace on linux, ftrace/ust/ltrace/utrace/strace/systemtap/. Anyway, if you do not add any hard debugging code, it's not possible to display the params in the correct way. If you accept the efforts to add entry/exit debugging infomation, then it's much easier.

Also here is a similar thread talk about this problem.

Tool to trace local function calls in Linux

like image 101
Sam Liao Avatar answered Oct 20 '22 14:10

Sam Liao