Insert into C++ map leads to infinite recursion?

Viewed 188

I'm trying to write some code that will allow me to insert into a C++ map from an extern "C" function. The code is as follows:

class CFITracing {
    std::unordered_map<uintptr_t, uintptr_t> CallerCalleePairs;
    std::map<std::string, int> BranchResults;

public:
    void HandleCallerCallee(uintptr_t Caller, uintptr_t Callee);
    void HandleBranchResult(int cond, char* branchName);

    void printResults();
};

...

void CFITracing::HandleBranchResult(int cond, char* branchName) {
    std::string branchStr(branchName);
    printf("%s\n", "pre");

    /* segfault at this line, regardless of what string I use as a key (even "hi") */
    BranchResults[branchStr] = cond; 

    printf("%s\n", "success");
}

CFITracing CFIT;


__attribute__((used))
__attribute__((optnone))
extern "C" void __trace(int cond, char* branchName) {
    CFIT.HandleBranchResult(cond, branchName);
}


Calls to the __trace function are inserted into the binary via an LLVM pass I've written, which passes an int and char* to my code above.

On calls to __trace, "pre" is printed repeatedly until a segmentation fault occurs. GDB shows that, when the line with the map insert occurs, the code somehow loops and this line is called repeatedly until the segfault occurs.

When debugging via valgrind, the following error occurs:

==20881== Stack overflow in thread #1: can't grow stack to 0x1ffe801000
==20881== 
==20881== Process terminating with default action of signal 11 (SIGSEGV)
==20881==  Access not within mapped region at address 0x1FFE801FF8
==20881== Stack overflow in thread #1: can't grow stack to 0x1ffe801000
==20881==    at 0x58069A2: _IO_file_xsputn@@GLIBC_2.2.5 (fileops.c:1220)

The presence of a stack overflow, together with the repeated prints, make me think infinite recursion has been triggered. I think it's likely I've created some type of undefined behavior, but I'm not sure exactly how to write this code to prevent it, given that I need to insert into the map via this extern "C" __trace() function.

Thus, my questions are as follows: is there anything quick I can fix to prevent this behavior from taking place? If not, how should I aim to redesign this, given that I need to insert into the map via the extern "C" function? Thanks for your help!

0 Answers
Related