padlock-cli 0.9.7

Struct memory layout analyzer for C, C++, Rust, Go, and Zig
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
// padlock-cli/src/config.rs
//
// Reads and applies per-project configuration from `.padlock.toml`.
//
// padlock looks for the config file by walking up from the analysed file's
// directory to the filesystem root, stopping at the first `.padlock.toml`
// found. This mirrors how tools like rustfmt and clippy locate their configs.
//
// Example `.padlock.toml`:
//
//   [padlock]
//   min_severity   = "medium"    # report only medium and above (high|medium|low)
//   fail_below     = 60          # exit 1 if any struct scores below this
//   ignore         = ["GeneratedStruct", "FfiLayout"]  # suppress by name
//
//   [arch]
//   override = "aarch64"         # force a specific arch (x86_64|aarch64|aarch64_apple|wasm32|riscv64)
//
//   # Per-struct overrides — keyed by exact struct name
//   [ignore."MyFfiStruct"]       # suppress entirely (same as adding to `ignore` list)
//   [override."HotPath"]
//   min_severity = "high"        # only report High findings for this struct
//   fail_below   = 50            # lower threshold for this struct

use std::path::{Path, PathBuf};

use padlock_core::findings::Severity;

const CONFIG_FILENAME: &str = ".padlock.toml";

/// Per-struct severity and threshold overrides.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct StructOverride {
    /// Override min_severity for this struct only.
    pub min_severity: Option<Severity>,
    /// Override fail_below for this struct only.
    pub fail_below: Option<u8>,
}

/// Loaded and validated project configuration.
#[derive(Debug, Clone, PartialEq)]
pub struct Config {
    /// Minimum severity to report. Findings below this level are suppressed.
    pub min_severity: Severity,
    /// Exit non-zero if any struct's score falls below this value (0 = disabled).
    pub fail_below: u8,
    /// Struct names to suppress entirely from output and exit-code logic.
    pub ignore: Vec<String>,
    /// Optional architecture override name (validated at load time).
    pub arch_override: Option<String>,
    /// Per-struct overrides keyed by exact struct name.
    pub struct_overrides: std::collections::HashMap<String, StructOverride>,

    // ── filter defaults ───────────────────────────────────────────────────────
    /// Include only structs whose names match this regex pattern.
    /// CLI `--filter` overrides this when provided.
    pub filter: Option<String>,
    /// Exclude structs whose names match this regex pattern.
    /// CLI `--exclude` overrides this when provided.
    pub exclude: Option<String>,
    /// Show only structs with total size >= N bytes.
    /// CLI `--min-size` overrides this when provided.
    pub min_size: Option<usize>,
    /// Show only structs with at least N padding holes.
    /// CLI `--min-holes` overrides this when provided.
    pub min_holes: Option<usize>,
    /// Default sort order for output: "score" | "size" | "waste" | "name".
    /// CLI `--sort-by` overrides this when provided.
    pub sort_by: Option<String>,
    /// Exit non-zero when any finding meets this severity: "high" | "medium" | "low".
    /// CLI `--fail-on-severity` overrides this when provided.
    pub fail_on_severity: Option<Severity>,
    /// Glob patterns matched against each layout's `source_file`.
    /// Layouts whose source path matches any pattern are excluded from all output.
    /// Example: `["proto/**", "vendor/**", "generated/**"]`
    pub exclude_paths: Vec<String>,
    /// Additional type-name substrings treated as concurrent synchronization wrappers.
    /// Any field whose type name contains one of these strings will be annotated as
    /// Concurrent, enabling false-sharing detection for project-specific lock types.
    /// Example: `["SeqLock", "TicketLock", "BoundedMPMC"]`
    pub custom_sync_types: Vec<String>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            min_severity: Severity::Low,
            fail_below: 0,
            ignore: Vec::new(),
            arch_override: None,
            struct_overrides: std::collections::HashMap::new(),
            filter: None,
            exclude: None,
            min_size: None,
            min_holes: None,
            sort_by: None,
            fail_on_severity: None,
            exclude_paths: Vec::new(),
            custom_sync_types: Vec::new(),
        }
    }
}

impl Config {
    /// Load config by searching upward from `start_dir`.
    /// Returns `Config::default()` if no config file is found.
    pub fn load_from(start_dir: &Path) -> Self {
        find_config_file(start_dir)
            .and_then(|p| Self::load_file(&p))
            .unwrap_or_default()
    }

    /// Load config for a given analysis target path (file or directory).
    #[allow(dead_code)]
    pub fn for_path(target: &Path) -> Self {
        let dir = if target.is_dir() {
            target.to_path_buf()
        } else {
            target.parent().unwrap_or(target).to_path_buf()
        };
        Self::load_from(&dir)
    }

    fn load_file(path: &Path) -> Option<Self> {
        let text = std::fs::read_to_string(path).ok()?;
        let doc: toml::Value = toml::from_str(&text)
            .map_err(|e| eprintln!("padlock: warning: failed to parse {}: {e}", path.display()))
            .ok()?;

        let padlock = doc.get("padlock");
        let arch = doc.get("arch");

        let min_severity = padlock
            .and_then(|p| p.get("min_severity"))
            .and_then(|v| v.as_str())
            .and_then(parse_severity)
            .unwrap_or(Severity::Low);

        let fail_below = padlock
            .and_then(|p| p.get("fail_below"))
            .and_then(|v| v.as_integer())
            .map(|n| n.clamp(0, 100) as u8)
            .unwrap_or(0);

        let ignore = padlock
            .and_then(|p| p.get("ignore"))
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(str::to_owned))
                    .collect()
            })
            .unwrap_or_default();

        let arch_override = arch
            .and_then(|a| a.get("override"))
            .and_then(|v| v.as_str())
            .map(str::to_owned);

        // Per-struct overrides: [override."StructName"]
        let mut struct_overrides = std::collections::HashMap::new();
        if let Some(overrides_table) = doc.get("override").and_then(|v| v.as_table()) {
            for (struct_name, val) in overrides_table {
                let min_sev = val
                    .get("min_severity")
                    .and_then(|v| v.as_str())
                    .and_then(parse_severity);
                let fail_b = val
                    .get("fail_below")
                    .and_then(|v| v.as_integer())
                    .map(|n| n.clamp(0, 100) as u8);
                if min_sev.is_some() || fail_b.is_some() {
                    struct_overrides.insert(
                        struct_name.clone(),
                        StructOverride {
                            min_severity: min_sev,
                            fail_below: fail_b,
                        },
                    );
                }
            }
        }

        let filter = padlock
            .and_then(|p| p.get("filter"))
            .and_then(|v| v.as_str())
            .map(str::to_owned);

        let exclude = padlock
            .and_then(|p| p.get("exclude"))
            .and_then(|v| v.as_str())
            .map(str::to_owned);

        let min_size = padlock
            .and_then(|p| p.get("min_size"))
            .and_then(|v| v.as_integer())
            .map(|n| n.max(0) as usize);

        let min_holes = padlock
            .and_then(|p| p.get("min_holes"))
            .and_then(|v| v.as_integer())
            .map(|n| n.max(0) as usize);

        let sort_by = padlock
            .and_then(|p| p.get("sort_by"))
            .and_then(|v| v.as_str())
            .map(str::to_owned);

        let fail_on_severity = padlock
            .and_then(|p| p.get("fail_on_severity"))
            .and_then(|v| v.as_str())
            .and_then(parse_severity);

        let exclude_paths = padlock
            .and_then(|p| p.get("exclude_paths"))
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(str::to_owned))
                    .collect()
            })
            .unwrap_or_default();

        let custom_sync_types = padlock
            .and_then(|p| p.get("custom_sync_types"))
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(str::to_owned))
                    .collect()
            })
            .unwrap_or_default();

        Some(Self {
            min_severity,
            fail_below,
            ignore,
            arch_override,
            struct_overrides,
            filter,
            exclude,
            min_size,
            min_holes,
            sort_by,
            fail_on_severity,
            exclude_paths,
            custom_sync_types,
        })
    }

    /// Returns true if a struct with the given name should be suppressed.
    pub fn is_ignored(&self, struct_name: &str) -> bool {
        self.ignore.iter().any(|n| n == struct_name)
    }

    /// Returns true if a layout's source path matches any `exclude_paths` glob pattern.
    /// `path` is matched as-is (forward-slash separated) against each pattern.
    pub fn is_path_excluded(&self, path: &str) -> bool {
        if self.exclude_paths.is_empty() {
            return false;
        }
        // Normalise to forward slashes so patterns work on all platforms.
        let normalised = path.replace('\\', "/");
        self.exclude_paths.iter().any(|pat| {
            glob::Pattern::new(pat)
                .map(|g| g.matches(&normalised))
                .unwrap_or(false)
        })
    }

    /// Returns true if a finding with the given severity should be reported.
    pub fn should_report(&self, severity: &Severity) -> bool {
        severity_rank(severity) >= severity_rank(&self.min_severity)
    }

    /// Returns true if a finding with the given severity should be reported
    /// for the named struct, applying any per-struct override.
    #[allow(dead_code)]
    pub fn should_report_for(&self, struct_name: &str, severity: &Severity) -> bool {
        let effective_min = self
            .struct_overrides
            .get(struct_name)
            .and_then(|o| o.min_severity.as_ref())
            .unwrap_or(&self.min_severity);
        severity_rank(severity) >= severity_rank(effective_min)
    }

    /// Returns the effective fail_below threshold for the named struct.
    #[allow(dead_code)]
    pub fn fail_below_for(&self, struct_name: &str) -> u8 {
        self.struct_overrides
            .get(struct_name)
            .and_then(|o| o.fail_below)
            .unwrap_or(self.fail_below)
    }
}

// ── helpers ───────────────────────────────────────────────────────────────────

fn find_config_file(start: &Path) -> Option<PathBuf> {
    let mut dir = start.canonicalize().unwrap_or_else(|_| start.to_path_buf());
    loop {
        let candidate = dir.join(CONFIG_FILENAME);
        if candidate.exists() {
            return Some(candidate);
        }
        if !dir.pop() {
            return None;
        }
    }
}

fn parse_severity(s: &str) -> Option<Severity> {
    match s.to_ascii_lowercase().as_str() {
        "high" => Some(Severity::High),
        "medium" | "med" => Some(Severity::Medium),
        "low" => Some(Severity::Low),
        _ => {
            eprintln!("padlock: warning: unknown min_severity '{s}', using 'low'");
            None
        }
    }
}

fn severity_rank(s: &Severity) -> u8 {
    match s {
        Severity::Low => 0,
        Severity::Medium => 1,
        Severity::High => 2,
    }
}

// ── tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn write_config(content: &str) -> NamedTempFile {
        let mut f = NamedTempFile::new().unwrap();
        f.write_all(content.as_bytes()).unwrap();
        f
    }

    #[test]
    fn default_config_is_permissive() {
        let cfg = Config::default();
        assert_eq!(cfg.min_severity, Severity::Low);
        assert_eq!(cfg.fail_below, 0);
        assert!(cfg.ignore.is_empty());
    }

    #[test]
    fn parse_full_config() {
        // Write to a temp file then load via load_file
        let content = r#"
[padlock]
min_severity = "medium"
fail_below   = 60
ignore       = ["GeneratedFoo", "FfiLayout"]

[arch]
override = "aarch64"
"#;
        let f = write_config(content);
        let cfg = Config::load_file(f.path()).unwrap();
        assert_eq!(cfg.min_severity, Severity::Medium);
        assert_eq!(cfg.fail_below, 60);
        assert_eq!(cfg.ignore, vec!["GeneratedFoo", "FfiLayout"]);
        assert_eq!(cfg.arch_override.as_deref(), Some("aarch64"));
    }

    #[test]
    fn parse_high_severity() {
        let content = "[padlock]\nmin_severity = \"high\"\n";
        let f = write_config(content);
        let cfg = Config::load_file(f.path()).unwrap();
        assert_eq!(cfg.min_severity, Severity::High);
    }

    #[test]
    fn parse_low_severity() {
        let content = "[padlock]\nmin_severity = \"low\"\n";
        let f = write_config(content);
        let cfg = Config::load_file(f.path()).unwrap();
        assert_eq!(cfg.min_severity, Severity::Low);
    }

    #[test]
    fn missing_keys_use_defaults() {
        let content = "[padlock]\n";
        let f = write_config(content);
        let cfg = Config::load_file(f.path()).unwrap();
        assert_eq!(cfg.min_severity, Severity::Low);
        assert_eq!(cfg.fail_below, 0);
        assert!(cfg.ignore.is_empty());
    }

    #[test]
    fn fail_below_clamped_to_100() {
        let content = "[padlock]\nfail_below = 200\n";
        let f = write_config(content);
        let cfg = Config::load_file(f.path()).unwrap();
        assert_eq!(cfg.fail_below, 100);
    }

    #[test]
    fn is_ignored_matches_exact_name() {
        let cfg = Config {
            ignore: vec!["FfiLayout".into()],
            ..Config::default()
        };
        assert!(cfg.is_ignored("FfiLayout"));
        assert!(!cfg.is_ignored("FfiLayoutExtra"));
    }

    #[test]
    fn should_report_high_always_when_min_low() {
        let cfg = Config::default(); // min_severity = Low
        assert!(cfg.should_report(&Severity::High));
        assert!(cfg.should_report(&Severity::Medium));
        assert!(cfg.should_report(&Severity::Low));
    }

    #[test]
    fn should_report_suppresses_low_when_min_medium() {
        let cfg = Config {
            min_severity: Severity::Medium,
            ..Config::default()
        };
        assert!(cfg.should_report(&Severity::High));
        assert!(cfg.should_report(&Severity::Medium));
        assert!(!cfg.should_report(&Severity::Low));
    }

    #[test]
    fn should_report_only_high_when_min_high() {
        let cfg = Config {
            min_severity: Severity::High,
            ..Config::default()
        };
        assert!(cfg.should_report(&Severity::High));
        assert!(!cfg.should_report(&Severity::Medium));
        assert!(!cfg.should_report(&Severity::Low));
    }

    #[test]
    fn parse_filter_defaults() {
        let content = r#"
[padlock]
filter            = "^Hot"
exclude           = "^Generated"
min_size          = 64
min_holes         = 2
sort_by           = "waste"
fail_on_severity  = "high"
"#;
        let f = write_config(content);
        let cfg = Config::load_file(f.path()).unwrap();
        assert_eq!(cfg.filter.as_deref(), Some("^Hot"));
        assert_eq!(cfg.exclude.as_deref(), Some("^Generated"));
        assert_eq!(cfg.min_size, Some(64));
        assert_eq!(cfg.min_holes, Some(2));
        assert_eq!(cfg.sort_by.as_deref(), Some("waste"));
        assert_eq!(cfg.fail_on_severity, Some(Severity::High));
    }

    #[test]
    fn filter_defaults_absent_gives_none() {
        let content = "[padlock]\nmin_severity = \"low\"\n";
        let f = write_config(content);
        let cfg = Config::load_file(f.path()).unwrap();
        assert!(cfg.filter.is_none());
        assert!(cfg.exclude.is_none());
        assert!(cfg.min_size.is_none());
        assert!(cfg.min_holes.is_none());
        assert!(cfg.sort_by.is_none());
        assert!(cfg.fail_on_severity.is_none());
    }

    #[test]
    fn find_config_file_returns_none_for_nonexistent_dir() {
        let result = find_config_file(Path::new("/tmp/__padlock_no_such_dir__"));
        assert!(result.is_none());
    }

    #[test]
    fn load_from_nonexistent_dir_returns_default() {
        let cfg = Config::load_from(Path::new("/tmp/__padlock_no_such_dir__"));
        assert_eq!(cfg, Config::default());
    }

    #[test]
    fn parse_exclude_paths() {
        let content = r#"
[padlock]
exclude_paths = ["proto/**", "vendor/**"]
"#;
        let f = write_config(content);
        let cfg = Config::load_file(f.path()).unwrap();
        assert_eq!(cfg.exclude_paths, vec!["proto/**", "vendor/**"]);
    }

    #[test]
    fn is_path_excluded_matches_glob() {
        let cfg = Config {
            exclude_paths: vec!["proto/**".into(), "vendor/**".into()],
            ..Config::default()
        };
        assert!(cfg.is_path_excluded("proto/foo/bar.go"));
        assert!(cfg.is_path_excluded("vendor/github.com/pkg/pkg.go"));
        assert!(!cfg.is_path_excluded("src/main.rs"));
    }

    #[test]
    fn is_path_excluded_empty_patterns_never_excludes() {
        let cfg = Config::default();
        assert!(!cfg.is_path_excluded("proto/foo/bar.go"));
    }

    #[test]
    fn is_path_excluded_normalises_backslashes() {
        let cfg = Config {
            exclude_paths: vec!["proto/**".into()],
            ..Config::default()
        };
        // Windows-style path should still match.
        assert!(cfg.is_path_excluded("proto\\foo\\bar.go"));
    }
}