1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
|
//===- unittests/StaticAnalyzer/BlockEntranceCallbackTest.cpp -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "CheckerRegistration.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Analysis/ProgramPoint.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/raw_ostream.h"
#include "gtest/gtest.h"
using namespace clang;
using namespace ento;
namespace {
class BlockEntranceCallbackTester final : public Checker<check::BlockEntrance> {
const BugType Bug{this, "BlockEntranceTester"};
public:
void checkBlockEntrance(const BlockEntrance &Entrance,
CheckerContext &C) const {
ExplodedNode *Node = C.generateNonFatalErrorNode(C.getState());
if (!Node)
return;
const auto *FD =
cast<FunctionDecl>(C.getLocationContext()->getStackFrame()->getDecl());
std::string Description = llvm::formatv(
"Within '{0}' B{1} -> B{2}", FD->getIdentifier()->getName(),
Entrance.getPreviousBlock()->getBlockID(),
Entrance.getBlock()->getBlockID());
auto Report =
std::make_unique<PathSensitiveBugReport>(Bug, Description, Node);
C.emitReport(std::move(Report));
}
};
class BranchConditionCallbackTester final
: public Checker<check::BranchCondition> {
const BugType Bug{this, "BranchConditionCallbackTester"};
public:
void checkBranchCondition(const Stmt *Condition, CheckerContext &C) const {
ExplodedNode *Node = C.generateNonFatalErrorNode(C.getState());
if (!Node)
return;
const auto *FD =
cast<FunctionDecl>(C.getLocationContext()->getStackFrame()->getDecl());
std::string Buffer =
(llvm::Twine("Within '") + FD->getIdentifier()->getName() +
"': branch condition '")
.str();
llvm::raw_string_ostream OS(Buffer);
Condition->printPretty(OS, /*Helper=*/nullptr,
C.getASTContext().getPrintingPolicy());
OS << "'";
auto Report = std::make_unique<PathSensitiveBugReport>(Bug, Buffer, Node);
C.emitReport(std::move(Report));
C.addTransition();
}
};
template <typename Checker> void registerChecker(CheckerManager &Mgr) {
Mgr.registerChecker<Checker>();
}
bool shouldAlwaysRegister(const CheckerManager &) { return true; }
void addBlockEntranceTester(AnalysisASTConsumer &AnalysisConsumer,
AnalyzerOptions &AnOpts) {
AnOpts.CheckersAndPackages.emplace_back("test.BlockEntranceTester", true);
AnalysisConsumer.AddCheckerRegistrationFn([](CheckerRegistry &Registry) {
Registry.addChecker(®isterChecker<BlockEntranceCallbackTester>,
&shouldAlwaysRegister, "test.BlockEntranceTester",
"EmptyDescription");
});
}
void addBranchConditionTester(AnalysisASTConsumer &AnalysisConsumer,
AnalyzerOptions &AnOpts) {
AnOpts.CheckersAndPackages.emplace_back("test.BranchConditionTester", true);
AnalysisConsumer.AddCheckerRegistrationFn([](CheckerRegistry &Registry) {
Registry.addChecker(®isterChecker<BranchConditionCallbackTester>,
&shouldAlwaysRegister, "test.BranchConditionTester",
"EmptyDescription");
});
}
llvm::SmallVector<StringRef> parseEachDiag(StringRef Diags) {
llvm::SmallVector<StringRef> Fragments;
llvm::SplitString(Diags, Fragments, "\n");
// Drop the prefix like "test.BlockEntranceTester: " from each fragment.
for (StringRef &Fragment : Fragments) {
Fragment = Fragment.drop_until([](char Ch) { return Ch == ' '; });
Fragment.consume_front(" ");
}
llvm::sort(Fragments);
return Fragments;
}
template <AddCheckerFn Fn = addBlockEntranceTester, AddCheckerFn... Fns>
bool runChecker(const std::string &Code, std::string &Diags) {
std::string RawDiags;
bool Res = runCheckerOnCode<Fn, Fns...>(Code, RawDiags,
/*OnlyEmitWarnings=*/true);
llvm::raw_string_ostream OS(Diags);
llvm::interleave(parseEachDiag(RawDiags), OS, "\n");
return Res;
}
[[maybe_unused]] void dumpCFGAndEgraph(AnalysisASTConsumer &AnalysisConsumer,
AnalyzerOptions &AnOpts) {
AnOpts.CheckersAndPackages.emplace_back("debug.DumpCFG", true);
AnOpts.CheckersAndPackages.emplace_back("debug.ViewExplodedGraph", true);
}
/// Use this instead of \c runChecker to enable the debugging a test case.
template <AddCheckerFn... Fns>
[[maybe_unused]] bool debugChecker(const std::string &Code,
std::string &Diags) {
return runChecker<dumpCFGAndEgraph, Fns...>(Code, Diags);
}
std::string expected(SmallVector<StringRef> Diags) {
llvm::sort(Diags);
std::string Result;
llvm::raw_string_ostream OS(Result);
llvm::interleave(Diags, OS, "\n");
return Result;
}
TEST(BlockEntranceTester, FromEntryToExit) {
constexpr auto Code = R"cpp(
void top() {
// empty
})cpp";
std::string Diags;
// Use "debugChecker" instead of "runChecker" for debugging.
EXPECT_TRUE(runChecker(Code, Diags));
EXPECT_EQ(expected({"Within 'top' B1 -> B0"}), Diags);
}
TEST(BlockEntranceTester, SingleOpaqueIfCondition) {
constexpr auto Code = R"cpp(
bool coin();
int glob;
void top() {
if (coin()) {
glob = 1;
} else {
glob = 2;
}
glob = 3;
})cpp";
std::string Diags;
// Use "debugChecker" instead of "runChecker" for debugging.
EXPECT_TRUE(runChecker(Code, Diags));
EXPECT_EQ(expected({
"Within 'top' B1 -> B0",
"Within 'top' B2 -> B1",
"Within 'top' B3 -> B1",
"Within 'top' B4 -> B2",
"Within 'top' B4 -> B3",
"Within 'top' B5 -> B4",
}),
Diags);
// entry true exit
// B5 -------> B4 --> B2 --> B1 --> B0
// | ^
// | false |
// v |
// B3 -----------------------+
}
TEST(BlockEntranceTester, TrivialIfCondition) {
constexpr auto Code = R"cpp(
bool coin();
int glob;
void top() {
int cond = true;
if (cond) {
glob = 1;
} else {
glob = 2;
}
glob = 3;
})cpp";
std::string Diags;
// Use "debugChecker" instead of "runChecker" for debugging.
EXPECT_TRUE(runChecker(Code, Diags));
EXPECT_EQ(expected({
"Within 'top' B1 -> B0",
"Within 'top' B3 -> B1",
"Within 'top' B4 -> B3",
"Within 'top' B5 -> B4",
}),
Diags);
// entry true exit
// B5 ----------> B4 --> B3 --> B1 --> B0
}
TEST(BlockEntranceTester, AcrossFunctions) {
constexpr auto Code = R"cpp(
bool coin();
int glob;
void nested() { glob = 1; }
void top() {
glob = 0;
nested();
glob = 2;
})cpp";
std::string Diags;
// Use "debugChecker" instead of "runChecker" for debugging.
EXPECT_TRUE(runChecker(Code, Diags));
EXPECT_EQ(
expected({
// Going from the "top" entry artificial node to the "top" body.
// Ideally, we shouldn't observe this edge because it's artificial.
"Within 'top' B2 -> B1",
// We encounter the call to "nested()" in the "top" body, thus we have
// a "CallEnter" node, but importantly, we also elide the transition
// to the "entry" node of "nested()".
// We only see the edge from the "nested()" entry to the "nested()"
// body:
"Within 'nested' B2 -> B1",
// Once we return from "nested()", we transition to the "exit" node of
// "nested()":
"Within 'nested' B1 -> B0",
// We will eventually return to the "top" body, thus we transition to
// its "exit" node:
"Within 'top' B1 -> B0",
}),
Diags);
}
TEST(BlockEntranceTester, ShortCircuitingLogicalOperator) {
constexpr auto Code = R"cpp(
bool coin();
void top(int x) {
int v = 0;
if (coin() && (v = x)) {
v = 2;
}
v = 3;
})cpp";
// coin(): false
// +--------------------------------+
// entry | v exit
// +----+ +----+ +----+ +----+ +----+ +----+
// | B5 | --> | B4 | --> | B3 | --> | B2 | --> | B1 | --> | B0 |
// +----+ +----+ +----+ +----+ +----+ +----+
// | ^
// +---------------------+
// (v = x): false
std::string Diags;
// Use "debugChecker" instead of "runChecker" for debugging.
EXPECT_TRUE(runChecker(Code, Diags));
EXPECT_EQ(expected({
"Within 'top' B1 -> B0",
"Within 'top' B2 -> B1",
"Within 'top' B3 -> B1",
"Within 'top' B3 -> B2",
"Within 'top' B4 -> B1",
"Within 'top' B4 -> B3",
"Within 'top' B5 -> B4",
}),
Diags);
}
TEST(BlockEntranceTester, Switch) {
constexpr auto Code = R"cpp(
bool coin();
int top(int x) {
int v = 0;
switch (x) {
case 1: v = 10; break;
case 2: v = 20; break;
default: v = 30; break;
}
return v;
})cpp";
// +----+
// | B5 | -------------------------+
// +----+ |
// ^ [case 1] |
// entry | v exit
// +----+ +----+ [default] +----+ +----+ +----+
// | B6 | --> | B2 | ----------> | B3 | --> | B1 | --> | B0 |
// +----+ +----+ +----+ +----+ +----+
// | ^
// v [case 2] |
// +----+ |
// | B4 | -------------------------+
// +----+
std::string Diags;
// Use "debugChecker" instead of "runChecker" for debugging.
EXPECT_TRUE(runChecker(Code, Diags));
EXPECT_EQ(expected({
"Within 'top' B1 -> B0",
"Within 'top' B2 -> B3",
"Within 'top' B2 -> B4",
"Within 'top' B2 -> B5",
"Within 'top' B3 -> B1",
"Within 'top' B4 -> B1",
"Within 'top' B5 -> B1",
"Within 'top' B6 -> B2",
}),
Diags);
}
TEST(BlockEntranceTester, BlockEntranceVSBranchCondition) {
constexpr auto Code = R"cpp(
bool coin();
int top(int x) {
int v = 0;
switch (x) {
default: v = 30; break;
}
if (x == 6) {
v = 40;
}
return v;
})cpp";
std::string Diags;
// Use "debugChecker" instead of "runChecker" for debugging.
EXPECT_TRUE((runChecker<addBlockEntranceTester, addBranchConditionTester>(
Code, Diags)));
EXPECT_EQ(expected({
"Within 'top' B1 -> B0",
"Within 'top' B2 -> B1",
"Within 'top' B3 -> B1",
"Within 'top' B3 -> B2",
"Within 'top' B4 -> B5",
"Within 'top' B5 -> B3",
"Within 'top' B6 -> B4",
"Within 'top': branch condition 'x == 6'",
}),
Diags);
}
} // namespace
|