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
//! Compiler Wrapper from `LibAFL`

#![deny(rustdoc::broken_intra_doc_links)]
#![deny(clippy::all)]
#![deny(clippy::pedantic)]
#![allow(
    clippy::unreadable_literal,
    clippy::type_repetition_in_bounds,
    clippy::missing_errors_doc,
    clippy::cast_possible_truncation,
    clippy::used_underscore_binding,
    clippy::ptr_as_ptr,
    clippy::missing_panics_doc,
    clippy::missing_docs_in_private_items,
    clippy::module_name_repetitions,
    clippy::unreadable_literal
)]
#![cfg_attr(not(test), warn(
    missing_debug_implementations,
    missing_docs,
    //trivial_casts,
    trivial_numeric_casts,
    unused_extern_crates,
    unused_import_braces,
    unused_qualifications,
    //unused_results
))]
#![cfg_attr(test, deny(
    missing_debug_implementations,
    missing_docs,
    //trivial_casts,
    trivial_numeric_casts,
    unused_extern_crates,
    unused_import_braces,
    unused_qualifications,
    unused_must_use,
    missing_docs,
    //unused_results
))]
#![cfg_attr(
    test,
    deny(
        bad_style,
        dead_code,
        improper_ctypes,
        non_shorthand_field_patterns,
        no_mangle_generic_items,
        overflowing_literals,
        path_statements,
        patterns_in_fns_without_body,
        unconditional_recursion,
        unused,
        unused_allocation,
        unused_comparisons,
        unused_parens,
        while_true
    )
)]

use std::{path::Path, process::Command};

pub mod ar;
pub use ar::ArWrapper;
pub mod cfg;
pub use cfg::{CfgEdge, ControlFlowGraph, EntryBasicBlockInfo, HasWeight};
pub mod clang;
pub use clang::{ClangWrapper, LLVMPasses};
pub mod libtool;
pub use libtool::LibtoolWrapper;

/// `LibAFL` CC Error Type
#[derive(Debug)]
pub enum Error {
    /// CC Wrapper called with invalid arguments
    InvalidArguments(String),
    /// Io error occurred
    Io(std::io::Error),
    /// Something else happened
    Unknown(String),
}

/// `LibAFL` target configuration
#[derive(Debug, Clone)]
pub enum Configuration {
    /// Default uninstrumented configurations
    Default,
    /// Sanitizing addresses
    AddressSanitizer,
    /// Sanitizing undefined behavior
    UndefinedBehaviorSanitizer,
    /// Generating a coverage map
    GenerateCoverageMap,
    /// Generating coverage profile data for `llvm-cov`
    GenerateCoverageProfile,
    /// Instrumenting for cmplog/redqueen
    CmpLog,
    /// A compound `Configuration`, made up of a list of other `Configuration`s
    Compound(Vec<Self>),
}

impl Configuration {
    /// Get compiler flags for this `Configuration`
    pub fn to_flags(&self) -> Result<Vec<String>, Error> {
        Ok(match self {
            Configuration::Default => vec![],
            // hardware asan is more memory efficient than asan on arm64
            #[cfg(all(
                any(target_os = "linux", target_os = "android"),
                target_arch = "aarch64"
            ))]
            Configuration::AddressSanitizer => vec!["-fsanitize=hwaddress".to_string()],
            #[cfg(not(all(
                any(target_os = "linux", target_os = "android"),
                target_arch = "aarch64"
            )))]
            Configuration::AddressSanitizer => vec!["-fsanitize=address".to_string()],
            Configuration::UndefinedBehaviorSanitizer => vec!["-fsanitize=undefined".to_string()],
            Configuration::GenerateCoverageMap => {
                vec!["-fsanitize-coverage=trace-pc-guard".to_string()]
            }
            Configuration::CmpLog => vec!["-fsanitize-coverage=trace-cmp".to_string()],
            Configuration::GenerateCoverageProfile => {
                vec![
                    "-fprofile-instr-generate".to_string(),
                    "-fcoverage-mapping".to_string(),
                ]
            }
            Configuration::Compound(configurations) => {
                let mut result: Vec<String> = vec![];
                for configuration in configurations {
                    result.extend(configuration.to_flags()?);
                }
                result
            }
        })
    }
    /// Insert a `Configuration` specific 'tag' in the extension of the given file
    #[must_use]
    pub fn replace_extension(&self, path: &Path) -> std::path::PathBuf {
        let mut parent = if let Some(parent) = path.parent() {
            parent.to_path_buf()
        } else {
            std::path::PathBuf::from("")
        };
        let output = path.file_name().unwrap();
        let output = output.to_str().unwrap();

        let new_filename = if let Some((filename, extension)) = output.split_once('.') {
            if let Configuration::Default = self {
                format!("{filename}.{extension}")
            } else {
                format!("{filename}.{self}.{extension}")
            }
        } else if let Configuration::Default = self {
            output.to_string()
        } else {
            format!("{output}.{self}")
        };
        parent.push(new_filename);
        parent
    }
}

impl std::str::FromStr for Configuration {
    type Err = ();
    fn from_str(input: &str) -> Result<Configuration, Self::Err> {
        Ok(match input {
            "asan" => Configuration::AddressSanitizer,
            "ubsan" => Configuration::UndefinedBehaviorSanitizer,
            "coverage" => Configuration::GenerateCoverageMap,
            "llvm-cov" => Configuration::GenerateCoverageProfile,
            "cmplog" => Configuration::CmpLog,
            _ => Configuration::Default,
        })
    }
}

impl std::fmt::Display for Configuration {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Configuration::Default => write!(f, ""),
            Configuration::AddressSanitizer => write!(f, "asan"),
            Configuration::UndefinedBehaviorSanitizer => write!(f, "ubsan"),
            Configuration::GenerateCoverageMap => write!(f, "coverage"),
            Configuration::GenerateCoverageProfile => write!(f, "llvm-cov"),
            Configuration::CmpLog => write!(f, "cmplog"),
            Configuration::Compound(configurations) => {
                let mut result: Vec<String> = vec![];
                for configuration in configurations {
                    result.push(format!("{configuration}"));
                }
                write!(f, "{}", result.join("_"))
            }
        }
    }
}

// TODO macOS
/// extension for static libraries
#[cfg(windows)]
pub const LIB_EXT: &str = "lib";
/// extension for static libraries
#[cfg(not(windows))]
pub const LIB_EXT: &str = "a";

/// prefix for static libraries
#[cfg(windows)]
pub const LIB_PREFIX: &str = "";
/// prefix for static libraries
#[cfg(not(windows))]
pub const LIB_PREFIX: &str = "lib";

/// Wrap a tool hijacking its arguments
pub trait ToolWrapper {
    /// Set the wrapper arguments parsing a command line set of arguments
    fn parse_args<S>(&mut self, args: &[S]) -> Result<&'_ mut Self, Error>
    where
        S: AsRef<str>;

    /// Add an argument
    fn add_arg<S>(&mut self, arg: S) -> &'_ mut Self
    where
        S: AsRef<str>;

    /// Add arguments
    fn add_args<S>(&mut self, args: &[S]) -> &'_ mut Self
    where
        S: AsRef<str>,
    {
        for arg in args {
            self.add_arg(arg);
        }
        self
    }

    /// Add a `Configuration`
    fn add_configuration(&mut self, configuration: Configuration) -> &'_ mut Self;

    /// Command to run the compiler
    fn command(&mut self) -> Result<Vec<String>, Error>;

    /// Command to run the compiler for a given `Configuration`
    #[allow(clippy::too_many_lines)]
    fn command_for_configuration(
        &mut self,
        configuration: Configuration,
    ) -> Result<Vec<String>, Error>;

    /// Get the list of requested `Configuration`s
    fn configurations(&self) -> Result<Vec<Configuration>, Error>;

    /// Whether to ignore the configured `Configurations`. Useful for e.g. nested calls to
    /// `libafl_cc` from `libafl_libtool`.
    fn ignore_configurations(&self) -> Result<bool, Error>;

    /// Get if in linking mode
    fn is_linking(&self) -> bool;

    /// Filter out argumets
    fn filter(&self, _args: &mut Vec<String>) {}

    /// Silences `libafl_cc` output
    fn silence(&mut self, value: bool) -> &'_ mut Self;

    /// Returns `true` if `silence` was called with `true`
    fn is_silent(&self) -> bool;

    /// Run the tool
    fn run(&mut self) -> Result<Option<i32>, Error> {
        let mut last_status = Ok(None);
        let configurations = if self.ignore_configurations()? {
            vec![Configuration::Default]
        } else {
            self.configurations()?
        };
        for configuration in configurations {
            let mut args = self.command_for_configuration(configuration)?;
            self.filter(&mut args);

            if !self.is_silent() {
                dbg!(args.clone());
            }
            if args.is_empty() {
                last_status = Err(Error::InvalidArguments(
                    "The number of arguments cannot be 0".into(),
                ));
                continue;
            }
            let status = match Command::new(&args[0]).args(&args[1..]).status() {
                Ok(s) => s,
                Err(e) => {
                    last_status = Err(Error::Io(e));
                    continue;
                }
            };
            if !self.is_silent() {
                dbg!(status);
            }
            last_status = Ok(status.code());
        }
        last_status
    }
}

/// Wrap a compiler hijacking its arguments
pub trait CompilerWrapper: ToolWrapper {
    /// Add a compiler argument only when compiling
    fn add_cc_arg<S>(&mut self, arg: S) -> &'_ mut Self
    where
        S: AsRef<str>;

    /// Add a compiler argument only when linking
    fn add_link_arg<S>(&mut self, arg: S) -> &'_ mut Self
    where
        S: AsRef<str>;

    /// Add compiler arguments only when compiling
    fn add_cc_args<S>(&mut self, args: &[S]) -> &'_ mut Self
    where
        S: AsRef<str>,
    {
        for arg in args {
            self.add_cc_arg(arg);
        }
        self
    }

    /// Add compiler arguments only when linking
    fn add_link_args<S>(&mut self, args: &[S]) -> &'_ mut Self
    where
        S: AsRef<str>,
    {
        for arg in args {
            self.add_link_arg(arg);
        }
        self
    }

    /// Link static C lib
    fn link_staticlib<S>(&mut self, dir: &Path, name: S) -> &'_ mut Self
    where
        S: AsRef<str>;
}