mirage-analyzer 1.3.0

Path-Aware Code Intelligence Engine for Rust
Documentation
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
//! CFG analysis: entry/exit detection, dominance preparation

use crate::cfg::{BlockKind, Cfg, Terminator};
use petgraph::graph::NodeIndex;

/// Find the entry node of a CFG
///
/// The entry is always the first basic block (id = 0).
/// Returns None if the CFG is empty.
pub fn find_entry(cfg: &Cfg) -> Option<NodeIndex> {
    cfg.node_indices().next()
}

/// Find all exit nodes in a CFG
///
/// Exits are blocks that terminate execution:
/// - Return terminators
/// - Unreachable terminators
/// - Abort terminators (panics)
///
/// Functions can have multiple exits due to:
/// - Early returns
/// - Panic paths
/// - Different exit points from error handling
pub fn find_exits(cfg: &Cfg) -> Vec<NodeIndex> {
    cfg.node_indices()
        .filter(|&idx| is_exit_block(cfg, idx))
        .collect()
}

/// Check if a block is an exit block
pub fn is_exit_block(cfg: &Cfg, block_idx: NodeIndex) -> bool {
    if let Some(block) = cfg.node_weight(block_idx) {
        return matches!(
            &block.terminator,
            Terminator::Return | Terminator::Unreachable | Terminator::Abort(_)
        );
    }
    false
}

/// Get the BlockKind of a node
pub fn get_block_kind(cfg: &Cfg, block_idx: NodeIndex) -> Option<BlockKind> {
    cfg.node_weight(block_idx).map(|b| b.kind)
}

/// Count incoming edges to a node
pub fn in_degree(cfg: &Cfg, block_idx: NodeIndex) -> usize {
    cfg.neighbors_directed(block_idx, petgraph::Direction::Incoming)
        .count()
}

/// Count outgoing edges from a node
pub fn out_degree(cfg: &Cfg, block_idx: NodeIndex) -> usize {
    cfg.neighbors_directed(block_idx, petgraph::Direction::Outgoing)
        .count()
}

/// Check if a node is a merge point (multiple incoming edges)
pub fn is_merge_point(cfg: &Cfg, block_idx: NodeIndex) -> bool {
    in_degree(cfg, block_idx) > 1
}

/// Check if a node is a branch point (multiple outgoing edges)
pub fn is_branch_point(cfg: &Cfg, block_idx: NodeIndex) -> bool {
    out_degree(cfg, block_idx) > 1
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cfg::{BasicBlock, EdgeType};
    use petgraph::graph::DiGraph;

    fn create_test_cfg() -> Cfg {
        let mut g = DiGraph::new();

        // Block 0: entry, goes to 1
        let b0 = g.add_node(BasicBlock {
            id: 0,
            db_id: None,
            kind: BlockKind::Entry,
            statements: vec![],
            terminator: Terminator::Goto { target: 1 },
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        // Block 1: if statement, goes to 2 (true) or 3 (false)
        let b1 = g.add_node(BasicBlock {
            id: 1,
            db_id: None,
            kind: BlockKind::Normal,
            statements: vec![],
            terminator: Terminator::SwitchInt {
                targets: vec![2],
                otherwise: 3,
            },
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        // Block 2: true branch, returns
        let b2 = g.add_node(BasicBlock {
            id: 2,
            db_id: None,
            kind: BlockKind::Exit,
            statements: vec![],
            terminator: Terminator::Return,
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        // Block 3: false branch, returns
        let b3 = g.add_node(BasicBlock {
            id: 3,
            db_id: None,
            kind: BlockKind::Exit,
            statements: vec![],
            terminator: Terminator::Return,
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        // Add edges
        g.add_edge(b0, b1, EdgeType::Fallthrough);
        g.add_edge(b1, b2, EdgeType::TrueBranch);
        g.add_edge(b1, b3, EdgeType::FalseBranch);

        g
    }

    #[test]
    fn test_find_entry() {
        let cfg = create_test_cfg();
        let entry = find_entry(&cfg);
        assert!(entry.is_some());
        assert_eq!(entry.unwrap().index(), 0);
    }

    #[test]
    fn test_find_exits() {
        let cfg = create_test_cfg();
        let exits = find_exits(&cfg);
        assert_eq!(exits.len(), 2);

        // Both blocks 2 and 3 are exits
        let exit_ids: Vec<_> = exits
            .iter()
            .map(|&idx| cfg.node_weight(idx).unwrap().id)
            .collect();
        assert!(exit_ids.contains(&2));
        assert!(exit_ids.contains(&3));
    }

    #[test]
    fn test_is_exit_block() {
        let cfg = create_test_cfg();

        let b0 = NodeIndex::new(0);
        let b1 = NodeIndex::new(1);
        let b2 = NodeIndex::new(2);
        let b3 = NodeIndex::new(3);

        assert!(!is_exit_block(&cfg, b0)); // entry
        assert!(!is_exit_block(&cfg, b1)); // branch
        assert!(is_exit_block(&cfg, b2)); // exit
        assert!(is_exit_block(&cfg, b3)); // exit
    }

    #[test]
    fn test_is_branch_point() {
        let cfg = create_test_cfg();

        let b0 = NodeIndex::new(0);
        let b1 = NodeIndex::new(1);
        let b2 = NodeIndex::new(2);

        assert!(!is_branch_point(&cfg, b0)); // 1 outgoing
        assert!(is_branch_point(&cfg, b1)); // 2 outgoing
        assert!(!is_branch_point(&cfg, b2)); // 0 outgoing
    }

    #[test]
    fn test_is_merge_point() {
        let cfg = create_test_cfg();

        let b0 = NodeIndex::new(0);
        let b1 = NodeIndex::new(1);

        assert!(!is_merge_point(&cfg, b0)); // 0 incoming
        assert!(!is_merge_point(&cfg, b1)); // 1 incoming
    }

    #[test]
    fn test_is_merge_point_with_actual_merge() {
        let mut g = DiGraph::new();

        // Create a diamond pattern: 0 -> 1, 0 -> 2, 1 -> 3, 2 -> 3
        // Block 3 is a merge point (2 incoming edges)

        let b0 = g.add_node(BasicBlock {
            id: 0,
            db_id: None,
            kind: BlockKind::Entry,
            statements: vec![],
            terminator: Terminator::SwitchInt {
                targets: vec![1],
                otherwise: 2,
            },
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        let b1 = g.add_node(BasicBlock {
            id: 1,
            db_id: None,
            kind: BlockKind::Normal,
            statements: vec![],
            terminator: Terminator::Goto { target: 3 },
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        let b2 = g.add_node(BasicBlock {
            id: 2,
            db_id: None,
            kind: BlockKind::Normal,
            statements: vec![],
            terminator: Terminator::Goto { target: 3 },
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        let b3 = g.add_node(BasicBlock {
            id: 3,
            db_id: None,
            kind: BlockKind::Exit,
            statements: vec![],
            terminator: Terminator::Return,
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        g.add_edge(b0, b1, EdgeType::TrueBranch);
        g.add_edge(b0, b2, EdgeType::FalseBranch);
        g.add_edge(b1, b3, EdgeType::Fallthrough);
        g.add_edge(b2, b3, EdgeType::Fallthrough);

        assert!(!is_merge_point(&g, b0)); // 0 incoming
        assert!(!is_merge_point(&g, b1)); // 1 incoming
        assert!(!is_merge_point(&g, b2)); // 1 incoming
        assert!(is_merge_point(&g, b3)); // 2 incoming - merge point!
    }

    #[test]
    fn test_multiple_exits_with_unwind() {
        let mut g = DiGraph::new();

        // Block 0: entry with call that can unwind
        let b0 = g.add_node(BasicBlock {
            id: 0,
            db_id: None,
            kind: BlockKind::Entry,
            statements: vec![],
            terminator: Terminator::Call {
                target: Some(1),
                unwind: Some(2),
            },
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        // Block 1: normal return
        let b1 = g.add_node(BasicBlock {
            id: 1,
            db_id: None,
            kind: BlockKind::Exit,
            statements: vec![],
            terminator: Terminator::Return,
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        // Block 2: unwind exit
        let b2 = g.add_node(BasicBlock {
            id: 2,
            db_id: None,
            kind: BlockKind::Exit,
            statements: vec![],
            terminator: Terminator::Abort("panic".to_string()),
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        g.add_edge(b0, b1, EdgeType::Call);
        g.add_edge(b0, b2, EdgeType::Exception);

        let exits = find_exits(&g);
        assert_eq!(exits.len(), 2);
    }

    #[test]
    fn test_empty_cfg() {
        let cfg: Cfg = DiGraph::new();
        assert!(find_entry(&cfg).is_none());
        assert!(find_exits(&cfg).is_empty());
    }

    #[test]
    fn test_single_block_cfg() {
        let mut g = DiGraph::new();

        let b0 = g.add_node(BasicBlock {
            id: 0,
            db_id: None,
            kind: BlockKind::Entry,
            statements: vec![],
            terminator: Terminator::Return,
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        // A single block that is both entry and exit
        assert_eq!(find_entry(&g), Some(b0));
        assert_eq!(find_exits(&g), vec![b0]);
    }

    #[test]
    fn test_unreachable_exit() {
        let mut g = DiGraph::new();

        // Block 0: entry
        let b0 = g.add_node(BasicBlock {
            id: 0,
            db_id: None,
            kind: BlockKind::Entry,
            statements: vec![],
            terminator: Terminator::Goto { target: 1 },
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        // Block 1: normal path
        let b1 = g.add_node(BasicBlock {
            id: 1,
            db_id: None,
            kind: BlockKind::Normal,
            statements: vec![],
            terminator: Terminator::Return,
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        // Block 2: unreachable (dead code)
        let _b2 = g.add_node(BasicBlock {
            id: 2,
            db_id: None,
            kind: BlockKind::Exit,
            statements: vec![],
            terminator: Terminator::Unreachable,
            source_location: None,
            coord_x: 0,
            coord_y: 0,
            coord_z: 0,
        });

        g.add_edge(b0, b1, EdgeType::Fallthrough);

        // Unreachable is still an exit block
        let exits = find_exits(&g);
        assert_eq!(exits.len(), 2);
        let exit_ids: Vec<_> = exits
            .iter()
            .map(|&idx| g.node_weight(idx).unwrap().id)
            .collect();
        assert!(exit_ids.contains(&1)); // Return
        assert!(exit_ids.contains(&2)); // Unreachable
    }
}