Skip to content

Commit 442fa76

Browse files
authored
Merge pull request #32 from CoreTrace/30-feat-add-compilation-database-support
30 feat add compilation database support
2 parents 835695a + 9f0a090 commit 442fa76

31 files changed

Lines changed: 1521 additions & 359 deletions

‎CMakeLists.txt‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ endif()
1414
set(CMAKE_CXX_STANDARD 20)
1515
set(CMAKE_CXX_STANDARD_REQUIRED ON)
1616
set(CMAKE_CXX_EXTENSIONS OFF)
17+
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
1718

1819
set(LLVM_LINK_LLVM_DYLIB ON)
1920

@@ -50,6 +51,7 @@ set(STACK_ANALYZER_SOURCES
5051
src/StackUsageAnalyzer.cpp
5152
src/analysis/AllocaUsage.cpp
5253
src/analysis/AnalyzerUtils.cpp
54+
src/analysis/CompileCommands.cpp
5355
src/analysis/ConstParamAnalysis.cpp
5456
src/analysis/DynamicAlloca.cpp
5557
src/analysis/FunctionFilter.cpp
@@ -150,8 +152,8 @@ if(BUILD_CLI)
150152
target_link_libraries(stack_usage_analyzer
151153
PRIVATE
152154
stack_usage_analyzer_lib
153-
# pas besoin de relinker cc::compilerlib_static ici,
154-
# il est déjà dans la lib
155+
# No need to relink cc::compilerlib_static here,
156+
# it is already linked into the library.
155157
)
156158

157159
if(ENABLE_DEBUG_ASAN)

‎README.md‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@
2020
./stack_usage_analyzer --mode=[abi/ir] test.[ll/c/cpp] other.[ll/c/cpp]
2121
./stack_usage_analyzer main.cpp -I./include
2222
./stack_usage_analyzer main.cpp -I./include --compile-arg=-I/opt/homebrew/opt/llvm@20/include
23+
./stack_usage_analyzer main.cpp --compile-commands=build/compile_commands.json
2324
./stack_usage_analyzer main.cpp -I./include --only-file=./main.cpp --only-function=main
25+
./stack_usage_analyzer main.cpp --dump-ir=./debug/main.ll
26+
./stack_usage_analyzer a.c b.c --dump-ir=./debug
2427
```
2528

2629
```
@@ -29,6 +32,11 @@
2932
--warnings-only keeps only important diagnostics
3033
--stack-limit=<value> overrides stack limit (bytes, or KiB/MiB/GiB)
3134
--compile-arg=<arg> passes an extra argument to the compiler
35+
--compile-commands=<path> uses compile_commands.json (file or directory)
36+
--compdb=<path> alias for --compile-commands
37+
--compdb-fast drops heavy build flags for faster analysis
38+
--timing prints compile/analysis timings to stderr
39+
--dump-ir=<path> writes LLVM IR to a file (or directory for multiple inputs)
3240
-I<dir> or -I <dir> adds an include directory
3341
-D<name>[=value] or -D <name>[=value] defines a macro
3442
--only-file=<path> or --only-file <path> filters by file
@@ -38,6 +46,13 @@
3846
--dump-filter prints filter decisions (stderr)
3947
```
4048

49+
To generate `compile_commands.json` with CMake, configure with
50+
`-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` and point to the resulting file
51+
(often under `build/`).
52+
53+
If analysis feels slow, `--compdb-fast` disables heavy flags (optimizations,
54+
sanitizers, profiling) while keeping include paths and macros.
55+
4156
### Example
4257

4358
Given this code:
@@ -142,7 +157,7 @@ Function: main
142157
Examples:
143158
```c
144159
char buf[10];
145-
return buf; // renvoi pointeur vers stack → use-after-return
160+
return buf; // returns pointer to stack -> use-after-return
146161
```
147162

148163
Or storing:

‎extern-project/src/main.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ int main(int argc, char **argv)
2222

2323
auto res = ctrace::stack::analyzeFile(filename, cfg, ctx, diag);
2424

25-
// Exemple : output SARIF sur stdout
25+
// Example: SARIF output to stdout
2626
std::cout << ctrace::stack::toSarif(res, filename) << std::endl;
2727

2828
return 0;

‎include/StackUsageAnalyzer.hpp‎

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@ namespace llvm
1515
class SMDiagnostic;
1616
} // namespace llvm
1717

18+
namespace ctrace::stack::analysis
19+
{
20+
class CompilationDatabase;
21+
} // namespace ctrace::stack::analysis
22+
1823
namespace ctrace::stack
1924
{
2025

@@ -26,33 +31,39 @@ namespace ctrace::stack
2631
ABI
2732
};
2833

29-
// Configuration de l'analyse (mode + limite de stack)
34+
// Analysis configuration (mode + stack limit).
3035
struct AnalysisConfig
3136
{
3237
AnalysisMode mode = AnalysisMode::IR;
33-
StackSize stackLimit = 8ull * 1024ull * 1024ull; // 8 MiB par défaut
38+
StackSize stackLimit = 8ull * 1024ull * 1024ull; // 8 MiB default
3439
bool quiet = false;
3540
bool warningsOnly = false;
3641
std::vector<std::string> extraCompileArgs;
42+
std::shared_ptr<const analysis::CompilationDatabase> compilationDatabase;
43+
bool requireCompilationDatabase = false;
44+
bool compdbFast = false;
45+
bool timing = false;
3746
std::vector<std::string> onlyFiles;
3847
std::vector<std::string> onlyDirs;
3948
std::vector<std::string> onlyFunctions;
4049
bool dumpFilter = false;
50+
std::string dumpIRPath;
51+
bool dumpIRIsDir = false;
4152
};
4253

43-
// Résultat par fonction
54+
// Per-function result
4455
struct FunctionResult
4556
{
4657
std::string filePath;
4758
std::string name;
48-
StackSize localStack = 0; // taille frame locale (suivant le mode)
49-
StackSize maxStack = 0; // max stack incluant les callees
50-
bool localStackUnknown = false; // taille locale inconnue (alloca dynamique)
51-
bool maxStackUnknown = false; // max stack inconnue (propagée via appels)
52-
bool hasDynamicAlloca = false; // alloca dynamique détectée dans la fonction
53-
54-
bool isRecursive = false; // dans un cycle F <-> G ...
55-
bool hasInfiniteSelfRecursion = false; // heuristique DominatorTree
59+
StackSize localStack = 0; // local frame size (depends on mode)
60+
StackSize maxStack = 0; // max stack including callees
61+
bool localStackUnknown = false; // unknown local size (dynamic alloca)
62+
bool maxStackUnknown = false; // unknown max stack (propagated via calls)
63+
bool hasDynamicAlloca = false; // dynamic alloca detected in the function
64+
65+
bool isRecursive = false; // part of a cycle F <-> G ...
66+
bool hasInfiniteSelfRecursion = false; // DominatorTree heuristic
5667
bool exceedsLimit = false; // maxStack > config.stackLimit
5768
};
5869

@@ -151,7 +162,7 @@ namespace ctrace::stack
151162
std::string message;
152163
};
153164

154-
// Résultat global pour un module
165+
// Global result for a module
155166
struct AnalysisResult
156167
{
157168
AnalysisConfig config;
@@ -162,22 +173,22 @@ namespace ctrace::stack
162173
std::vector<Diagnostic> diagnostics;
163174
};
164175

165-
// Serialize an AnalysisResult to a simple JSON format (pour CI / GitHub Actions).
166-
// `inputFile` : chemin du fichier analysé (celui que tu passes à analyzeFile).
176+
// Serialize an AnalysisResult to a simple JSON format (for CI / GitHub Actions).
177+
// `inputFile`: path of the analyzed file (the one you pass to analyzeFile).
167178
std::string toJson(const AnalysisResult& result, const std::string& inputFile);
168179
std::string toJson(const AnalysisResult& result, const std::vector<std::string>& inputFiles);
169180

170181
// Serialize an AnalysisResult to SARIF 2.1.0 (compatible GitHub Code Scanning).
171-
// `inputFile` : chemin du fichier analysé.
172-
// `toolName` / `toolVersion` : metadata du tool dans le SARIF.
182+
// `inputFile`: path of the analyzed file.
183+
// `toolName` / `toolVersion`: tool metadata in SARIF.
173184
std::string toSarif(const AnalysisResult& result, const std::string& inputFile,
174185
const std::string& toolName = "coretrace-stack-analyzer",
175186
const std::string& toolVersion = "0.1.0");
176187

177-
// Analyse un module déjà chargé (tu peux réutiliser dans d'autres outils)
188+
// Analyze an already loaded module (can be reused by other tools).
178189
AnalysisResult analyzeModule(llvm::Module& mod, const AnalysisConfig& config);
179190

180-
// Helper pratique : charge un .ll et appelle analyzeModule()
191+
// Convenience helper: load a .ll and call analyzeModule()
181192
AnalysisResult analyzeFile(const std::string& filename, const AnalysisConfig& config,
182193
llvm::LLVMContext& ctx, llvm::SMDiagnostic& err);
183194

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#pragma once
2+
3+
#include <memory>
4+
#include <string>
5+
#include <unordered_map>
6+
#include <vector>
7+
8+
namespace ctrace::stack::analysis
9+
{
10+
struct CompileCommand
11+
{
12+
std::string directory;
13+
std::vector<std::string> arguments;
14+
};
15+
16+
class CompilationDatabase
17+
{
18+
public:
19+
static std::shared_ptr<CompilationDatabase> loadFromFile(const std::string& path,
20+
std::string& error);
21+
22+
const CompileCommand* findCommandForFile(const std::string& filePath) const;
23+
24+
const std::string& sourcePath() const
25+
{
26+
return sourcePath_;
27+
}
28+
29+
private:
30+
std::string sourcePath_;
31+
std::unordered_map<std::string, CompileCommand> commands_;
32+
};
33+
} // namespace ctrace::stack::analysis

‎include/analysis/InvalidBaseReconstruction.hpp‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,11 @@ namespace ctrace::stack::analysis
1919
struct InvalidBaseReconstructionIssue
2020
{
2121
std::string funcName;
22-
std::string varName; // nom de la variable alloca (stack object)
23-
std::string sourceMember; // membre source (ex: "b")
24-
int64_t offsetUsed = 0; // offset utilisé dans le calcul (peut être négatif)
25-
std::string targetType; // type vers lequel on cast (ex: "struct A*")
26-
bool isOutOfBounds = false; // true si on peut prouver que c'est hors bornes
22+
std::string varName; // alloca variable name (stack object)
23+
std::string sourceMember; // source member (e.g., "b")
24+
int64_t offsetUsed = 0; // offset used in the calculation (can be negative)
25+
std::string targetType; // target cast type (e.g., "struct A*")
26+
bool isOutOfBounds = false; // true if we can prove it is out of bounds
2727
const llvm::Instruction* inst = nullptr;
2828
};
2929

‎include/analysis/SizeMinusKWrites.hpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ namespace ctrace::stack::analysis
1818
struct SizeMinusKWriteIssue
1919
{
2020
std::string funcName;
21-
std::string sinkName; // nom de l'appel ou "store"
21+
std::string sinkName; // call name or "store"
2222
bool ptrNonNull = false;
2323
bool sizeAboveK = false;
2424
bool hasPointerDest = true;

‎include/analysis/StackBufferAnalysis.hpp‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,14 @@ namespace ctrace::stack::analysis
2121
std::string funcName;
2222
std::string varName;
2323
StackSize arraySize = 0;
24-
StackSize indexOrUpperBound = 0; // utilisé pour les bornes sup (UB) ou index constant
24+
StackSize indexOrUpperBound = 0; // used for upper bounds (UB) or constant index
2525
bool isWrite = false;
2626
bool indexIsConstant = false;
2727
const llvm::Instruction* inst = nullptr;
2828

29-
// Violation basée sur une borne inférieure (index potentiellement négatif)
29+
// Violation based on a lower bound (index potentially negative)
3030
bool isLowerBoundViolation = false;
31-
long long lowerBound = 0; // borne inférieure déduite (signée)
31+
long long lowerBound = 0; // deduced lower bound (signed)
3232

3333
std::string aliasPath; // ex: "pp -> ptr -> buf"
3434
std::vector<std::string> aliasPathVec; // {"pp", "ptr", "buf"}
@@ -49,8 +49,8 @@ namespace ctrace::stack::analysis
4949
{
5050
std::string funcName;
5151
std::string varName;
52-
std::size_t storeCount = 0; // nombre total de StoreInst vers ce buffer
53-
std::size_t distinctIndexCount = 0; // nombre d'expressions d'index distinctes
52+
std::size_t storeCount = 0; // total number of StoreInsts into this buffer
53+
std::size_t distinctIndexCount = 0; // number of distinct index expressions
5454
const llvm::AllocaInst* allocaInst = nullptr;
5555
};
5656

‎include/analysis/StackComputation.hpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ namespace ctrace::stack::analysis
3333

3434
struct InternalAnalysisState
3535
{
36-
std::map<const llvm::Function*, StackEstimate> TotalStack; // stack max, callees inclus
37-
std::set<const llvm::Function*> RecursiveFuncs; // fonctions dans au moins un cycle
38-
std::set<const llvm::Function*> InfiniteRecursionFuncs; // auto-récursion “infinie”
36+
std::map<const llvm::Function*, StackEstimate> TotalStack; // max stack, including callees
37+
std::set<const llvm::Function*> RecursiveFuncs; // functions in at least one cycle
38+
std::set<const llvm::Function*> InfiniteRecursionFuncs; // “infinite” self-recursion
3939
};
4040

4141
CallGraph buildCallGraph(llvm::Module& M);

‎include/analysis/StackPointerEscape.hpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ namespace ctrace::stack::analysis
1919
std::string varName;
2020
std::string
2121
escapeKind; // "return", "store_global", "store_unknown", "call_arg", "call_callback"
22-
std::string targetName; // nom du global, si applicable
22+
std::string targetName; // global name, if applicable
2323
const llvm::Instruction* inst = nullptr;
2424
};
2525

0 commit comments

Comments
 (0)