rllvm-query 0.8.0

Source-level queries over LLVM bitcode captured by rllvm
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
//! Shared `ProgramFacts`/`Session` builders for this crate's module tests.
//!
//! Kept in one module, rather than duplicated per test module, because Rust
//! test modules cannot import each other's `#[cfg(test)] mod tests` and more
//! than one submodule's tests build on these fixtures.

use std::path::PathBuf;

use rllvm_core::catalog::{CatalogOrigin, CatalogScope};

use crate::{
    bind::{BindingCandidate, BindingStatus, SymbolBinding},
    facts::{
        CallSiteFact, CallSiteId, CallTarget, FieldBasis, FieldEvidence, FieldRef, FunctionFact,
        FunctionId, Language, LanguageBasis, Linkage, ModuleAnalysis, ModuleReport, ProgramFacts,
        SourceLanguage, SourceLocation, SourceStatus, UseFact, UseKind,
    },
    index::Session,
};

pub(crate) fn function(
    module: &str,
    symbol: &str,
    is_definition: bool,
    linkage: Linkage,
) -> FunctionFact {
    FunctionFact {
        id: FunctionId {
            module_id: module.into(),
            symbol: symbol.into(),
        },
        is_definition,
        linkage,
        language: None,
        signature: "i32 (i32, i32)".into(),
        location: None,
        mapped_lines: Default::default(),
        alias_of: None,
    }
}

/// A definition in module `m`, attributed to `language` by its producer.
pub(crate) fn attributed(
    symbol: &str,
    linkage: Linkage,
    language: Option<Language>,
) -> FunctionFact {
    let mut fact = function("m", symbol, true, linkage);
    fact.language = language.map(|name| SourceLanguage {
        name,
        basis: LanguageBasis::Producer,
    });
    fact
}

/// A current, uninlined `file:line`. Only the two fields a fixture ever
/// varies are parameters; the rest are the defaults every caller wanted.
pub(crate) fn source_location(file: &str, line: u32) -> SourceLocation {
    SourceLocation {
        file: file.into(),
        directory: None,
        line,
        column: 1,
        source_status: SourceStatus::Current,
        status_basis: None,
        inlined_at: Vec::new(),
    }
}

pub(crate) fn direct_call(
    caller: &FunctionFact,
    callee: &FunctionFact,
    index: u32,
) -> CallSiteFact {
    CallSiteFact {
        id: CallSiteId {
            function: caller.id.clone(),
            block_index: 0,
            instruction_index: index,
        },
        location: None,
        target: CallTarget::Direct {
            callee: callee.id.clone(),
        },
    }
}

/// An indirect call site in `caller`: `llvm_target_bound` is what CVP
/// managed to bound it to, or `None` for a site it could not bound.
pub(crate) fn indirect_call(
    caller: &FunctionFact,
    index: u32,
    location: Option<SourceLocation>,
    llvm_target_bound: Option<Vec<FunctionId>>,
) -> CallSiteFact {
    CallSiteFact {
        id: CallSiteId {
            function: caller.id.clone(),
            block_index: 0,
            instruction_index: index,
        },
        location,
        target: CallTarget::Indirect {
            signature: "i32 (i32, i32)".into(),
            llvm_target_bound,
            via_field: None,
        },
    }
}

/// An unbounded indirect call in `caller` at `t.c:line`, dispatching through
/// `field` when the pointer was traced to one.
pub(crate) fn indirect_call_through(
    caller: &FunctionFact,
    line: u32,
    field: Option<FieldRef>,
) -> CallSiteFact {
    let mut site = indirect_call(caller, line, Some(source_location("t.c", line)), None);
    if let CallTarget::Indirect { via_field, .. } = &mut site.target {
        *via_field = field.map(|field| FieldEvidence {
            field,
            basis: FieldBasis::StructGep,
            name: None,
        });
    }
    site
}

/// A module report with only its id and status set; fixtures override the
/// one or two other fields they actually pin.
pub(crate) fn report(id: &str, status: ModuleAnalysis) -> ModuleReport {
    ModuleReport {
        id: id.into(),
        status,
        ir_stage: None,
        debug_info: None,
        compiler: None,
        configuration_id: None,
        content_sha256: None,
        target_triple: None,
        producers: Vec::new(),
        diagnostic: None,
    }
}

/// An ambiguous binding for `symbol`, declared in `declared_in` and defined
/// once per `(module, configuration)` candidate.
pub(crate) fn ambiguous_binding(
    symbol: &str,
    declared_in: &[&str],
    candidates: &[(&str, Option<&str>)],
) -> SymbolBinding {
    SymbolBinding {
        symbol: symbol.into(),
        declared_in: declared_in.iter().map(|id| (*id).to_string()).collect(),
        candidates: candidates
            .iter()
            .map(|(module, configuration)| BindingCandidate {
                function: FunctionId {
                    module_id: (*module).into(),
                    symbol: symbol.into(),
                },
                configuration_id: configuration.map(str::to_string),
            })
            .collect(),
        status: BindingStatus::Ambiguous,
    }
}

pub(crate) fn facts(functions: Vec<FunctionFact>, call_sites: Vec<CallSiteFact>) -> ProgramFacts {
    ProgramFacts {
        functions,
        call_sites,
        uses: Vec::new(),
        scope: CatalogScope {
            kind: "test".into(),
            total_entries: 1,
            selected_entries: 1,
            selection: Default::default(),
            selection_history: Vec::new(),
            analysis_arguments: Vec::new(),
            whole_program_complete: None,
            limitations: Vec::new(),
        },
        origin: CatalogOrigin {
            kind: "test".into(),
            input: PathBuf::from("test"),
            sha256: None,
        },
        modules: Vec::new(),
    }
}

/// One module, one edge per pair.
pub(crate) fn session_from(edges: &[(&str, &str)]) -> Session {
    let mut functions: Vec<FunctionFact> = Vec::new();
    let lookup = |functions: &mut Vec<FunctionFact>, name: &str| -> FunctionFact {
        if let Some(existing) = functions.iter().find(|f| f.id.symbol == name) {
            return existing.clone();
        }
        let created = function("m", name, true, Linkage::Internal);
        functions.push(created.clone());
        created
    };
    let mut call_sites = Vec::new();
    for (index, (from, to)) in edges.iter().enumerate() {
        let caller = lookup(&mut functions, from);
        let callee = lookup(&mut functions, to);
        call_sites.push(direct_call(&caller, &callee, index as u32));
    }
    Session::new(facts(functions, call_sites), Vec::new())
}

/// `a` reaches `target` only through an indirect site CVP bounded to
/// `{target, other}`, recorded at `t.c:9`. A second bound member matters: it
/// lets a test tell a correct bounded-indirect edge apart from one that
/// collapsed the bound to just the target taken. The location makes the site
/// addressable by `at` and `indirect-targets`, which
/// `session_with_address_taken_function` can only answer for an *unbounded*
/// site.
pub(crate) fn session_with_bounded_indirect() -> Session {
    let a = function("m", "a", true, Linkage::Internal);
    let target = function("m", "target", true, Linkage::Internal);
    let other = function("m", "other", true, Linkage::Internal);
    let site = indirect_call(
        &a,
        0,
        Some(source_location("t.c", 9)),
        Some(vec![target.id.clone(), other.id.clone()]),
    );
    Session::new(facts(vec![a, target, other], vec![site]), Vec::new())
}

/// `a` calls `b`; `b` reaches `c` only through an indirect call CVP could not
/// bound, so no path exists over direct edges.
pub(crate) fn session_with_indirect_gap() -> Session {
    let a = function("m", "a", true, Linkage::Internal);
    let b = function("m", "b", true, Linkage::Internal);
    let c = function("m", "c", true, Linkage::Internal);
    let call = direct_call(&a, &b, 0);
    let indirect = indirect_call(&b, 1, None, None);
    Session::new(facts(vec![a, b, c], vec![call, indirect]), Vec::new())
}

/// One `i32 (i32, i32)` indirect site at `t.c:4`, an `add` of that signature
/// whose address is taken, and a `log` whose address is taken but whose
/// signature does not match.
pub(crate) fn session_with_address_taken_function() -> Session {
    let add = function("m", "add", true, Linkage::Internal);
    let log = FunctionFact {
        signature: "void (ptr)".into(),
        ..function("m", "log", true, Linkage::Internal)
    };
    let caller = function("m", "caller", true, Linkage::Internal);
    let mut base = facts(
        vec![add.clone(), log.clone(), caller.clone()],
        vec![indirect_call(
            &caller,
            0,
            Some(SourceLocation {
                file: "t.c".into(),
                directory: None,
                line: 4,
                column: 3,
                source_status: SourceStatus::Unknown,
                status_basis: None,
                inlined_at: Vec::new(),
            }),
            None,
        )],
    );
    base.uses = [add.id, log.id]
        .into_iter()
        .map(|used| UseFact {
            used,
            in_function: Some(caller.id.clone()),
            in_global: None,
            location: None,
            kind: UseKind::StoredToMemory,
            field: None,
        })
        .collect();
    Session::new(base, Vec::new())
}

/// `scope.selected_entries == 2`, but only one module was read: `a` parsed,
/// `b` failed. Pins that `scope` is quoted from the catalog and never
/// recomputed from what `analysis` actually managed to read.
pub(crate) fn facts_with_one_failed_module() -> ProgramFacts {
    let mut base = facts(vec![], vec![]);
    base.scope.total_entries = 2;
    base.scope.selected_entries = 2;
    base.modules = vec![
        ModuleReport {
            debug_info: Some(true),
            ..report("a", ModuleAnalysis::Analyzed)
        },
        ModuleReport {
            diagnostic: Some("truncated".into()),
            ..report("b", ModuleAnalysis::Failed)
        },
    ];
    base
}

/// A function whose only mapped line is the given `(file, line)` pairs.
pub(crate) fn session_from_source_lines(lines: &[(&str, u32)]) -> Session {
    let mut only = function("m", "only", true, Linkage::Internal);
    only.mapped_lines = lines
        .iter()
        .map(|(file, line)| (PathBuf::from(file), *line))
        .collect();
    Session::new(facts(vec![only], Vec::new()), Vec::new())
}

/// Two ambiguous symbols, and one of them reachable through two different
/// declarations: `c1` and `c2` each define `caller` and declare `target`,
/// while `a` and `b` each define `target`. A second binding, `unused`, is
/// ambiguous too but sits on no path out of `caller`.
///
/// Distinguishes three counts that are easy to conflate: the bindings one
/// walk reached (one), the declarations it reached them through (two), and
/// every ambiguous binding in scope (two).
pub(crate) fn session_with_ambiguous_bindings() -> Session {
    let mut functions = Vec::new();
    let mut call_sites = Vec::new();
    for (index, module) in ["c1", "c2"].into_iter().enumerate() {
        let caller = function(module, "caller", true, Linkage::External);
        let declaration = function(module, "target", false, Linkage::External);
        call_sites.push(direct_call(&caller, &declaration, index as u32));
        functions.push(caller);
        functions.push(declaration);
    }
    functions.push(function("a", "target", true, Linkage::External));
    functions.push(function("b", "target", true, Linkage::External));

    let target = ambiguous_binding(
        "target",
        &["c1", "c2"],
        &[("a", Some("debug")), ("b", Some("release"))],
    );
    let unused = ambiguous_binding("unused", &["z"], &[("a", None), ("b", None)]);
    Session::new(facts(functions, call_sites), vec![target, unused])
}

/// A C++ module: two instantiations of `twice`, a `twice_helper` that must
/// not be confused for one, `ns::twice` in a namespace, and a C `main`.
///
/// Symbols are the real mangled spellings, so `Session::new` demangles them
/// through the same path a captured module would.
pub(crate) fn session_with_cxx_symbols() -> Session {
    let functions = [
        "_Z5twiceIiET_S0_",  // int twice<int>(int)
        "_Z5twiceIdET_S0_",  // double twice<double>(double)
        "_Z12twice_helperv", // twice_helper()
        "_ZN2ns5twiceEv",    // ns::twice()
        "main",
    ]
    .into_iter()
    .map(|symbol| function("m", symbol, true, Linkage::External))
    .collect();
    Session::new(facts(functions, Vec::new()), Vec::new())
}

/// Two hashed, analyzed modules for the overlay. `mod_a` holds an unresolved
/// site through `ops@8` in `dispatch` (`t.c:4`), an unresolved site with no
/// field in `call_plain` (`t.c:5`), a site CVP bounded to `{h1}` in
/// `bounded` (`t.c:6`), a direct call from `init` to `h3`, and the handlers
/// `h1` and `h3`. Both modules define a static `helper`.
pub(crate) fn facts_with_overlay_sites() -> ProgramFacts {
    let dispatch = function("mod_a", "dispatch", true, Linkage::External);
    let call_plain = function("mod_a", "call_plain", true, Linkage::External);
    let bounded = function("mod_a", "bounded", true, Linkage::External);
    let init = function("mod_a", "init", true, Linkage::External);
    let h1 = function("mod_a", "h1", true, Linkage::Internal);
    let h3 = function("mod_a", "h3", true, Linkage::Internal);
    let call_sites = vec![
        indirect_call_through(
            &dispatch,
            4,
            Some(FieldRef {
                record: "ops".into(),
                offset: 8,
            }),
        ),
        indirect_call_through(&call_plain, 5, None),
        indirect_call(
            &bounded,
            6,
            Some(source_location("t.c", 6)),
            Some(vec![h1.id.clone()]),
        ),
        direct_call(&init, &h3, 7),
    ];
    let functions = vec![
        dispatch,
        call_plain,
        bounded,
        init,
        h1,
        h3,
        function("mod_a", "helper", true, Linkage::Internal),
        function("mod_b", "helper", true, Linkage::Internal),
    ];
    let mut base = facts(functions, call_sites);
    base.modules = [("mod_a", "aa"), ("mod_b", "bb")]
        .into_iter()
        .map(|(id, hash)| ModuleReport {
            content_sha256: Some(hash.into()),
            ..report(id, ModuleAnalysis::Analyzed)
        })
        .collect();
    base
}

/// One module the loader verified and extraction never saw, so
/// `analysis.verified` is the only non-zero count.
pub(crate) fn facts_with_one_verified_module() -> ProgramFacts {
    let mut base = facts(vec![], vec![]);
    base.scope.total_entries = 1;
    base.scope.selected_entries = 1;
    base.modules = vec![report("v", ModuleAnalysis::Verified)];
    base
}