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
#![recursion_limit = "1024"]
extern crate cargo_binutils;
extern crate chrono;
extern crate crossbeam;
extern crate fomat_macros;
extern crate globset;
extern crate log;
extern crate quick_xml as xml;
extern crate rustc_hash;
extern crate semver;
extern crate serde_json;
extern crate smallvec;
extern crate tempfile;
extern crate uuid;
extern crate walkdir;
extern crate zip;

mod defs;
pub use crate::defs::*;

mod producer;
pub use crate::producer::*;

mod gcov;
pub use crate::gcov::*;

mod llvm_tools;
pub use crate::llvm_tools::*;

mod parser;
pub use crate::parser::*;

mod filter;
pub use crate::filter::*;

mod path_rewriting;
pub use crate::path_rewriting::*;

mod output;
pub use crate::output::*;

mod reader;
pub use crate::reader::*;

mod covdir;
pub use crate::covdir::*;

pub mod html;

mod file_filter;
pub use crate::file_filter::*;

use log::error;
use std::collections::{btree_map, hash_map};
use std::fs;
use std::io::{BufReader, Cursor};
use std::path::PathBuf;
use walkdir::WalkDir;

// Merge results, without caring about duplicate lines (they will be removed at the end).
pub fn merge_results(result: &mut CovResult, result2: CovResult) {
    for (&line_no, &execution_count) in &result2.lines {
        match result.lines.entry(line_no) {
            btree_map::Entry::Occupied(c) => {
                *c.into_mut() += execution_count;
            }
            btree_map::Entry::Vacant(v) => {
                v.insert(execution_count);
            }
        };
    }

    for (line_no, taken) in result2.branches {
        match result.branches.entry(line_no) {
            btree_map::Entry::Occupied(c) => {
                let v = c.into_mut();
                for (x, y) in taken.iter().zip(v.iter_mut()) {
                    *y |= x;
                }
                let l = v.len();
                if taken.len() > l {
                    v.extend(&taken[l..]);
                }
            }
            btree_map::Entry::Vacant(v) => {
                v.insert(taken);
            }
        };
    }

    for (name, function) in result2.functions {
        match result.functions.entry(name) {
            hash_map::Entry::Occupied(f) => f.into_mut().executed |= function.executed,
            hash_map::Entry::Vacant(v) => {
                v.insert(function);
            }
        };
    }
}

fn add_results(
    mut results: Vec<(String, CovResult)>,
    result_map: &SyncCovResultMap,
    source_dir: &Option<PathBuf>,
) {
    let mut map = result_map.lock().unwrap();
    for result in results.drain(..) {
        let path = match source_dir {
            Some(source_dir) => {
                // the goal here is to be able to merge results for paths like foo/./bar and foo/bar
                if let Ok(p) = canonicalize_path(source_dir.join(&result.0)) {
                    String::from(p.to_str().unwrap())
                } else {
                    result.0
                }
            }
            None => result.0,
        };
        match map.entry(path) {
            hash_map::Entry::Occupied(obj) => {
                merge_results(obj.into_mut(), result.1);
            }
            hash_map::Entry::Vacant(v) => {
                v.insert(result.1);
            }
        };
    }
}

fn rename_single_files(results: &mut Vec<(String, CovResult)>, stem: &str) {
    // sometimes the gcno just contains foo.c
    // so in such case (with option --guess-directory-when-missing)
    // we guess the filename in using the buffer stem
    if let Some(parent) = PathBuf::from(stem).parent() {
        for (file, _) in results.iter_mut() {
            if has_no_parent(file) {
                *file = parent.join(&file).to_str().unwrap().to_string();
            }
        }
    }
}

// Some versions of GCC, because of a bug, generate multiple gcov files for each
// gcno, so we have to support this case too for the time being.
#[derive(PartialEq, Eq)]
enum GcovType {
    Unknown,
    SingleFile,
    MultipleFiles,
}

macro_rules! try_parse {
    ($v:expr, $f:expr) => {
        match $v {
            Ok(val) => val,
            Err(err) => {
                error!("Error parsing file {}: {}", $f, err);
                continue;
            }
        }
    };
}

pub fn consumer(
    working_dir: &PathBuf,
    source_dir: &Option<PathBuf>,
    result_map: &SyncCovResultMap,
    receiver: JobReceiver,
    branch_enabled: bool,
    guess_directory: bool,
    binary_path: &Option<String>,
) {
    let mut gcov_type = GcovType::Unknown;

    while let Ok(work_item) = receiver.recv() {
        if work_item.is_none() {
            break;
        }
        let work_item = work_item.unwrap();
        let new_results = match work_item.format {
            ItemFormat::GCNO => {
                match work_item.item {
                    ItemType::Path((stem, gcno_path)) => {
                        // GCC
                        if let Err(e) = run_gcov(&gcno_path, branch_enabled, working_dir) {
                            error!("Error when running gcov: {}", e);
                            continue;
                        };
                        let gcov_path =
                            gcno_path.file_name().unwrap().to_str().unwrap().to_string() + ".gcov";
                        let gcov_path = working_dir.join(gcov_path);
                        if gcov_type == GcovType::Unknown {
                            gcov_type = if gcov_path.exists() {
                                GcovType::SingleFile
                            } else {
                                GcovType::MultipleFiles
                            };
                        }

                        let mut new_results = if gcov_type == GcovType::SingleFile {
                            let new_results = try_parse!(parse_gcov(&gcov_path), work_item.name);
                            fs::remove_file(gcov_path).unwrap();
                            new_results
                        } else {
                            let mut new_results: Vec<(String, CovResult)> = Vec::new();

                            for entry in WalkDir::new(&working_dir).min_depth(1) {
                                let gcov_path = entry.unwrap();
                                let gcov_path = gcov_path.path();

                                new_results.append(&mut try_parse!(
                                    parse_gcov(&gcov_path),
                                    work_item.name
                                ));

                                fs::remove_file(gcov_path).unwrap();
                            }

                            new_results
                        };

                        if guess_directory {
                            rename_single_files(&mut new_results, &stem);
                        }
                        new_results
                    }
                    ItemType::Buffers(buffers) => {
                        // LLVM
                        match GCNO::compute(
                            &buffers.stem,
                            buffers.gcno_buf,
                            buffers.gcda_buf,
                            branch_enabled,
                        ) {
                            Ok(mut r) => {
                                if guess_directory {
                                    rename_single_files(&mut r, &buffers.stem);
                                }
                                r
                            }
                            Err(e) => {
                                // Just print the error, don't panic and continue
                                error!("Error in computing counters: {}", e);
                                Vec::new()
                            }
                        }
                    }
                    ItemType::Content(_) => {
                        error!("Invalid content type");
                        continue;
                    }
                    ItemType::Paths(_) => {
                        error!("Invalid content type");
                        continue;
                    }
                }
            }
            ItemFormat::PROFRAW => {
                if binary_path.is_none() {
                    error!("The path to the compiled binary must be given as an argument when source-based coverage is used");
                    continue;
                }

                if let ItemType::Paths(profraw_paths) = work_item.item {
                    match llvm_tools::profraws_to_lcov(
                        profraw_paths.as_slice(),
                        binary_path.as_ref().unwrap(),
                        working_dir,
                    ) {
                        Ok(lcov) => try_parse!(parse_lcov(lcov, branch_enabled), work_item.name),
                        Err(e) => {
                            error!("Error while executing llvm tools: {}", e);
                            continue;
                        }
                    }
                } else {
                    error!("Invalid content type");
                    continue;
                }
            }
            ItemFormat::INFO | ItemFormat::JACOCO_XML => {
                if let ItemType::Content(content) = work_item.item {
                    if work_item.format == ItemFormat::INFO {
                        try_parse!(parse_lcov(content, branch_enabled), work_item.name)
                    } else {
                        let buffer = BufReader::new(Cursor::new(content));
                        try_parse!(parse_jacoco_xml_report(buffer), work_item.name)
                    }
                } else {
                    error!("Invalid content type");
                    continue;
                }
            }
        };

        add_results(new_results, result_map, source_dir);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustc_hash::FxHashMap;
    use std::fs::File;
    use std::io::Read;
    use std::sync::{Arc, Mutex};

    #[test]
    fn test_merge_results() {
        let mut functions1: FunctionMap = FxHashMap::default();
        functions1.insert(
            "f1".to_string(),
            Function {
                start: 1,
                executed: false,
            },
        );
        functions1.insert(
            "f2".to_string(),
            Function {
                start: 2,
                executed: false,
            },
        );
        let mut result = CovResult {
            lines: [(1, 21), (2, 7), (7, 0)].iter().cloned().collect(),
            branches: [
                (1, vec![false, false]),
                (2, vec![false, true]),
                (4, vec![true]),
            ]
            .iter()
            .cloned()
            .collect(),
            functions: functions1,
        };
        let mut functions2: FunctionMap = FxHashMap::default();
        functions2.insert(
            "f1".to_string(),
            Function {
                start: 1,
                executed: false,
            },
        );
        functions2.insert(
            "f2".to_string(),
            Function {
                start: 2,
                executed: true,
            },
        );
        let result2 = CovResult {
            lines: [(1, 21), (3, 42), (4, 7), (2, 0), (8, 0)]
                .iter()
                .cloned()
                .collect(),
            branches: [
                (1, vec![false, false]),
                (2, vec![false, true]),
                (3, vec![true]),
            ]
            .iter()
            .cloned()
            .collect(),
            functions: functions2,
        };

        merge_results(&mut result, result2);
        assert_eq!(
            result.lines,
            [(1, 42), (2, 7), (3, 42), (4, 7), (7, 0), (8, 0)]
                .iter()
                .cloned()
                .collect()
        );
        assert_eq!(
            result.branches,
            [
                (1, vec![false, false]),
                (2, vec![false, true]),
                (3, vec![true]),
                (4, vec![true]),
            ]
            .iter()
            .cloned()
            .collect()
        );
        assert!(result.functions.contains_key("f1"));
        assert!(result.functions.contains_key("f2"));
        let mut func = result.functions.get("f1").unwrap();
        assert_eq!(func.start, 1);
        assert_eq!(func.executed, false);
        func = result.functions.get("f2").unwrap();
        assert_eq!(func.start, 2);
        assert_eq!(func.executed, true);
    }

    #[test]
    fn test_merge_relative_path() {
        let mut f = File::open("./test/relative_path/relative_path.info")
            .expect("Failed to open lcov file");
        let mut buf = Vec::new();
        f.read_to_end(&mut buf).unwrap();
        let results = parse_lcov(buf, false).unwrap();
        let result_map: Arc<SyncCovResultMap> = Arc::new(Mutex::new(
            FxHashMap::with_capacity_and_hasher(1, Default::default()),
        ));
        add_results(
            results,
            &result_map,
            &Some(PathBuf::from("./test/relative_path")),
        );
        let result_map = Arc::try_unwrap(result_map).unwrap().into_inner().unwrap();

        assert!(result_map.len() == 1);

        let cpp_file =
            canonicalize_path(PathBuf::from("./test/relative_path/foo/bar/oof.cpp")).unwrap();
        let cpp_file = cpp_file.to_str().unwrap();
        let cov_result = result_map.get(cpp_file).unwrap();

        assert_eq!(
            cov_result.lines,
            [(1, 63), (2, 63), (3, 84), (4, 42)]
                .iter()
                .cloned()
                .collect()
        );
        assert!(cov_result.functions.contains_key("myfun"));
    }

    #[test]
    fn test_ignore_relative_path() {
        let mut f = File::open("./test/relative_path/relative_path.info")
            .expect("Failed to open lcov file");
        let mut buf = Vec::new();
        f.read_to_end(&mut buf).unwrap();
        let results = parse_lcov(buf, false).unwrap();
        let result_map: Arc<SyncCovResultMap> = Arc::new(Mutex::new(
            FxHashMap::with_capacity_and_hasher(3, Default::default()),
        ));
        add_results(results, &result_map, &None);
        let result_map = Arc::try_unwrap(result_map).unwrap().into_inner().unwrap();

        assert!(result_map.len() == 3);
    }
}