codeql-coding-standards icon indicating copy to clipboard operation
codeql-coding-standards copied to clipboard

`A7-1-7`: Exclude expression statements in macros

Open lcartey opened this issue 8 months ago • 0 comments

Affected rules

  • A7-1-7

Description

Macro expansion can cause multiple expressions and statements to appear at the same location. We exclude macro expanded declarations, I think we should do the same for expression statements.

Reviewing the query, I think this is actually caused by a bracketing issue:

    not isAffectedByMacro() and
   // MISSING OPENING BRACKET HERE
    exists(Declaration d |
       ...
    )
    or
    this instanceof ExprStmt and
    not exists(ForStmt f | f.getInitialization().getAChild*() = this) and
    not exists(LambdaExpression l | l.getLambdaFunction().getBlock().getAChild*() = this)
   // MISSING CLOSED BRACKET HERE

There's also an interesting thing happening here with locations - as we might expect such macro expansions to by the not l1 = l2 line in the select clause:

  exists(Location l1, Location l2 |
    e1.getLocation() = l1 and
    e2.getLocation() = l2 and
    not l1 = l2 and
....

The reason this doesn't exclude this case is that when we expand the macro, we may provide different locations for the expressions and statements within, if we can associate them with a specific macro parameter.

Example

#define foo(x, y)                                                              \
  x++;                                                                         \
  y++;

void test_macro() {
  int a = 1;
  int b = 1;
  foo(a, b); // COMPLIANT
}

lcartey avatar Jun 26 '24 10:06 lcartey