How to set a breakpoint in GDB where the function returns?

后端 未结 7 1419
孤独总比滥情好
孤独总比滥情好 2020-11-27 06:10

I have a C++ function which has many return statements at various places. How to set a breakpoint at the return statement where the function actually returns ?

And

7条回答
  •  死守一世寂寞
    2020-11-27 06:43

    If you can change the source code, you might use some dirty trick with the preprocessor:

    void on_return() {
    
    }
    
    #define return return on_return(), /* If the function has a return value != void */
    #define return return on_return()  /* If the function has a return value == void */
    
    /* <<<-- Insert your function here -->>> */
    
    #undef return
    

    Then set a breakpoint to on_return and go one frame up.

    Attention: This will not work, if a function does not return via a return statement. So ensure, that it's last line is a return.

    Example (shamelessly copied from C code, but will work also in C++):

    #include 
    
    /* Dummy function to place the breakpoint */
    void on_return(void) {
    
    }
    
    #define return return on_return()
    void myfun1(int a) {
        if (a > 10) return;
        printf("<10\n");
        return;   
    }
    #undef return
    
    #define return return on_return(),
    int myfun2(int a) {
        if (a < 0) return -1;
        if (a > 0) return 1;
        return 0;
    }
    #undef return
    
    
    int main(void)
    {
        myfun1(1);
        myfun2(2);
    }
    

    The first macro will change

    return;
    

    to

    return on_return();
    

    Which is valid, since on_return also returns void.

    The second macro will change

    return -1;
    

    to

    return on_return(), -1;
    

    Which will call on_return() and then return -1 (thanks to the ,-operator).

    This is a very dirty trick, but despite using backwards-stepping, it will work in multi-threaded environments and inlined functions, too.

提交回复
热议问题