ziggy 1.7.2

A multi-fuzzer management utility for all of your Rust fuzzing needs 🧑‍🎤
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
use crate::{
    Common, Cover,
    util::Utf8PathBuf,
    util::{Context, progress_bar},
};
use anyhow::{Context as _, Result, bail};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use std::{
    env, fmt, fs,
    io::{Read, Write},
    path::{Path, PathBuf},
    process,
    str::FromStr,
};

impl Cover {
    pub fn generate_coverage(&self, common: &Common) -> Result<(), anyhow::Error> {
        let cx = Context::new(common, self.target.clone())?;

        let base_dir = cx.target_dir.join("coverage/debug");
        let coverage_target_dir = base_dir.join(format!("deps/coverage-{}", &cx.bin_target));
        let cfg = Cfg::new(
            base_dir.join(&cx.bin_target),
            coverage_target_dir.join("cov-%p-%m.profraw"),
        )?;

        eprintln!("Generating coverage");

        // build the runner
        Self::build_runner(common).context("instrumenting for coverage")?;

        let mut cov_dir_exists = coverage_target_dir.is_dir();
        if !self.keep && cov_dir_exists {
            fs::remove_dir_all(&coverage_target_dir)
                .with_context(|| format!("⚠️  couldn't remove {}", &coverage_target_dir))?;
            cov_dir_exists = false;
        }
        if !cov_dir_exists {
            fs::create_dir_all(&coverage_target_dir).context("output dir for profraws")?;
        }

        let input_path = PathBuf::from(
            self.input
                .display()
                .to_string()
                .replace("{ziggy_output}", &self.ziggy_output.display().to_string())
                .replace("{target_name}", &cx.bin_target),
        );

        let coverage_corpus = if input_path.is_dir() {
            fs::read_dir(input_path)
                .context("opening corpus")?
                .flatten()
                .map(|e| e.path())
                .collect()
        } else {
            vec![input_path]
        };

        if let Some(threads) = self.jobs {
            rayon::ThreadPoolBuilder::default()
                .num_threads(threads)
                .build_global()
                .expect("Failure initializing thread pool");
        }

        let coverage_dir = self
            .output
            .display()
            .to_string()
            .replace("{ziggy_output}", &self.ziggy_output.display().to_string())
            .replace("{target_name}", &cx.bin_target);

        if let Err(e) = fs::remove_dir_all(&coverage_dir)
            && e.kind() != std::io::ErrorKind::NotFound
        {
            return Err(anyhow::Error::from(e))
                .with_context(|| format!("⚠️  couldn't remove {coverage_dir}"));
        }

        eprintln!("    Generating raw profiles");
        let pb = progress_bar(coverage_corpus.len() as u64);
        let log_dir = self.ziggy_output.join(format!("{}/logs", &cx.bin_target));
        fs::create_dir_all(&log_dir).context("output dir for logs")?;
        let log_file = std::sync::Mutex::new(
            std::fs::File::create(log_dir.join("coverage.log")).context("logfile")?,
        );
        let tls = thread_local::ThreadLocal::new();
        #[expect(clippy::significant_drop_tightening)]
        coverage_corpus.into_par_iter().for_each(|file| {
            let mut buf = tls
                .get_or(|| std::cell::RefCell::new(Vec::with_capacity(8 * 1024)))
                .borrow_mut();
            buf.clear();
            let _ = cfg.profile(file.as_path(), &mut buf);
            let mut log_file = log_file.lock().unwrap();
            let _ = log_file.write_all(&buf);
            // use `lock_file` mutex to avoid contention on progress bar
            pb.inc(1);
        });
        pb.finish();

        // We generate the code coverage report
        eprintln!("\n    Generating coverage report");

        let out_dir = PathBuf::from(coverage_dir);
        let profdata = out_dir.join("coverage.prodata");
        fs::create_dir_all(&out_dir).context("output dir for coverage")?;
        cfg.merge_profraw(&profdata, self.jobs)
            .context("llvm_profdata: merging profraw files")?;

        let mut fmt = 0_u8;
        let types = {
            for t in &self.output_type {
                match t {
                    ReportType::Html => fmt |= 1 << 0,
                    ReportType::Text => fmt |= 1 << 1,
                    ReportType::Json => fmt |= 1 << 2,
                    ReportType::LCov => fmt |= 1 << 3,
                }
            }
            [
                ReportType::Html,
                ReportType::Text,
                ReportType::Json,
                ReportType::LCov,
            ]
            .into_iter()
            .enumerate()
            .filter_map(|(s, t)| (fmt & (1 << s) != 0).then_some(t))
        };

        for t in types {
            cfg.report_coverage(&profdata, &out_dir, t, self.jobs)
                .with_context(|| format!("llvm_cov report of type `{t}`"))?;
        }

        Ok(())
    }

    /// Build the runner with the appropriate flags for coverage
    pub fn build_runner(common: &Common) -> Result<(), anyhow::Error> {
        let target_dir = common.target_dir()?;

        let mut coverage_rustflags =
            env::var("COVERAGE_RUSTFLAGS").unwrap_or_else(|_| "-Cinstrument-coverage".to_string());
        coverage_rustflags.push(' ');
        coverage_rustflags.push_str(&env::var("RUSTFLAGS").unwrap_or_default());

        let profiles_dir = target_dir.join("coverage/build-coverage-profraw");
        fs::create_dir_all(&profiles_dir)?;

        let build = common
            .cargo()
            .args([
                "rustc",
                "--features=ziggy/coverage",
                &format!("--target-dir={}", target_dir.join("coverage")),
            ])
            .env("RUSTFLAGS", coverage_rustflags)
            .env(
                "LLVM_PROFILE_FILE",
                profiles_dir.join("build-%p-%m.profraw"),
            )
            .spawn()
            .context("⚠️  couldn't spawn rustc for coverage")?
            .wait()
            .context("⚠️  couldn't wait for rustc during coverage")?;
        if !build.success() {
            bail!("⚠️  build failed");
        }

        fs::remove_dir_all(&profiles_dir)
            .with_context(|| format!("⚠️  error removing dir {profiles_dir}"))?;
        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct Cfg {
    runner: Utf8PathBuf,
    prof_file_template: Utf8PathBuf,
    llvm_profdata: PathBuf,
    llvm_cov: PathBuf,
}

impl Cfg {
    pub fn new(runner: Utf8PathBuf, prof_file_template: Utf8PathBuf) -> Result<Self> {
        let profdata = env::var_os("LLVM_PROFDATA");
        let cov = env::var_os("LLVM_COV");
        let target_libdir = if profdata.is_none() || cov.is_none() {
            let bytes = std::process::Command::new(
                std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()),
            )
            .arg("--print=target-libdir")
            .output()
            .context("failed running `rustc --print=target-libdir")?
            .stdout;
            PathBuf::from(
                String::from_utf8(bytes).expect("invalid utf8 output from `rustc --print`"),
            )
        } else {
            PathBuf::new()
        };

        let llvm_profdata = if let Some(path) = profdata {
            PathBuf::from(path)
        } else {
            let mut libdir: PathBuf = target_libdir.clone();
            libdir.pop();
            libdir.push("bin");
            libdir.push("llvm-profdata");
            if !libdir.exists() {
                bail!("⚠️  llvm-profdata not found: try `rustup component add llvm-tools`");
            }
            libdir
        };

        let llvm_cov = if let Some(path) = cov {
            PathBuf::from(path)
        } else {
            let mut libdir: PathBuf = target_libdir;
            libdir.pop();
            libdir.push("bin");
            libdir.push("llvm-cov");
            if !libdir.exists() {
                bail!("⚠️  llvm-cov not found: try `rustup component add llvm-tools`");
            }
            libdir
        };

        Ok(Self {
            runner,
            prof_file_template,
            llvm_profdata,
            llvm_cov,
        })
    }

    pub fn llvm_profdata(&self) -> process::Command {
        process::Command::new(&self.llvm_profdata)
    }

    pub fn llvm_cov(&self) -> process::Command {
        process::Command::new(&self.llvm_cov)
    }

    pub fn runner_path(&self) -> &Path {
        self.runner.as_std_path()
    }

    pub fn profile_simple(&self, seed: &Path, profraw_pattern_overwrite: Option<&Path>) {
        let _ = process::Command::new(&self.runner)
            .arg(seed)
            .stdin(process::Stdio::null())
            .stdout(process::Stdio::null())
            .stderr(process::Stdio::null())
            .env(
                "LLVM_PROFILE_FILE",
                profraw_pattern_overwrite.unwrap_or(self.prof_file_template.as_std_path()),
            )
            .status();
    }

    fn profile(&self, seed: &Path, output: &mut Vec<u8>) -> Result<(), anyhow::Error> {
        // redirect stderr and stdout into buffer (via pipe)
        let (mut rx, tx) = std::io::pipe()?;

        let mut child = process::Command::new(&self.runner)
            .arg(seed)
            .stdin(std::process::Stdio::null())
            .stdout(tx.try_clone()?)
            .stderr(tx)
            .env("LLVM_PROFILE_FILE", &self.prof_file_template)
            .spawn()?;

        rx.read_to_end(output)?;
        let status = child.wait()?;
        if !status.success() {
            bail!("⚠️  runner failed with exit code `{status}`");
        }
        Ok(())
    }

    pub fn merge_profraw(&self, output: &Path, jobs: Option<usize>) -> Result<(), anyhow::Error> {
        let profiles_dir = {
            let mut path = self.prof_file_template.clone();
            path.pop();
            path
        };

        // Write the profraw paths to a file and pass it via `-f` instead of
        // passing each path on the command line, which can exceed ARG_MAX
        // when coverage runs produce a large number of profraw files.
        let mut list_file = std::io::BufWriter::new(
            tempfile::NamedTempFile::new()
                .context("creating temp file for llvm-profdata input list")?,
        );
        for entry in fs::read_dir(&profiles_dir)? {
            let path = entry?.path();
            if path.extension().is_some_and(|ext| ext == "profraw") {
                writeln!(list_file, "{}", path.display())
                    .context("writing profraw path to input list")?;
            }
        }

        let status = self
            .llvm_profdata()
            .arg("merge")
            .arg("--sparse")
            .arg("--failure-mode=warn")
            .arg("-f")
            .arg(
                list_file
                    .into_inner()
                    .context("flushing llvm-profdata input list")?
                    .path(),
            )
            .arg("-o")
            .arg(output)
            .args(jobs.map(|n| format!("-j={n}")))
            .status()?;
        if !status.success() {
            bail!("⚠️  llvm-profdata failed with exit code `{status}`");
        }
        Ok(())
    }

    pub fn report_coverage(
        &self,
        merged_profile: &Path,
        output: &Path,
        format: ReportType,
        jobs: Option<usize>,
    ) -> Result<()> {
        use ReportType::{Html, Json, LCov, Text};

        let mut cov_cmd = self.llvm_cov();
        match format {
            Html => cov_cmd.args(["show", "-format=html"]),
            Text => cov_cmd.args(["show", "-format=text"]),
            Json => cov_cmd.args(["export", "-format=text"]),
            LCov => cov_cmd.args(["export", "-format=lcov"]),
        };
        match format {
            Text | Html => {
                cov_cmd.arg("-output-dir").arg(output).args([
                    "-show-directory-coverage",
                    "-show-line-counts-or-regions",
                    "-show-branches=count",
                ]);
            }
            Json => {
                cov_cmd.stdout(fs::File::create(output.join("coverage.json"))?);
            }
            LCov => {
                cov_cmd.stdout(fs::File::create(output.join("coverage.lcov"))?);
            }
        }
        let status = cov_cmd
            .arg("-instr-profile")
            .arg(merged_profile)
            .arg(&self.runner)
            .args(jobs.map(|n| format!("-j={n}")))
            .status()?;
        if !status.success() {
            bail!("⚠️  llvm-cov failed with exit code `{status}`");
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
pub enum ReportType {
    Html,
    Text,
    Json,
    LCov,
}

impl FromStr for ReportType {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(match s.to_ascii_lowercase().as_str() {
            "html" => Self::Html,
            "text" | "txt" => Self::Text,
            "json" => Self::Json,
            "lcov" => Self::LCov,
            _ => anyhow::bail!("help: available types: `html`, `text`, `json`, `lcov`"),
        })
    }
}

impl fmt::Display for ReportType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Html => write!(f, "html"),
            Self::Text => write!(f, "text"),
            Self::Json => write!(f, "json"),
            Self::LCov => write!(f, "lcov"),
        }
    }
}