Skip to content

Commit c607798

Browse files
committed
Add a library to support the detection of banned functions
This supports accurate detection of usage of banned functions: - Detects both accesses and calls - Reports the macro definition if the use is within a macro defined in the users code. - Otherwise reports the location of the expression.
1 parent 555fdec commit c607798

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* A library for supporting the consistent detection of banned functions in C++ code.
3+
*/
4+
5+
import cpp
6+
import AlertReporting
7+
8+
/**
9+
* A signature for a banned function.
10+
*/
11+
signature class BannedFunction extends Function;
12+
13+
/**
14+
* A module for detecting uses of banned functions in C++ code.
15+
*/
16+
module BannedFunctions<BannedFunction F> {
17+
final private class FinalExpr = Expr;
18+
19+
/**
20+
* An expression that uses a banned function.
21+
*
22+
* It can be either a function call or a function access (taking the address of the function).
23+
*/
24+
class UseExpr extends FinalExpr {
25+
string action;
26+
F bannedFunction;
27+
28+
UseExpr() {
29+
this.(FunctionCall).getTarget() = bannedFunction and
30+
action = "Call to"
31+
or
32+
this.(FunctionAccess).getTarget() = bannedFunction and
33+
action = "Address taken for"
34+
}
35+
36+
string getFunctionName() { result = bannedFunction.getName() }
37+
38+
string getAction() { result = action }
39+
40+
Element getPrimaryElement() {
41+
// If this is defined in a macro in the users source location, then report the macro
42+
// expansion, otherwise report the element itself. This ensures that we always report
43+
// the use of the terminating function, but combine usages when the macro is defined
44+
// by the user.
45+
exists(Element e | e = MacroUnwrapper<UseExpr>::unwrapElement(this) |
46+
if exists(e.getFile().getRelativePath()) then result = e else result = this
47+
)
48+
}
49+
}
50+
51+
final private class FinalElement = Element;
52+
53+
/**
54+
* A `Use` of a banned function.
55+
*
56+
* This is an `Element` in a program which represents the use of a banned function.
57+
* For uses within macro expansions, this may report the location of the macro, if
58+
* it is defined within the user's source code.
59+
*/
60+
class Use extends FinalElement {
61+
UseExpr use;
62+
63+
Use() { this = use.getPrimaryElement() }
64+
65+
string getFunctionName() { result = use.getFunctionName() }
66+
67+
string getAction() { result = use.getAction() }
68+
}
69+
}

0 commit comments

Comments
 (0)