how to track a stack var with static analyzer

Hi everyone,

I'm trying to track a stack variable using the static analyzer
by getting a symbol from function args.

In checkPostCall I do:

if (callEvent.getCalleeIdentifier() == IdentInfoTrackMem) {
     // ...
     auto s = callEvent.getArgSVal(0).getAsSymbol();
     if (s == nullptr) {
         std::cout << "nullptr" << std::endl;
     }
}

// this is function used to track the var
void trackMem(int *i) {
     *i = 0;
     printf("%i\n", *i);
}

The strange thing is that it workes fine when the variable passed to
trackMem is previously allocated with malloc. But when passing
a pointer to a stack variable to trackMem callEvent.getArgSVal(0).getAsSymbol() always evaluates to nullptr.

Hi everyone,

I’m trying to track a stack variable using the static analyzer
by getting a symbol from function args.

In checkPostCall I do:

if (callEvent.getCalleeIdentifier() == IdentInfoTrackMem) {
// …
auto s = callEvent.getArgSVal(0).getAsSymbol();
if (s == nullptr) {
std::cout << “nullptr” << std::endl;
}
}

// this is function used to track the var
void trackMem(int *i) {
*i = 0;
printf(“%i\n”, *i);
}

The strange thing is that it workes fine when the variable passed to
trackMem is previously allocated with malloc. But when passing
a pointer to a stack variable to trackMem callEvent.getArgSVal(0).getAsSymbol() always evaluates to nullptr.

The address of a stack variable is not a symbol. Take a look at this section of the Checker Developer Manual and examine the SVal that represents the 0-th argument.

http://clang-analyzer.llvm.org/checker_dev_manual.html#values

Thanks a lot!

One more question about this:
Is there a way to recognize the SVal in another context
where it's not passed as a pointer but as a value/dereferenced pointer?

I'd like to recognize when the stack variable is used in a branch like this (the var is passed to the comparison as lhs):

void MPISchemaChecker::checkBranchCondition(const Stmt *condition,
                                             CheckerContext &ctx) const {
     condition->dumpColor();
     if (const BinaryOperator *b = dyn_cast<BinaryOperator>(condition)) {
         if (b->isComparisonOp()) {
             Expr *LHS = b->getLHS();
             SVal Val = ctx.getSVal(LHS);
             ProgramStateRef progStateRef = ctx.getState();

             if (progStateRef->contains<RankVarsSet>(Val)) {
                 std::cout << "used in if branch" << std::endl;
             }
         }
     }