fold/docs/internal/clang-analysis-api-research.md
trvon 585ae4e4ab
docs: clang API research, multi-language IR patterns, Rust-Clang parity gap analysis
- clang-analysis-api-research.md: AST nodes, CFG, type system, constant folding
- multi-language-ir-patterns.md: CodeQL shared engine, Infer SIL, Kani MIR→Goto-C
- rust-clang-scanning-parity.md: 9-component comparison table, 8 priority fixes
2026-05-28 20:08:38 -04:00

60 lines
2.4 KiB
Markdown

# Clang LibTooling API for Dynamic Symbolic Analysis
> Generated 2026-05-28. Research on Clang LibTooling APIs for fold's symbolic pipeline.
## AST Visitor Architecture
fold uses `RecursiveASTVisitor` to walk the Clang AST. Key node types for security analysis:
| Node | Security Relevance |
|------|-------------------|
| `DeclRefExpr` | Variable read — feeds symbolic env |
| `CallExpr` | Function call — interprocedural boundary |
| `MemberExpr` | Struct field access — pointer offset tracking |
| `ArraySubscriptExpr` | Array access — OOB detection |
| `ConditionalOperator` | Ternary — path predicate forking |
| `BinaryOperator` | Arithmetic, comparison, logical |
| `UnaryOperator` | Deref (`*p`), address-of (`&x`) |
| `CXXMemberCallExpr` | Method call — virtual dispatch |
| `CXXConstructExpr` | Object construction — HeapModel allocation |
| `CXXDeleteExpr` | Deallocation — use-after-free tracking |
| `ReturnStmt` | Function exit — memory leak paths |
## CFG (Control Flow Graph)
`clang::CFG::buildCFG(Decl*, ASTContext*)` produces a `clang::CFG` with:
- **CFGBlock**: nodes containing `CFGElement`s (statements, initializers, destructors)
- **Successors/predecessors**: block-level edges for control flow
- **Terminator**: conditional branches at block end
fold's security walker uses a homegrown CFG walker (`src/detect/security_walker.cpp`) rather than clang's built-in CFG, to thread `SymbolicEnv` through blocks with path predicate splitting.
## Type System
`clang::QualType` provides:
- `getTypePtr()->isIntegerType()`, `isSignedIntegerType()`
- `ASTContext::getTypeSize(QualType)` — bit-width
- `ASTContext::getTypeAlign(QualType)` — alignment
fold uses `encoder_type_queries.cpp` for type queries.
## Constant Folding
- `Expr::EvaluateAsInt()` — computes integer constant expression
- `Expr::EvaluateAsFloat()` — float constant expression
- `Expr::isEvaluatable()` — check if constant-foldable
fold uses these in `encoder.cpp` for div-by-zero literal filtering.
## Source Location
- `clang::SourceManager` + `clang::SourceLocation` → file:line:col
- `clang::FullSourceLoc` for expanded locations
fold maps these through `clang_location_mapper.cpp` to its own `ir::SourceLoc`.
## Recommendations for fold
1. Use `clang::CFG` for dead-branch detection (UNSAT path predicates on CFG edges)
2. Leverage `CXXMemberCallExpr` for virtual dispatch resolution
3. Use `clang::ento::PathSensitive` checkers for taint tracking patterns