-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsageAnalyzer.cpp
More file actions
1410 lines (1278 loc) · 58.4 KB
/
StackUsageAnalyzer.cpp
File metadata and controls
1410 lines (1278 loc) · 58.4 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "StackUsageAnalyzer.hpp"
#include <chrono>
#include <cstdint>
#include <map>
#include <string>
#include <vector>
#include <unordered_set>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <llvm/ADT/DenseMap.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/CFG.h>
#include <llvm/IR/DebugInfoMetadata.h>
#include "analysis/AllocaUsage.hpp"
#include "analysis/AnalyzerUtils.hpp"
#include "analysis/ConstParamAnalysis.hpp"
#include "analysis/DuplicateIfCondition.hpp"
#include "analysis/DynamicAlloca.hpp"
#include "analysis/FunctionFilter.hpp"
#include "analysis/InputPipeline.hpp"
#include "analysis/IRValueUtils.hpp"
#include "analysis/InvalidBaseReconstruction.hpp"
#include "analysis/MemIntrinsicOverflow.hpp"
#include "analysis/SizeMinusKWrites.hpp"
#include "analysis/StackBufferAnalysis.hpp"
#include "analysis/StackComputation.hpp"
#include "analysis/StackPointerEscape.hpp"
#include "analysis/UninitializedVarAnalysis.hpp"
#include "passes/ModulePasses.hpp"
namespace ctrace::stack
{
namespace
{
struct SourceLocation
{
unsigned line = 0;
unsigned column = 0;
};
struct FunctionAuxData
{
llvm::DenseMap<const llvm::Function*, SourceLocation> locations;
llvm::DenseMap<const llvm::Function*, std::string> callPaths;
llvm::DenseMap<const llvm::Function*, std::vector<std::pair<std::string, StackSize>>>
localAllocas;
llvm::DenseMap<const llvm::Function*, std::size_t> indices;
};
struct ModuleAnalysisContext
{
llvm::Module& mod;
const AnalysisConfig& config;
const llvm::DataLayout* dataLayout = nullptr;
analysis::FunctionFilter filter;
std::vector<llvm::Function*> functions;
std::unordered_set<const llvm::Function*> functionSet;
std::vector<llvm::Function*> allDefinedFunctions;
std::unordered_set<const llvm::Function*> allDefinedSet;
bool shouldAnalyze(const llvm::Function& F) const
{
return functionSet.find(&F) != functionSet.end();
}
bool isDefined(const llvm::Function& F) const
{
return allDefinedSet.find(&F) != allDefinedSet.end();
}
};
using LocalStackMap = std::map<const llvm::Function*, analysis::LocalStackInfo>;
static ModuleAnalysisContext buildContext(llvm::Module& mod, const AnalysisConfig& config)
{
ModuleAnalysisContext ctx{mod, config, &mod.getDataLayout(),
analysis::buildFunctionFilter(mod, config)};
for (llvm::Function& F : mod)
{
if (F.isDeclaration())
continue;
ctx.allDefinedFunctions.push_back(&F);
if (ctx.filter.shouldAnalyze(F))
ctx.functions.push_back(&F);
}
ctx.allDefinedSet.reserve(ctx.allDefinedFunctions.size());
for (const llvm::Function* F : ctx.allDefinedFunctions)
{
ctx.allDefinedSet.insert(F);
}
ctx.functionSet.reserve(ctx.functions.size());
for (const llvm::Function* F : ctx.functions)
{
ctx.functionSet.insert(F);
}
return ctx;
}
static LocalStackMap computeLocalStacks(const ModuleAnalysisContext& ctx)
{
LocalStackMap localStack;
for (llvm::Function* F : ctx.allDefinedFunctions)
{
analysis::LocalStackInfo info =
analysis::computeLocalStack(*F, *ctx.dataLayout, ctx.config.mode);
localStack[F] = info;
}
return localStack;
}
static analysis::CallGraph buildCallGraphFiltered(const ModuleAnalysisContext& ctx)
{
analysis::CallGraph CG;
for (llvm::Function* F : ctx.allDefinedFunctions)
{
auto& vec = CG[F];
for (llvm::BasicBlock& BB : *F)
{
for (llvm::Instruction& I : BB)
{
const llvm::Function* Callee = nullptr;
if (auto* CI = llvm::dyn_cast<llvm::CallInst>(&I))
{
Callee = CI->getCalledFunction();
}
else if (auto* II = llvm::dyn_cast<llvm::InvokeInst>(&I))
{
Callee = II->getCalledFunction();
}
if (Callee && !Callee->isDeclaration() && ctx.isDefined(*Callee))
{
vec.push_back(Callee);
}
}
}
}
return CG;
}
static analysis::InternalAnalysisState
computeRecursionState(const ModuleAnalysisContext& ctx, const analysis::CallGraph& CG,
const LocalStackMap& localStack)
{
analysis::InternalAnalysisState state =
analysis::computeGlobalStackUsage(CG, localStack);
for (llvm::Function* F : ctx.allDefinedFunctions)
{
const llvm::Function* Fn = F;
if (!state.RecursiveFuncs.count(Fn))
continue;
if (analysis::detectInfiniteSelfRecursion(*F))
{
state.InfiniteRecursionFuncs.insert(Fn);
}
}
return state;
}
static AnalysisResult buildResults(const ModuleAnalysisContext& ctx,
const LocalStackMap& localStack,
const analysis::InternalAnalysisState& state,
const analysis::CallGraph& CG, FunctionAuxData& aux)
{
AnalysisResult result;
result.config = ctx.config;
for (llvm::Function* F : ctx.functions)
{
const llvm::Function* Fn = F;
analysis::LocalStackInfo localInfo;
analysis::StackEstimate totalInfo;
auto itLocal = localStack.find(Fn);
if (itLocal != localStack.end())
localInfo = itLocal->second;
auto itTotal = state.TotalStack.find(Fn);
if (itTotal != state.TotalStack.end())
totalInfo = itTotal->second;
FunctionResult fr;
fr.name = F->getName().str();
fr.filePath = analysis::getFunctionSourcePath(*F);
if (fr.filePath.empty() && !ctx.filter.moduleSourcePath.empty())
fr.filePath = ctx.filter.moduleSourcePath;
fr.localStack = localInfo.bytes;
fr.localStackUnknown = localInfo.unknown;
fr.maxStack = totalInfo.bytes;
fr.maxStackUnknown = totalInfo.unknown;
fr.hasDynamicAlloca = localInfo.hasDynamicAlloca;
fr.isRecursive = state.RecursiveFuncs.count(Fn) != 0;
fr.hasInfiniteSelfRecursion = state.InfiniteRecursionFuncs.count(Fn) != 0;
fr.exceedsLimit = (!fr.maxStackUnknown && totalInfo.bytes > ctx.config.stackLimit);
unsigned line = 0;
unsigned column = 0;
if (analysis::getFunctionSourceLocation(*F, line, column))
{
aux.locations[Fn] = {line, column};
}
if (!fr.isRecursive && totalInfo.bytes > localInfo.bytes)
{
std::string path = analysis::buildMaxStackCallPath(Fn, CG, state);
if (!path.empty())
aux.callPaths[Fn] = path;
}
if (!localInfo.localAllocas.empty())
{
aux.localAllocas[Fn] = localInfo.localAllocas;
}
result.functions.push_back(std::move(fr));
aux.indices[Fn] = result.functions.size() - 1;
}
return result;
}
static void emitSummaryDiagnostics(AnalysisResult& result, const ModuleAnalysisContext& ctx,
const FunctionAuxData& aux)
{
for (const llvm::Function* Fn : ctx.functions)
{
auto itIndex = aux.indices.find(Fn);
if (itIndex == aux.indices.end())
continue;
const std::size_t index = itIndex->second;
if (index >= result.functions.size())
continue;
const FunctionResult& fr = result.functions[index];
if (fr.isRecursive)
{
Diagnostic diag;
diag.funcName = fr.name;
diag.filePath = fr.filePath;
diag.severity = DiagnosticSeverity::Warning;
diag.errCode = DescriptiveErrorCode::None;
diag.message = " [!] recursive or mutually recursive function detected\n";
result.diagnostics.push_back(std::move(diag));
}
if (fr.hasInfiniteSelfRecursion)
{
Diagnostic diag;
diag.funcName = fr.name;
diag.filePath = fr.filePath;
diag.severity = DiagnosticSeverity::Warning;
diag.errCode = DescriptiveErrorCode::None;
diag.message = " [!!!] unconditional self recursion detected (no base case)\n"
" this will eventually overflow the stack at runtime\n";
result.diagnostics.push_back(std::move(diag));
}
if (fr.exceedsLimit)
{
Diagnostic diag;
diag.funcName = fr.name;
diag.filePath = fr.filePath;
diag.severity = DiagnosticSeverity::Warning;
diag.errCode = DescriptiveErrorCode::None;
auto itLoc = aux.locations.find(Fn);
if (itLoc != aux.locations.end())
{
diag.line = itLoc->second.line;
diag.column = itLoc->second.column;
}
std::string message;
bool suppressLocation = false;
StackSize maxCallee =
(fr.maxStack > fr.localStack) ? (fr.maxStack - fr.localStack) : 0;
auto itLocals = aux.localAllocas.find(Fn);
std::string aliasLine;
if (fr.localStack >= maxCallee && itLocals != aux.localAllocas.end())
{
std::string localsDetails;
std::string singleName;
StackSize singleSize = 0;
for (const auto& entry : itLocals->second)
{
if (entry.first == "<unnamed>")
continue;
if (entry.second >= ctx.config.stackLimit && entry.second > singleSize)
{
singleName = entry.first;
singleSize = entry.second;
}
}
if (!singleName.empty())
{
aliasLine = " alias path: " + singleName + "\n";
}
else if (!itLocals->second.empty())
{
localsDetails +=
" locals: " + std::to_string(itLocals->second.size()) +
" variables (total " + std::to_string(fr.localStack) + " bytes)\n";
std::vector<std::pair<std::string, StackSize>> named = itLocals->second;
named.erase(std::remove_if(named.begin(), named.end(), [](const auto& v)
{ return v.first == "<unnamed>"; }),
named.end());
std::sort(named.begin(), named.end(),
[](const auto& a, const auto& b)
{
if (a.second != b.second)
return a.second > b.second;
return a.first < b.first;
});
if (!named.empty())
{
constexpr std::size_t kMaxLocalsForLocation = 5;
if (named.size() > kMaxLocalsForLocation)
suppressLocation = true;
std::string listLine = " locals list: ";
for (std::size_t idx = 0; idx < named.size(); ++idx)
{
if (idx > 0)
listLine += ", ";
listLine += named[idx].first + "(" +
std::to_string(named[idx].second) + ")";
}
localsDetails += listLine + "\n";
}
}
if (!localsDetails.empty())
message += localsDetails;
}
auto itPath = aux.callPaths.find(Fn);
std::string suffix;
if (itPath != aux.callPaths.end())
{
suffix += " path: " + itPath->second + "\n";
}
std::string mainLine = " [!] potential stack overflow: exceeds limit of " +
std::to_string(ctx.config.stackLimit) + " bytes\n";
message = mainLine + aliasLine + suffix + message;
if (suppressLocation)
{
diag.line = 0;
diag.column = 0;
}
diag.message = std::move(message);
result.diagnostics.push_back(std::move(diag));
}
}
}
static void appendStackBufferDiagnostics(
AnalysisResult& result,
const std::vector<analysis::StackBufferOverflowIssue>& bufferIssues)
{
for (const auto& issue : bufferIssues)
{
unsigned line = 0;
unsigned column = 0;
unsigned startLine = 0;
unsigned startColumn = 0;
unsigned endLine = 0;
unsigned endColumn = 0;
bool haveLoc = false;
if (issue.inst)
{
llvm::DebugLoc DL = issue.inst->getDebugLoc();
if (DL)
{
line = DL.getLine();
startLine = DL.getLine();
startColumn = DL.getCol();
column = DL.getCol();
// By default, same as start
endLine = DL.getLine();
endColumn = DL.getCol();
haveLoc = true;
if (auto* loc = DL.get())
{
if (auto* scope = llvm::dyn_cast<llvm::DILocation>(loc))
{
if (scope->getColumn() != 0)
{
endColumn = scope->getColumn() + 1;
}
}
}
}
}
bool isUnreachable = false;
{
using namespace llvm;
if (issue.inst)
{
auto* BB = issue.inst->getParent();
// Walk block predecessors to see whether some
// have a conditional branch with a constant condition.
for (auto* Pred : predecessors(BB))
{
auto* BI = dyn_cast<BranchInst>(Pred->getTerminator());
if (!BI || !BI->isConditional())
continue;
auto* CI = dyn_cast<ICmpInst>(BI->getCondition());
if (!CI)
continue;
const llvm::Function& Func = *issue.inst->getFunction();
auto* C0 = analysis::tryGetConstFromValue(CI->getOperand(0), Func);
auto* C1 = analysis::tryGetConstFromValue(CI->getOperand(1), Func);
if (!C0 || !C1)
continue;
// Evaluate the ICmp result for these constants (homegrown implementation).
bool condTrue = false;
auto pred = CI->getPredicate();
const auto& v0 = C0->getValue();
const auto& v1 = C1->getValue();
switch (pred)
{
case ICmpInst::ICMP_EQ:
condTrue = (v0 == v1);
break;
case ICmpInst::ICMP_NE:
condTrue = (v0 != v1);
break;
case ICmpInst::ICMP_SLT:
condTrue = v0.slt(v1);
break;
case ICmpInst::ICMP_SLE:
condTrue = v0.sle(v1);
break;
case ICmpInst::ICMP_SGT:
condTrue = v0.sgt(v1);
break;
case ICmpInst::ICMP_SGE:
condTrue = v0.sge(v1);
break;
case ICmpInst::ICMP_ULT:
condTrue = v0.ult(v1);
break;
case ICmpInst::ICMP_ULE:
condTrue = v0.ule(v1);
break;
case ICmpInst::ICMP_UGT:
condTrue = v0.ugt(v1);
break;
case ICmpInst::ICMP_UGE:
condTrue = v0.uge(v1);
break;
default:
// Do not handle other exotic predicates here.
continue;
}
// Branch of the form:
// br i1 %cond, label %then, label %else
// Successor 0 taken if condTrue == true
// Successor 1 taken if condTrue == false
if (BB == BI->getSuccessor(0) && condTrue == false)
{
// The "then" block is never reached.
isUnreachable = true;
}
else if (BB == BI->getSuccessor(1) && condTrue == true)
{
// The "else" block is never reached.
isUnreachable = true;
}
}
}
}
std::ostringstream body;
Diagnostic diag;
if (issue.isLowerBoundViolation)
{
diag.errCode = DescriptiveErrorCode::NegativeStackIndex;
body << " [!!] potential negative index on variable '" << issue.varName
<< "' (size " << issue.arraySize << ")\n";
if (!issue.aliasPath.empty())
{
body << " alias path: " << issue.aliasPath << "\n";
}
body << " inferred lower bound for index expression: " << issue.lowerBound
<< " (index may be < 0)\n";
}
else
{
diag.errCode = DescriptiveErrorCode::StackBufferOverflow;
body << " [!!] potential stack buffer overflow on variable '" << issue.varName
<< "' (size " << issue.arraySize << ")\n";
if (!issue.aliasPath.empty())
{
body << " alias path: " << issue.aliasPath << "\n";
}
if (issue.indexIsConstant)
{
body << " constant index " << issue.indexOrUpperBound
<< " is out of bounds (0.."
<< (issue.arraySize ? issue.arraySize - 1 : 0) << ")\n";
}
else
{
body << " index variable may go up to " << issue.indexOrUpperBound
<< " (array last valid index: "
<< (issue.arraySize ? issue.arraySize - 1 : 0) << ")\n";
}
}
if (issue.isWrite)
{
body << " (this is a write access)\n";
}
else
{
body << " (this is a read access)\n";
}
if (isUnreachable)
{
body << " [info] this access appears unreachable at runtime "
"(condition is always false for this branch)\n";
}
diag.funcName = issue.funcName;
diag.line = haveLoc ? line : 0;
diag.column = haveLoc ? column : 0;
diag.startLine = haveLoc ? startLine : 0;
diag.startColumn = haveLoc ? startColumn : 0;
diag.endLine = haveLoc ? endLine : 0;
diag.endColumn = haveLoc ? endColumn : 0;
diag.severity = DiagnosticSeverity::Warning;
diag.message = body.str();
diag.variableAliasingVec = issue.aliasPathVec;
result.diagnostics.push_back(std::move(diag));
}
}
static void
appendDynamicAllocaDiagnostics(AnalysisResult& result,
const std::vector<analysis::DynamicAllocaIssue>& issues)
{
for (const auto& d : issues)
{
unsigned line = 0;
unsigned column = 0;
bool haveLoc = false;
if (d.allocaInst)
{
llvm::DebugLoc DL = d.allocaInst->getDebugLoc();
if (DL)
{
line = DL.getLine();
column = DL.getCol();
haveLoc = true;
}
}
std::ostringstream body;
body << " [!] dynamic stack allocation detected for variable '" << d.varName
<< "'\n";
body << " allocated type: " << d.typeName << "\n";
body << " size of this allocation is not compile-time constant "
"(VLA / variable alloca) and may lead to unbounded stack usage\n";
Diagnostic diag;
diag.funcName = d.funcName;
diag.line = haveLoc ? line : 0;
diag.column = haveLoc ? column : 0;
diag.severity = DiagnosticSeverity::Warning;
diag.errCode = DescriptiveErrorCode::VLAUsage;
diag.message = body.str();
result.diagnostics.push_back(std::move(diag));
}
}
static void
appendAllocaUsageDiagnostics(AnalysisResult& result, const AnalysisConfig& config,
StackSize allocaLargeThreshold,
const std::vector<analysis::AllocaUsageIssue>& issues)
{
for (const auto& a : issues)
{
unsigned line = 0;
unsigned column = 0;
bool haveLoc = false;
if (a.allocaInst)
{
llvm::DebugLoc DL = a.allocaInst->getDebugLoc();
if (DL)
{
line = DL.getLine();
column = DL.getCol();
haveLoc = true;
}
}
bool isOversized = false;
if (a.sizeIsConst && a.sizeBytes >= allocaLargeThreshold)
isOversized = true;
else if (a.hasUpperBound && a.upperBoundBytes >= allocaLargeThreshold)
isOversized = true;
else if (a.sizeIsConst && config.stackLimit != 0 &&
a.sizeBytes >= config.stackLimit)
isOversized = true;
std::ostringstream body;
Diagnostic diag;
diag.funcName = a.funcName;
diag.line = haveLoc ? line : 0;
diag.column = haveLoc ? column : 0;
if (isOversized)
{
diag.severity = DiagnosticSeverity::Error;
diag.errCode = DescriptiveErrorCode::AllocaTooLarge;
body << " [!!] large alloca on the stack for variable '" << a.varName << "'\n";
}
else if (a.userControlled)
{
diag.severity = DiagnosticSeverity::Warning;
diag.errCode = DescriptiveErrorCode::AllocaUserControlled;
body << " [!!] user-controlled alloca size for variable '" << a.varName
<< "'\n";
}
else
{
diag.severity = DiagnosticSeverity::Warning;
diag.errCode = DescriptiveErrorCode::AllocaUsageWarning;
body << " [!] dynamic alloca on the stack for variable '" << a.varName
<< "'\n";
}
body
<< " allocation performed via alloca/VLA; stack usage grows with runtime "
"value\n";
if (a.sizeIsConst)
{
body << " requested stack size: " << a.sizeBytes << " bytes\n";
}
else if (a.hasUpperBound)
{
body << " inferred upper bound for size: " << a.upperBoundBytes
<< " bytes\n";
}
else
{
body << " size is unbounded at compile time\n";
}
if (a.isInfiniteRecursive)
{
// Any alloca inside infinite recursion will blow the stack.
diag.severity = DiagnosticSeverity::Error;
body << " function is infinitely recursive; this alloca runs at every "
"frame and guarantees stack overflow\n";
}
else if (a.isRecursive)
{
// Controlled recursion still compounds stack usage across frames.
if (diag.severity != DiagnosticSeverity::Error &&
(isOversized || a.userControlled))
{
diag.severity = DiagnosticSeverity::Error;
}
body << " function is recursive; this allocation repeats at each "
"recursion "
"depth and can exhaust the stack\n";
}
if (isOversized)
{
body << " exceeds safety threshold of " << allocaLargeThreshold
<< " bytes";
if (config.stackLimit != 0)
{
body << " (stack limit: " << config.stackLimit << " bytes)";
}
body << "\n";
}
else if (a.userControlled)
{
body << " size depends on user-controlled input "
"(function argument or non-local value)\n";
}
else
{
body << " size does not appear user-controlled but remains "
"runtime-dependent\n";
}
diag.message = body.str();
result.diagnostics.push_back(std::move(diag));
}
}
static void
appendMemIntrinsicDiagnostics(AnalysisResult& result,
const std::vector<analysis::MemIntrinsicIssue>& issues)
{
for (const auto& m : issues)
{
unsigned line = 0;
unsigned column = 0;
bool haveLoc = false;
if (m.inst)
{
llvm::DebugLoc DL = m.inst->getDebugLoc();
if (DL)
{
line = DL.getLine();
column = DL.getCol();
haveLoc = true;
}
}
std::ostringstream body;
body << "Function: " << m.funcName;
if (haveLoc)
{
body << " (line " << line << ", column " << column << ")";
}
body << "\n";
body << " [!!] potential stack buffer overflow in " << m.intrinsicName
<< " on variable '" << m.varName << "'\n";
body << " destination stack buffer size: " << m.destSizeBytes << " bytes\n";
body << " requested " << m.lengthBytes << " bytes to be copied/initialized\n";
Diagnostic diag;
diag.funcName = m.funcName;
diag.line = haveLoc ? line : 0;
diag.column = haveLoc ? column : 0;
diag.severity = DiagnosticSeverity::Warning;
diag.message = body.str();
result.diagnostics.push_back(std::move(diag));
}
}
static void
appendSizeMinusKDiagnostics(AnalysisResult& result,
const std::vector<analysis::SizeMinusKWriteIssue>& issues)
{
for (const auto& s : issues)
{
unsigned line = 0;
unsigned column = 0;
bool haveLoc = false;
if (s.inst)
{
llvm::DebugLoc DL = s.inst->getDebugLoc();
if (DL)
{
line = DL.getLine();
column = DL.getCol();
haveLoc = true;
}
}
std::ostringstream body;
if (s.hasPointerDest)
{
body << " [!] potential unsafe write with length (size - " << s.k << ")";
}
else
{
body << " [!] potential unsafe size-" << s.k << " argument passed";
}
if (!s.sinkName.empty())
body << " in " << s.sinkName;
body << "\n";
if (s.hasPointerDest && !s.ptrNonNull)
body << " destination pointer may be null\n";
if (!s.sizeAboveK)
body << " size operand may be <= " << s.k << "\n";
Diagnostic diag;
diag.funcName = s.funcName;
diag.line = haveLoc ? line : 0;
diag.column = haveLoc ? column : 0;
diag.severity = DiagnosticSeverity::Warning;
diag.errCode = DescriptiveErrorCode::SizeMinusOneWrite;
diag.message = body.str();
result.diagnostics.push_back(std::move(diag));
}
}
static void
appendMultipleStoreDiagnostics(AnalysisResult& result,
const std::vector<analysis::MultipleStoreIssue>& issues)
{
for (const auto& ms : issues)
{
unsigned line = 0;
unsigned column = 0;
bool haveLoc = false;
if (ms.allocaInst)
{
llvm::DebugLoc DL = ms.allocaInst->getDebugLoc();
if (DL)
{
line = DL.getLine();
column = DL.getCol();
haveLoc = true;
}
}
std::ostringstream body;
Diagnostic diag;
body << " [!Info] multiple stores to stack buffer '" << ms.varName
<< "' in this function (" << ms.storeCount << " store instruction(s)";
diag.errCode = DescriptiveErrorCode::MultipleStoresToStackBuffer;
if (ms.distinctIndexCount > 0)
{
body << ", " << ms.distinctIndexCount << " distinct index expression(s)";
}
body << ")\n";
if (ms.distinctIndexCount == 1)
{
body << " all stores use the same index expression "
"(possible redundant or unintended overwrite)\n";
}
else if (ms.distinctIndexCount > 1)
{
body << " stores use different index expressions; "
"verify indices are correct and non-overlapping\n";
}
diag.funcName = ms.funcName;
diag.line = haveLoc ? line : 0;
diag.column = haveLoc ? column : 0;
diag.severity = DiagnosticSeverity::Info;
diag.message = body.str();
result.diagnostics.push_back(std::move(diag));
}
}
static void appendDuplicateIfConditionDiagnostics(
AnalysisResult& result, const std::vector<analysis::DuplicateIfConditionIssue>& issues)
{
for (const auto& issue : issues)
{
unsigned line = 0;
unsigned column = 0;
unsigned startLine = 0;
unsigned startColumn = 0;
unsigned endLine = 0;
unsigned endColumn = 0;
bool haveLoc = false;
if (issue.conditionInst)
{
llvm::DebugLoc DL = issue.conditionInst->getDebugLoc();
if (DL)
{
line = DL.getLine();
startLine = DL.getLine();
column = DL.getCol();
startColumn = DL.getCol();
endLine = DL.getLine();
endColumn = DL.getCol();
haveLoc = true;
if (auto* loc = DL.get())
{
if (auto* scope = llvm::dyn_cast<llvm::DILocation>(loc))
{
if (scope->getColumn() != 0)
{
endColumn = scope->getColumn() + 1;
}
}
}
}
}
std::ostringstream body;
body << " [!] unreachable else-if branch: condition is equivalent to a previous "
"'if' condition\n";
body << " else branch implies previous condition is false\n";
Diagnostic diag;
diag.funcName = issue.funcName;
diag.line = haveLoc ? line : 0;
diag.column = haveLoc ? column : 0;
diag.startLine = haveLoc ? startLine : 0;
diag.startColumn = haveLoc ? startColumn : 0;
diag.endLine = haveLoc ? endLine : 0;
diag.endColumn = haveLoc ? endColumn : 0;
diag.severity = DiagnosticSeverity::Warning;
diag.errCode = DescriptiveErrorCode::DuplicateIfCondition;
diag.ruleId = "DuplicateIfCondition";
diag.message = body.str();
result.diagnostics.push_back(std::move(diag));
}
}
static void appendUninitializedLocalReadDiagnostics(
AnalysisResult& result,
const std::vector<analysis::UninitializedLocalReadIssue>& issues)
{
for (const auto& issue : issues)
{
unsigned line = issue.line;
unsigned column = issue.column;
bool haveLoc = (line != 0);
if (issue.inst)
{
llvm::DebugLoc DL = issue.inst->getDebugLoc();
if (DL)
{
line = DL.getLine();
column = DL.getCol();
haveLoc = true;
}
}
std::ostringstream body;
if (issue.kind == analysis::UninitializedLocalIssueKind::ReadBeforeDefiniteInit)
{
body << " [!!] potential read of uninitialized local variable '"
<< issue.varName << "'\n";
body << " this load may execute before any definite initialization on "
"all control-flow paths\n";
}
else if (issue.kind ==
analysis::UninitializedLocalIssueKind::ReadBeforeDefiniteInitViaCall)
{
body << " [!!] potential read of uninitialized local variable '"
<< issue.varName << "'\n";
body
<< " this call may read the value before any definite initialization";
if (!issue.calleeName.empty())
{
body << " in '" << issue.calleeName << "'";
}
body << "\n";
}
else
{
body << " [!] local variable '" << issue.varName << "' is never initialized\n";
body << " declared without initializer and no definite write was found "
"in this function\n";
}
Diagnostic diag;
diag.funcName = issue.funcName;
diag.line = haveLoc ? line : 0;
diag.column = haveLoc ? column : 0;
diag.severity = DiagnosticSeverity::Warning;
diag.errCode = DescriptiveErrorCode::UninitializedLocalRead;
diag.ruleId =
(issue.kind == analysis::UninitializedLocalIssueKind::ReadBeforeDefiniteInit ||
issue.kind ==
analysis::UninitializedLocalIssueKind::ReadBeforeDefiniteInitViaCall)
? "UninitializedLocalRead"
: "UninitializedLocalVariable";
diag.confidence =
(issue.kind == analysis::UninitializedLocalIssueKind::NeverInitialized) ? 0.75
: 0.90;
diag.cweId = "CWE-457";
diag.message = body.str();
result.diagnostics.push_back(std::move(diag));
}
}
static void appendInvalidBaseReconstructionDiagnostics(
AnalysisResult& result,
const std::vector<analysis::InvalidBaseReconstructionIssue>& issues)
{
for (const auto& br : issues)
{