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
412use std::os::unix::fs::PermissionsExt;
use std::os::unix::prelude::ExitStatusExt;
use std::path::Path;
use std::process::{Command, Output};
use std::time::Instant;
use std::{fs, process};
use jwalk::WalkDir;
use log::{error, info};
use once_cell::sync::{Lazy, OnceCell};
use rand::prelude::*;
use rand::{Rng, rng};
use crate::obj::ProgramConfig;
use crate::settings::{Setting, TIMEOUT_MESSAGE};
pub static START_TIME: Lazy<Instant> = Lazy::new(Instant::now);
pub static TIMEOUT_SECS: OnceCell<u64> = OnceCell::new();
#[derive(PartialOrd, PartialEq, Eq, Clone, Copy, Debug)]
pub enum CheckGroupFileMode {
None,
ByFolder,
ByFilesGroup,
}
pub(crate) fn check_if_app_ends() -> bool {
let elapsed = START_TIME.elapsed().as_secs();
let timeout = TIMEOUT_SECS.get().unwrap();
elapsed > *timeout
}
pub(crate) fn close_app_if_timeouts() {
if check_if_app_ends() {
info!("Timeout reached, closing app");
std::process::exit(0);
}
}
pub(crate) fn remove_and_create_entire_folder(folder_name: &str) {
if Path::new(folder_name).exists() {
info!("Removing folder {folder_name}");
if let Err(e) = fs::remove_dir_all(folder_name) {
let number_of_files = WalkDir::new(folder_name).max_depth(999).into_iter().count();
panic!("Failed to remove folder {folder_name} (number of files {number_of_files}), reason {e}");
}
info!("Folder {folder_name} removed");
} else {
info!("Folder {folder_name} not exists, so not removing it");
}
info!("Creating folder {folder_name}");
fs::create_dir_all(folder_name).unwrap();
info!("Folder {folder_name} created");
}
pub(crate) fn create_new_file_name(setting: &Setting, old_name: &str) -> String {
let mut random_number = rand::rng().random_range(1..100_000);
loop {
let pat = Path::new(&old_name);
let extension = pat.extension().unwrap().to_str().unwrap().to_string();
let file_name = pat.file_stem().unwrap().to_str().unwrap().to_string();
let new_name = format!("{}/{file_name}{}.{extension}", setting.broken_files_dir, random_number);
if !Path::new(&new_name).exists() {
return new_name;
}
random_number += 1;
}
}
pub(crate) fn create_new_file_name_for_minimization(setting: &Setting, old_name: &str) -> String {
let mut random_number = rand::rng().random_range(1..1000);
loop {
let pat = Path::new(&old_name);
let extension = pat.extension().unwrap().to_str().unwrap().to_string();
let file_name = pat.file_stem().unwrap().to_str().unwrap().to_string();
let new_name = format!(
"{}/{file_name}_minimized_{random_number}.{extension}",
setting.broken_files_dir,
);
if !Path::new(&new_name).exists() {
return new_name;
}
random_number += 1;
}
}
pub(crate) fn collect_output(output: &Output) -> String {
let stdout = &output.stdout;
let stderr = &output.stderr;
let stdout_str = String::from_utf8_lossy(stdout);
let stderr_str = String::from_utf8_lossy(stderr);
format!("{stdout_str}\n{stderr_str}")
}
pub(crate) fn try_to_save_file(full_name: &str, new_name: &str) {
if let Err(e) = fs::copy(full_name, new_name) {
error!("Failed to copy file {full_name}, reason {e}, (maybe broken files folder not exists?)");
}
}
pub(crate) fn minimize_new(obj: &Box<dyn ProgramConfig>, full_name: &str) {
let mut minimization_command = obj.get_minimize_command(full_name);
let minimization_command_str = collect_command_to_string(&minimization_command);
let output = minimization_command.spawn().unwrap().wait_with_output().unwrap();
let str_out = collect_output(&output);
if obj.get_settings().debug_print_results {
info!("Minimization output: {str_out}");
info!("Minimization command: {minimization_command_str}");
}
}
pub(crate) fn execute_command_on_pack_of_files(
obj: &Box<dyn ProgramConfig>,
folder_name: &str,
files: &[String],
) -> OutputResult {
let (child, command) = match obj.get_files_group_mode() {
CheckGroupFileMode::ByFolder => (obj.run_command(folder_name), obj.get_full_command(folder_name)),
CheckGroupFileMode::ByFilesGroup => (obj.run_group_command(files), obj.get_group_command(files)),
CheckGroupFileMode::None => panic!("Invalid mode"),
};
let output = child.wait_with_output().unwrap();
let mut str_out = collect_output(&output);
let is_signal_broken = !obj.get_settings().allowed_signal_statuses.is_empty()
&& output
.status
.signal()
.is_some_and(|code| !obj.get_settings().allowed_signal_statuses.contains(&code));
let is_status_code_broken = !obj.get_settings().allowed_error_statuses.is_empty()
&& output
.status
.code()
.is_some_and(|code| !obj.get_settings().allowed_error_statuses.contains(&code));
// Additionally status code is 124, but we skip here checking it, because at least for now it works fine
let timeouted = obj.get_settings().timeout_group > 0 && str_out.contains(TIMEOUT_MESSAGE);
let ignore_timeout = obj.get_settings().allowed_error_statuses.contains(&124);
str_out.push_str(&format!(
"\n##### Automatic Fuzzer note, output status \"{:?}\", output signal \"{:?}\"\n",
output.status.code(),
output.status.signal()
));
OutputResult::new(
output.status.code(),
output.status.signal(),
is_signal_broken,
is_status_code_broken,
obj.is_broken(&str_out, None), // Cannot type only one file, so no content to check
timeouted,
str_out,
collect_command_to_string(&command),
ignore_timeout,
)
}
#[allow(unused)]
#[derive(Debug)]
pub(crate) struct OutputResult {
output: String,
command_str: String,
code: Option<i32>,
signal: Option<i32>,
is_signal_broken: bool,
is_status_code_broken: bool,
// timeouted is only field to check if timeout was reached
// if timeouted is true, then always is_signal_broken is also true
have_invalid_output: bool,
timeouted: bool,
ignore_timeout: bool,
}
impl OutputResult {
#[allow(clippy::fn_params_excessive_bools)]
pub(crate) fn new(
code: Option<i32>,
signal: Option<i32>,
is_signal_broken: bool,
is_status_code_broken: bool,
have_invalid_output: bool,
timeouted: bool,
output: String,
command_str: String,
ignore_timeout: bool,
) -> Self {
Self {
output,
command_str,
code,
signal,
is_signal_broken,
is_status_code_broken,
have_invalid_output,
timeouted,
ignore_timeout,
}
}
pub(crate) fn is_broken(&self) -> bool {
if self.timeouted && self.ignore_timeout {
return false;
}
self.is_signal_broken || self.have_invalid_output || self.is_status_code_broken || self.timeouted
}
// pub(crate) fn is_only_signal_broken(&self) -> bool {
// self.is_signal_broken && !self.have_invalid_output && !self.is_status_code_broken
// }
pub(crate) fn get_output(&self) -> &str {
&self.output
}
// pub(crate) fn get_command_str(&self) -> &str {
// &self.command_str
// }
// pub(crate) fn debug_print(&self) {
// info!("Is broken: {}, is_signal_broken - {}, have_invalid_output - {}, is_status_code_broken - {}, timeouted - {}, code - {:?}, signal - {:?}", self.is_broken(), self.is_signal_broken, self.have_invalid_output, self.is_status_code_broken, self.timeouted, self.code, self.signal);
// }
}
#[allow(clippy::borrowed_box)]
pub(crate) fn execute_command_and_connect_output(obj: &Box<dyn ProgramConfig>, full_name: &str) -> OutputResult {
let content_before = fs::read(full_name).unwrap(); // In each iteration be sure that before and after, file is the same
let command = obj.get_full_command(full_name);
let child = obj.run_command(full_name);
let output = child.wait_with_output().unwrap();
let mut str_out = collect_output(&output);
let is_signal_broken = !obj.get_settings().allowed_signal_statuses.is_empty()
&& output
.status
.signal()
.is_some_and(|code| !obj.get_settings().allowed_signal_statuses.contains(&code));
let is_status_code_broken = !obj.get_settings().allowed_error_statuses.is_empty()
&& output
.status
.code()
.is_some_and(|code| !obj.get_settings().allowed_error_statuses.contains(&code));
let timeouted = obj.get_settings().timeout > 0 && str_out.contains(TIMEOUT_MESSAGE);
let ignore_timeout = obj.get_settings().allowed_error_statuses.contains(&124);
let res = fs::write(full_name, &content_before); // TODO read and save only in unsafe mode, most of tools not works unsafe - not try to fix things, but only reads content of file, so the no need to save previous content of file
assert!(
res.is_ok(),
"{res:?} - {full_name} - probably you need to set write permissions to this file"
);
str_out.push_str(&format!(
"\n##### Automatic Fuzzer note, output status \"{:?}\", output signal \"{:?}\"\n",
output.status.code(),
output.status.signal()
));
OutputResult::new(
output.status.code(),
output.status.signal(),
is_signal_broken,
is_status_code_broken,
obj.is_broken(&str_out, Some(full_name.to_string())),
timeouted,
str_out,
collect_command_to_string(&command),
ignore_timeout,
)
}
pub(crate) fn check_files_number(name: &str, dir: &str) {
info!(
"{name} - {} - Files Number {}.",
dir,
WalkDir::new(dir)
.max_depth(999)
.into_iter()
.flatten()
.filter(|e| e.path().is_file())
.count()
);
}
pub(crate) fn calculate_number_of_files(dir: &str) -> usize {
let mut number_of_files = 0;
for i in WalkDir::new(dir).max_depth(999).into_iter().flatten() {
if i.path().is_file() {
number_of_files += 1;
}
}
number_of_files
}
pub(crate) fn generate_files(obj: &Box<dyn ProgramConfig>, settings: &Setting) {
let command = obj.broken_file_creator();
let output = command.wait_with_output().unwrap();
let out = String::from_utf8(output.stdout).unwrap();
if !output.status.success() {
error!("{:?}", output.status);
error!("{out}");
error!("Failed to generate files");
process::exit(1);
}
if settings.debug_print_broken_files_creator {
info!("{out}");
}
}
pub(crate) fn collect_files(settings: &Setting) -> (Vec<String>, u64) {
let mut size_all = 0;
let mut files = Vec::new();
assert!(Path::new(&settings.temp_possible_broken_files_dir).is_dir());
for i in WalkDir::new(&settings.temp_possible_broken_files_dir)
.max_depth(999)
.into_iter()
.flatten()
{
let path = i.path();
if !path.is_file() {
continue;
}
let Ok(metadata) = i.metadata() else {
continue;
};
metadata.permissions().set_mode(0o777);
let Some(s) = path.to_str() else {
continue;
};
if settings.extensions.iter().any(|e| s.to_lowercase().ends_with(e)) {
files.push(s.to_string());
size_all += metadata.len();
}
}
files.shuffle(&mut rng());
if files.len() > settings.max_collected_files {
files.truncate(settings.max_collected_files);
}
if files.is_empty() {
dbg!(&settings);
assert!(!files.is_empty());
}
(files, size_all)
}
pub(crate) fn collect_command_to_string(command: &Command) -> String {
let args = command
.get_args()
.map(|e| {
let tmp_string = e.to_string_lossy();
if [" ", "\"", "\\", "/"].iter().any(|e| tmp_string.contains(e)) {
format!("\"{}\"", tmp_string.replace('"', "\\\""))
} else {
tmp_string.to_string()
}
})
.collect::<Vec<_>>();
format!("{} {}", command.get_program().to_string_lossy(), args.join(" "))
}
#[cfg(test)]
mod tests {
use std::ffi::OsStr;
use super::*;
#[test]
fn test_collect_command_to_string_simple() {
let mut command = Command::new("echo");
command.arg("Hello");
let result = collect_command_to_string(&command);
assert_eq!(result, "echo Hello");
}
#[test]
fn test_collect_command_to_string_with_spaces() {
let mut command = Command::new("echo");
command.arg("Hello World");
let result = collect_command_to_string(&command);
assert_eq!(result, "echo \"Hello World\"");
}
#[test]
fn test_collect_command_to_string_with_special_chars() {
let mut command = Command::new("echo");
command.arg("Hello \"World\"");
let result = collect_command_to_string(&command);
assert_eq!(result, "echo \"Hello \\\"World\\\"\"");
}
#[test]
fn test_collect_command_to_string_with_multiple_args() {
let mut command = Command::new("echo");
command.args(["Hello", "World"]);
let result = collect_command_to_string(&command);
assert_eq!(result, "echo Hello World");
}
#[test]
fn test_collect_command_to_string_with_os_str() {
let mut command = Command::new("echo");
command.arg(OsStr::new("Hello"));
let result = collect_command_to_string(&command);
assert_eq!(result, "echo Hello");
}
}