2

I have inherited a large body of code from developers long departed from the company. Do methods exist that will let me test if the code is re-entrant, short of reading through it?

I want to run the apis in multiple threads but aren't 100% sure if the code is re-entrant.

EDIT: Changed title to add thread-safe as the desirable goal

3 Answers3

4

No. It's generally intractible to prove re-entrancy through execution.

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
1

In general you can't automatically reason about reentrancy and thread-safety because of external dependencies, but anyway there are some tools which can help:

What open source C++ static analysis tools are available?

Clang Thread Safety Analysis.

Community
  • 1
  • 1
Anton Savin
  • 38,277
  • 8
  • 49
  • 82
0

1) Test for reentrency;

Reentrency means: you can interrupt an execution of a function before it's finished, then safely call it again while the first insance is suspended, then resume the first instance. Re-entrency is not necessarily linked to threads: it's also relevant for single threads, especially for callback functions related to hardware/software interrupts/signals.

There is no black-box test that can detect specifically reentrency issues. Because the re-entrency issue might only appear dependeing on where you interupt the execution. Verification that it's re-entrant requires you to analyze the source code.

There are several hints that help to spot risks (although not through tests):

  • if a function uses static or global variables, there are risks that it's not reentrant (that's one of the reason why it's recommended to avoid these, whenever possible).

  • if functions depend on previous calls to functions but without transfering data structures that could hold the execution context. This suggest some hidden statics (typical example is strtok() ).

  • if some extern are defined in headers

But there indicators give no certainty. The only way to gain certainty is code analysis.

2) Thread-safety

Thread-safety is even more difficult to verify than reentrency issues. Because several invocation of your API can happen in parallel, each being executed at different speed, and the issues may only appear, depending on the ordering of reads and writes between the threads. How could you test that the synchronisation mechanisms work in all the cases ?

Again, the only way is the in-depth analysis of the code. And it's even more difficult than for re-entrency, because you have to take ito consideration complex synchronisation issues (ex: deadlocks), access to shared variable, and also potential hardware issues like processor memory cache.

Christophe
  • 54,708
  • 5
  • 52
  • 107