Override gcov functions to get executed code lines

I'm want to get all executed code lines of project using gcov. For example code like:

int main()
{
   int i=0;
   for(i=0;i<3;i++)printf("Hello");
   return 0;
}

And result will be like:

1)int i=0;
2)for(i=0;i<3;i++)
3)printf("Hello");
4)for(i=0;i<3;i++)
5)printf("Hello");
6)for(i=0;i<3;i++)
7)printf("Hello");
8)for(i=0;i<3;i++)
9)return 0;

The main idea is to make own implementation of gcov functions by rewriting libgcov. After that use it in combination gcc -fprofile-arcs -ftest-coverage test.c -o test -lanothergcov .

So, is it right to do such thing or it will not work, also has anyone any experience working with source code of gcov to get from it needed info, which it doesn't provide?


That's not possible with simply rewriting libgcov. You'd have to rewrite the corresponding gcc code that injects the counter increment instruction inbetween every line.

After instrumentation your code will execute essentially as:

 crt0: 
     __gcov_init(main_locals);
     main();
     __gcov_exit(); // dump the counters to files

 int main() {
     static GcovStruct_t local;
     local.Counter[0]++;
     for (i=0;i<3;i++) {
     local.Counter[1]++;
     printf("Hello");
     local.Counter[2]++;
     }
     local.Counter[3]++;
 }

There maybe something to do though, as you can use
<prompt> gcc -S -fprofile-arcs -ftest-coverage to get the intermediate .s file:

    movq    .LPBX1(%rip), %rax
    addq    $1, %rax
    movq    %rax, .LPBX1(%rip)

This could be almost trivial to modify by search & replace into:

    movq    .LPBX1(%rip), %rax   -> leaq    .LPBX1(%rip), %rax
    addq     $1, %rax            -> pushq %rax
                                    call     __init_add_line_number_to_list
    movq    %rax, .LPBX1(%rip)   -> -- remove this --

Then you'd require the newly introduced routine to increment the qword pointer and to insert that address to some extra structure that would be processed by the gcov tools that you'd modify next.

链接地址: http://www.djcxy.com/p/37968.html

上一篇: GCOV静态库覆盖了C源代码

下一篇: 覆盖gcov函数以获得执行的代码行