mirage-analyzer 1.8.2

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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use crate::cli::responses::*;
use crate::cli::{detect_repo_path, resolve_db_path, Cli, OutputFormat, PathsArgs};
use crate::output;
use anyhow::Result;

pub fn paths(args: &PathsArgs, cli: &Cli) -> Result<()> {
    use crate::cfg::icfg::{build_icfg, enumerate_icfg_paths, project_icfg_to_cfg, IcfgOptions};
    use crate::cfg::load_cfg_from_db;
    use crate::cfg::{enumerate_paths_incremental, get_or_enumerate_paths, PathKind, PathLimits};
    use crate::storage::resolve_function_or_semantic;
    use crate::storage::{get_function_hash_db, MirageDb};

    // Resolve database path
    let db_path = resolve_db_path(cli.db.clone())?;

    // Detect repository path for incremental mode
    let repo_path = detect_repo_path(&db_path);

    // Handle incremental mode
    if args.incremental {
        let since = args
            .since
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("--since required with --incremental"))?;

        // Open database for incremental mode
        let db = match MirageDb::open(&db_path) {
            Ok(db) => db,
            Err(_e) => {
                if matches!(cli.output, OutputFormat::Json | OutputFormat::Pretty) {
                    let error = output::JsonError::database_not_found(&db_path);
                    let wrapper = output::JsonResponse::new(error);
                    println!("{}", wrapper.to_json());
                    std::process::exit(output::EXIT_DATABASE);
                } else {
                    output::error(&format!("Failed to open database: {}", db_path));
                    output::info("Hint: Run 'magellan watch' to create the database");
                    std::process::exit(output::EXIT_DATABASE);
                }
            }
        };

        // Run incremental path enumeration
        let result = match enumerate_paths_incremental(
            &args.function,
            &db,
            &repo_path,
            since,
            args.max_length,
        ) {
            Ok(r) => r,
            Err(e) => {
                if matches!(cli.output, OutputFormat::Json | OutputFormat::Pretty) {
                    let error = output::JsonError::new(
                        "IncrementalAnalysisError",
                        &format!("Incremental analysis failed: {}", e),
                        output::E_CFG_ERROR,
                    );
                    let wrapper = output::JsonResponse::new(error);
                    println!("{}", wrapper.to_json());
                    std::process::exit(output::EXIT_DATABASE);
                } else {
                    output::error(&format!("Incremental analysis failed: {}", e));
                    std::process::exit(output::EXIT_DATABASE);
                }
            }
        };

        // Output results
        match cli.output {
            OutputFormat::Human => {
                println!("Incremental path enumeration (since {}):", since);
                println!("  Analyzed functions: {}", result.analyzed_functions);
                println!("  Total paths: {}", result.paths.len());

                if args.show_errors {
                    let error_count = result
                        .paths
                        .iter()
                        .filter(|p| matches!(p.kind, PathKind::Error))
                        .count();
                    println!("  Error paths: {}", error_count);
                }

                if !result.paths.is_empty() {
                    println!("\nPaths:");
                    for path in &result.paths {
                        if args.show_errors || !matches!(path.kind, PathKind::Error) {
                            println!("  {}", path);
                        }
                    }
                }
            }
            OutputFormat::Json => {
                let response = serde_json::json!({
                    "incremental": true,
                    "since": since,
                    "analyzed_functions": result.analyzed_functions,
                    "skipped_functions": result.skipped_functions,
                    "total_paths": result.paths.len(),
                    "paths": result.paths,
                });
                println!("{}", serde_json::to_string(&response)?);
            }
            OutputFormat::Pretty => {
                let response = serde_json::json!({
                    "incremental": true,
                    "since": since,
                    "analyzed_functions": result.analyzed_functions,
                    "skipped_functions": result.skipped_functions,
                    "total_paths": result.paths.len(),
                    "paths": result.paths,
                });
                println!("{}", serde_json::to_string_pretty(&response)?);
            }
        }

        return Ok(());
    }

    // Standard path enumeration (non-incremental)
    // Open database
    let mut db = match MirageDb::open(&db_path) {
        Ok(db) => db,
        Err(_e) => {
            // JSON-aware error handling with remediation
            if matches!(cli.output, OutputFormat::Json | OutputFormat::Pretty) {
                let error = output::JsonError::database_not_found(&db_path);
                let wrapper = output::JsonResponse::new(error);
                println!("{}", wrapper.to_json());
                std::process::exit(output::EXIT_DATABASE);
            } else {
                output::error(&format!("Failed to open database: {}", db_path));
                output::info("Hint: Run 'magellan watch' to create the database");
                std::process::exit(output::EXIT_DATABASE);
            }
        }
    };

    // Resolve function name/ID or semantic query to function_id (with optional file filter)
    let function_id = match resolve_function_or_semantic(
        &db,
        &args.function,
        args.semantic_query.as_deref(),
        args.file.as_deref(),
    ) {
        Ok(id) => id,
        Err(e) => {
            if matches!(cli.output, OutputFormat::Json | OutputFormat::Pretty) {
                let error = output::JsonError::new(
                    "FunctionNotFound",
                    &format!("{}", e),
                    output::E_CFG_ERROR,
                );
                let wrapper = output::JsonResponse::new(error);
                println!("{}", wrapper.to_json());
                std::process::exit(output::EXIT_DATABASE);
            } else {
                output::error(&format!("{}", e));
                output::info(&format!("Hint: {}", output::R_HINT_LIST_FUNCTIONS));
                std::process::exit(output::EXIT_DATABASE);
            }
        }
    };

    // Build path limits based on args
    let mut limits = PathLimits::default();
    if let Some(max_length) = args.max_length {
        limits = limits.with_max_length(max_length);
    }

    let mut projected_icfg = None;

    let mut paths = if args.inter_procedural {
        let icfg = build_icfg(
            db.storage(),
            db.backend(),
            db.path(),
            function_id,
            IcfgOptions {
                max_depth: limits.max_length,
                include_return_edges: true,
            },
        )
        .map_err(|e| anyhow::anyhow!("ICFG path enumeration failed: {}", e))?;
        let synthetic_cfg = project_icfg_to_cfg(&icfg);
        let paths = enumerate_icfg_paths(&icfg, &limits);
        projected_icfg = Some((icfg, synthetic_cfg));
        paths
    } else {
        // Load CFG from database
        let cfg = match load_cfg_from_db(&db, function_id) {
            Ok(cfg) => cfg,
            Err(_e) => {
                if matches!(cli.output, OutputFormat::Json | OutputFormat::Pretty) {
                    let error = output::JsonError::new(
                        "CgfLoadError",
                        &format!("Failed to load CFG for function '{}'", args.function),
                        output::E_CFG_ERROR,
                    );
                    let wrapper = output::JsonResponse::new(error);
                    println!("{}", wrapper.to_json());
                    std::process::exit(output::EXIT_DATABASE);
                } else {
                    output::error(&format!(
                        "Failed to load CFG for function '{}'",
                        args.function
                    ));
                    output::info("The function may be corrupted. Try re-running 'magellan watch'");
                    std::process::exit(output::EXIT_DATABASE);
                }
            }
        };

        if db.is_sqlite() {
            let function_hash = match get_function_hash_db(&db, function_id) {
                Some(hash) => hash,
                None => {
                    if matches!(cli.output, OutputFormat::Json | OutputFormat::Pretty) {
                        let error = output::JsonError::new(
                            "HashNotFound",
                            &format!("Function hash not found for '{}'", args.function),
                            output::E_CFG_ERROR,
                        );
                        let wrapper = output::JsonResponse::new(error);
                        println!("{}", wrapper.to_json());
                        std::process::exit(output::EXIT_DATABASE);
                    } else {
                        output::error(&format!("Function hash not found for '{}'", args.function));
                        output::info(
                            "The function data may be incomplete. Try re-running 'magellan watch'",
                        );
                        std::process::exit(output::EXIT_DATABASE);
                    }
                }
            };

            get_or_enumerate_paths(&cfg, function_id, &function_hash, &limits, db.conn_mut()?)
                .map_err(|e| anyhow::anyhow!("Path enumeration failed: {}", e))?
        } else {
            crate::cfg::enumerate_paths(&cfg, &limits)
        }
    };

    // Filter to error paths if requested
    if args.show_errors {
        paths.retain(|p| p.kind == PathKind::Error);
    }

    // Sort by coverage if requested (highest total hit count first)
    if args.by_coverage {
        let coverage_map: std::collections::HashMap<i64, i64> = db
            .conn()
            .ok()
            .and_then(|conn| {
                let sql = "SELECT block_id, hit_count FROM cfg_block_coverage \
                       WHERE block_id IN (SELECT id FROM cfg_blocks WHERE function_id = ?1)";
                let mut stmt = conn.prepare(sql).ok()?;
                let rows = stmt.query_map([function_id], |row| {
                    Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
                });
                let mut map = std::collections::HashMap::new();
                if let Ok(iter) = rows {
                    for (block_id, hit_count) in iter.flatten() {
                        map.insert(block_id, hit_count);
                    }
                }
                if map.is_empty() {
                    None
                } else {
                    Some(map)
                }
            })
            .unwrap_or_default();

        // Build graph node index -> hit_count lookup via db_id
        if let Some((_, synthetic_cfg)) = projected_icfg.as_ref() {
            let node_hits: std::collections::HashMap<usize, i64> = synthetic_cfg
                .node_indices()
                .filter_map(|idx| synthetic_cfg.node_weight(idx).map(|b| (b.id, 0)))
                .collect();
            paths.sort_by(|a, b| {
                let total_a: i64 = a
                    .blocks
                    .iter()
                    .map(|bid| node_hits.get(bid).copied().unwrap_or(0))
                    .sum();
                let total_b: i64 = b
                    .blocks
                    .iter()
                    .map(|bid| node_hits.get(bid).copied().unwrap_or(0))
                    .sum();
                total_b.cmp(&total_a)
            });
        } else {
            let cfg = load_cfg_from_db(&db, function_id)
                .map_err(|e| anyhow::anyhow!("Failed to reload CFG for coverage sorting: {}", e))?;
            let node_hits: std::collections::HashMap<usize, i64> = cfg
                .node_indices()
                .filter_map(|idx| {
                    cfg.node_weight(idx).and_then(|b| {
                        b.db_id
                            .and_then(|db_id| coverage_map.get(&db_id).copied())
                            .map(|hits| (b.id, hits))
                    })
                })
                .collect();

            paths.sort_by(|a, b| {
                let total_a: i64 = a
                    .blocks
                    .iter()
                    .map(|bid| node_hits.get(bid).copied().unwrap_or(0))
                    .sum();
                let total_b: i64 = b
                    .blocks
                    .iter()
                    .map(|bid| node_hits.get(bid).copied().unwrap_or(0))
                    .sum();
                total_b.cmp(&total_a)
            });
        }
    }

    // Count error paths for reporting
    let error_count = paths.iter().filter(|p| p.kind == PathKind::Error).count();

    // Format output based on cli.output
    match cli.output {
        OutputFormat::Human => {
            // Human-readable text format
            println!("Function: {}", args.function);
            println!("Total paths: {}", paths.len());
            if args.show_errors {
                println!("(Showing error paths only)");
            } else {
                println!("Error paths: {}", error_count);
            }
            println!();

            if paths.is_empty() {
                output::info("No paths found");
                return Ok(());
            }

            for (i, path) in paths.iter().enumerate() {
                println!("Path {}: {}", i + 1, path.path_id);
                println!("  Kind: {:?}", path.kind);
                println!("  Length: {} blocks", path.len());
                if args.with_blocks {
                    let rendered_blocks = if let Some((icfg, _)) = projected_icfg.as_ref() {
                        path.blocks
                            .iter()
                            .map(|id| {
                                let node = &icfg.graph[petgraph::graph::NodeIndex::new(*id)];
                                match (&node.function_name, node.block_id) {
                                    (Some(function_name), block_id) if block_id >= 0 => {
                                        format!("{}:{}", function_name, block_id)
                                    }
                                    (Some(function_name), -1) => format!("{}:entry", function_name),
                                    (Some(function_name), -2) => format!("{}:exit", function_name),
                                    (Some(function_name), block_id) => {
                                        format!("{}:{}", function_name, block_id)
                                    }
                                    (None, block_id) => block_id.to_string(),
                                }
                            })
                            .collect::<Vec<_>>()
                    } else {
                        path.blocks
                            .iter()
                            .map(|id| id.to_string())
                            .collect::<Vec<_>>()
                    };
                    println!("  Blocks: {}", rendered_blocks.join(" -> "));
                }
                println!();
            }
        }
        OutputFormat::Json => {
            let response = PathsResponse {
                function: args.function.clone(),
                total_paths: paths.len(),
                error_paths: error_count,
                paths: if let Some((icfg, synthetic_cfg)) = projected_icfg.as_ref() {
                    paths
                        .iter()
                        .map(|p| PathSummary::from_icfg_path(p.clone(), synthetic_cfg, icfg))
                        .collect()
                } else {
                    let cfg = load_cfg_from_db(&db, function_id).map_err(|e| {
                        anyhow::anyhow!("Failed to reload CFG for JSON path output: {}", e)
                    })?;
                    paths
                        .iter()
                        .map(|p| PathSummary::from_with_cfg(p.clone(), &cfg))
                        .collect()
                },
            };
            let wrapper = output::JsonResponse::new(response);
            println!("{}", wrapper.to_json());
        }
        OutputFormat::Pretty => {
            let response = PathsResponse {
                function: args.function.clone(),
                total_paths: paths.len(),
                error_paths: error_count,
                paths: if let Some((icfg, synthetic_cfg)) = projected_icfg.as_ref() {
                    paths
                        .iter()
                        .map(|p| PathSummary::from_icfg_path(p.clone(), synthetic_cfg, icfg))
                        .collect()
                } else {
                    let cfg = load_cfg_from_db(&db, function_id).map_err(|e| {
                        anyhow::anyhow!("Failed to reload CFG for pretty path output: {}", e)
                    })?;
                    paths
                        .iter()
                        .map(|p| PathSummary::from_with_cfg(p.clone(), &cfg))
                        .collect()
                },
            };
            let wrapper = output::JsonResponse::new(response);
            println!("{}", wrapper.to_pretty_json());
        }
    }

    Ok(())
}