Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇
Go aicertificationcloud-engineeringcybercybersecuritycybersecurity-analystcybersecurity-certificationcybersecurity-certificationscybersecurity-educationcybersecurity-jobscybersecurity-portfoliocybersecurity-projectscybersecurity-toolsgrchackinglearningpentestingproject-repositoryprojetcspython
// ©AngelaMos | 2026
// coverage.rs
use std::collections::BTreeSet;
use std::path::Path;
pub const EDGE_FIELD_SEPARATOR: char = ':';
pub const AR_MAGIC: &[u8] = b"!<arch>\n";
pub const AR_HEADER_BYTES: usize = 60;
pub const AR_SIZE_RANGE: std::ops::Range<usize> = 48..58;
pub const BITCODE_MAGIC: &[u8] = b"BC\xc0\xde";
pub const SANCOV_GUARDS_SECTION: &[u8] = b"__sancov_guards";
// How the LIBRARY in this archive was instrumented, which is the precondition under every
// cross-harness coverage number: whether two SEPARATELY LINKED binaries built against it can
// have their edge IDs compared at all.
//
// Read off the artifact rather than inferred. A bitcode member means `afl-clang-lto` will
// re-instrument the whole merged module at every link. A `__sancov_guards` section means the
// library carries PCGUARD guards of its own, assigned IDs at STARTUP by walking the guard
// array. Neither means the library carries no coverage instrumentation at all, so it
// contributes no fixed edges and the only edges in the map are the harness's own - which move
// whenever the harness does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArchiveScheme {
Bitcode,
PcGuard,
Opaque,
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
haystack.len() >= needle.len() && haystack.windows(needle.len()).any(|slot| slot == needle)
}
fn member_scheme(body: &[u8]) -> Option<ArchiveScheme> {
if body.starts_with(BITCODE_MAGIC) {
return Some(ArchiveScheme::Bitcode);
}
if contains(body, SANCOV_GUARDS_SECTION) {
return Some(ArchiveScheme::PcGuard);
}
None
}
#[must_use]
pub fn archive_scheme(path: &Path) -> ArchiveScheme {
let Ok(bytes) = std::fs::read(path) else {
return ArchiveScheme::Opaque;
};
if !bytes.starts_with(AR_MAGIC) {
// Not an archive at all - a bare object or a shared library. Its own contents decide.
return member_scheme(&bytes).unwrap_or(ArchiveScheme::Opaque);
}
let mut at = AR_MAGIC.len();
let mut seen = ArchiveScheme::Opaque;
while at + AR_HEADER_BYTES <= bytes.len() {
let header = &bytes[at..at + AR_HEADER_BYTES];
let size: usize = std::str::from_utf8(&header[AR_SIZE_RANGE])
.ok()
.and_then(|field| field.trim().parse().ok())
.unwrap_or(0);
let body = at + AR_HEADER_BYTES;
if size == 0 || body + size > bytes.len() {
return seen;
}
match member_scheme(&bytes[body..body + size]) {
// One bitcode member is enough: the link re-instruments the merged module, so
// whatever the other members carry is renumbered along with it.
Some(ArchiveScheme::Bitcode) => return ArchiveScheme::Bitcode,
Some(scheme) => seen = scheme,
None => {}
}
// Members are padded to an even offset, and the symbol table is a member like any
// other - it simply never carries either signature, so it needs no special case.
at = body + size + (size & 1);
}
seen
}
#[must_use]
pub fn is_bitcode_archive(path: &Path) -> bool {
archive_scheme(path) == ArchiveScheme::Bitcode
}
// The one archive state whose numbering a second link cannot move. Measured on libpng's real
// emitted climb over 16 seeds: a PCGUARD archive with the harness compiled to match AND linked
// after the library contains the parent's map in 16 of 16, and every other combination of the
// three factors in 0 of 16.
#[must_use]
pub fn is_pcguard_archive(path: &Path) -> bool {
archive_scheme(path) == ArchiveScheme::PcGuard
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EdgeSet {
edges: BTreeSet<u32>,
}
impl EdgeSet {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn len(&self) -> usize {
self.edges.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.edges.is_empty()
}
#[must_use]
pub fn divergence(&self, other: &EdgeSet) -> usize {
self.edges.symmetric_difference(&other.edges).count()
}
#[must_use]
pub fn novel_against(&self, other: &EdgeSet) -> usize {
self.edges.difference(&other.edges).count()
}
#[must_use]
pub fn covers(&self, other: &EdgeSet) -> bool {
other.edges.is_subset(&self.edges)
}
pub fn absorb(&mut self, other: &EdgeSet) {
self.edges.extend(other.edges.iter().copied());
}
#[must_use]
pub fn union_of<'a>(maps: impl IntoIterator<Item = &'a EdgeSet>) -> EdgeSet {
let mut total = EdgeSet::new();
for map in maps {
total.absorb(map);
}
total
}
}
impl FromIterator<u32> for EdgeSet {
fn from_iter<I: IntoIterator<Item = u32>>(iter: I) -> Self {
Self {
edges: iter.into_iter().collect(),
}
}
}
#[must_use]
pub fn parse_showmap(text: &str) -> EdgeSet {
text.lines()
.filter_map(|line| {
let field = line.split(EDGE_FIELD_SEPARATOR).next()?.trim();
field.parse::<u32>().ok()
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
// A real `ar`, built here rather than shelled out for, so the parser is tested against the
// format rather than against whatever `llvm-ar` happened to emit on this machine.
fn archive(members: &[(&str, &[u8])]) -> Vec<u8> {
let mut bytes = AR_MAGIC.to_vec();
for (name, body) in members {
bytes.extend_from_slice(format!("{name:<16}").as_bytes());
bytes.extend_from_slice(format!("{:<12}{:<6}{:<6}{:<8}", 0, 0, 0, 644).as_bytes());
bytes.extend_from_slice(format!("{:<10}", body.len()).as_bytes());
bytes.extend_from_slice(b"\x60\n");
bytes.extend_from_slice(body);
if body.len() % 2 == 1 {
bytes.push(b'\n');
}
}
bytes
}
fn written(name: &str, bytes: &[u8]) -> std::path::PathBuf {
let path = lisdex_core::scratch::path(&format!("coverage-ar-{name}"));
std::fs::write(&path, bytes).expect("fixture");
path
}
// B80. This is the fact under every cross-harness number: a bitcode archive is
// re-instrumented at every link, so two harnesses do not number the same edge the same way.
#[test]
fn an_archive_holding_llvm_bitcode_is_recognised_as_relinked_every_time() {
let path = written(
"lto",
&archive(&[("mylib.o/", b"BC\xc0\xde\x00\x01\x02\x03")]),
);
assert!(is_bitcode_archive(&path));
let _ = std::fs::remove_file(path);
}
// The isolating control: same container, same parser, an ELF member instead. Without this
// a function that simply returned true would pass the test above.
#[test]
fn an_archive_holding_elf_objects_is_not() {
let path = written("elf", &archive(&[("mylib.o/", b"\x7fELF\x02\x01\x01\x00")]));
assert!(!is_bitcode_archive(&path));
let _ = std::fs::remove_file(path);
}
// The symbol table is member ZERO of almost every real archive and never carries the
// magic, so a parser that only ever looked at the first member would call every archive
// an object archive - including libpng16.a, which is bitcode.
#[test]
fn bitcode_behind_a_symbol_table_member_is_still_found() {
let path = written(
"sym",
&archive(&[
("/", b"\x00\x00\x00\x01symbols"),
("mylib.o/", b"BC\xc0\xde\x00\x01\x02\x03"),
]),
);
assert!(is_bitcode_archive(&path));
let _ = std::fs::remove_file(path);
}
// `--archive` is documented as taking an archive, but nothing stops a bare object or a
// shared library, and the renumbering does not care which container the bitcode arrived in.
// Gutting this arm reddened NOTHING until this pair existed.
#[test]
fn a_bare_bitcode_object_outside_any_archive_is_still_recognised() {
let path = written("bare-bc", b"BC\xc0\xde\x00\x01\x02\x03");
assert!(is_bitcode_archive(&path));
let _ = std::fs::remove_file(path);
}
#[test]
fn a_bare_elf_object_outside_any_archive_is_not() {
let path = written("bare-elf", b"\x7fELF\x02\x01\x01\x00");
assert!(!is_bitcode_archive(&path));
let _ = std::fs::remove_file(path);
}
#[test]
fn a_missing_archive_is_not_claimed_to_be_bitcode() {
assert!(!is_bitcode_archive(std::path::Path::new(
"/nonexistent/libnope.a"
)));
}
// B80's remaining half. "Not bitcode" was never the same claim as "the library carries a
// fixed numbering of its own": an uninstrumented archive is neither, and against one the
// only edges in the map belong to the harness, which moves whenever the harness does.
#[test]
fn an_archive_carrying_guard_sections_is_recognised_as_fixed_at_library_build_time() {
let path = written(
"pcg",
&archive(&[(
"mylib.o/",
b"\x7fELF\x02\x01\x01\x00....__sancov_guards....",
)]),
);
assert!(is_pcguard_archive(&path));
assert!(!is_bitcode_archive(&path));
let _ = std::fs::remove_file(path);
}
// The isolating control for the arm above: same container, same walk, an ELF member with
// no guard section. Without this a function returning PcGuard for every non-bitcode
// archive would pass.
#[test]
fn an_uninstrumented_archive_is_neither_bitcode_nor_pcguard() {
let path = written(
"plain",
&archive(&[("mylib.o/", b"\x7fELF\x02\x01\x01\x00")]),
);
assert_eq!(archive_scheme(&path), ArchiveScheme::Opaque);
assert!(!is_pcguard_archive(&path));
assert!(!is_bitcode_archive(&path));
let _ = std::fs::remove_file(path);
}
// A real archive holds many members and the instrumented ones are not first. The guard
// section has to be found behind the symbol table and behind uninstrumented members alike.
#[test]
fn a_guard_section_behind_other_members_is_still_found() {
let path = written(
"pcg-deep",
&archive(&[
("/", b"\x00\x00\x00\x01symbols"),
("empty.o/", b"\x7fELF\x02\x01\x01\x00"),
("mylib.o/", b"\x7fELF\x02\x01\x01\x00..__sancov_guards.."),
]),
);
assert!(is_pcguard_archive(&path));
let _ = std::fs::remove_file(path);
}
// Precedence, and it is not symmetric. A mixed archive still goes through the LTO link that
// renumbers the merged module, so one bitcode member settles it however many guard sections
// the other members carry.
//
// The member ORDER here is the whole control and was found by gutting: with the bitcode
// member last, a walk that merely recorded what it saw instead of returning on it still
// ends on Bitcode and passes. Bitcode FIRST is the arrangement in which only an early
// return survives - anything else is overwritten by the guard section behind it.
#[test]
fn one_bitcode_member_outranks_every_guard_section_behind_it() {
let path = written(
"mixed-bc-first",
&archive(&[
("lto.o/", b"BC\xc0\xde\x00\x01\x02\x03"),
("fast.o/", b"\x7fELF\x02\x01\x01\x00..__sancov_guards.."),
]),
);
assert_eq!(archive_scheme(&path), ArchiveScheme::Bitcode);
assert!(!is_pcguard_archive(&path));
let _ = std::fs::remove_file(path);
}
// The same claim with the members the other way round, because a real archive orders them
// however the build system happened to add them and neither order may be trusted.
#[test]
fn one_bitcode_member_outranks_every_guard_section_ahead_of_it() {
let path = written(
"mixed-bc-last",
&archive(&[
("fast.o/", b"\x7fELF\x02\x01\x01\x00..__sancov_guards.."),
("lto.o/", b"BC\xc0\xde\x00\x01\x02\x03"),
]),
);
assert_eq!(archive_scheme(&path), ArchiveScheme::Bitcode);
assert!(!is_pcguard_archive(&path));
let _ = std::fs::remove_file(path);
}
#[test]
fn a_missing_archive_is_not_claimed_to_be_pcguard_either() {
assert!(!is_pcguard_archive(std::path::Path::new(
"/nonexistent/libnope.a"
)));
}
#[test]
fn parses_edge_ids_and_discards_hit_counts() {
let map = parse_showmap("000123:1\n004567:3\n065535:255\n");
assert_eq!(map.len(), 3);
assert_eq!(map, [123, 4567, 65535].into_iter().collect());
}
#[test]
fn a_differing_hit_count_is_not_a_differing_edge() {
let hot = parse_showmap("42:1\n");
let hotter = parse_showmap("42:250\n");
assert_eq!(hot, hotter);
assert_eq!(hot.divergence(&hotter), 0);
}
#[test]
fn ignores_blank_and_malformed_lines() {
let map = parse_showmap("\n12:1\nnot-an-edge\n\n34:2\n");
assert_eq!(map.len(), 2);
}
#[test]
fn empty_output_is_an_empty_map() {
assert!(parse_showmap("").is_empty());
}
#[test]
fn divergence_counts_both_directions() {
let left: EdgeSet = [1, 2, 3].into_iter().collect();
let right: EdgeSet = [3, 4].into_iter().collect();
assert_eq!(left.divergence(&right), 3);
}
#[test]
fn identical_maps_do_not_diverge() {
let left: EdgeSet = [1, 2, 3].into_iter().collect();
let right: EdgeSet = [3, 2, 1].into_iter().collect();
assert_eq!(left.divergence(&right), 0);
}
#[test]
fn novelty_is_one_directional() {
let candidate: EdgeSet = [1, 2, 9].into_iter().collect();
let accepted: EdgeSet = [1, 2, 3, 4].into_iter().collect();
assert_eq!(candidate.novel_against(&accepted), 1);
assert_eq!(accepted.novel_against(&candidate), 2);
}
#[test]
fn covers_detects_a_superset() {
let wide: EdgeSet = [1, 2, 3, 4].into_iter().collect();
let narrow: EdgeSet = [2, 3].into_iter().collect();
assert!(wide.covers(&narrow));
assert!(!narrow.covers(&wide));
}
#[test]
fn a_map_covers_itself() {
let map: EdgeSet = [7, 8].into_iter().collect();
assert!(map.covers(&map));
}
#[test]
fn union_merges_every_map() {
let first: EdgeSet = [1, 2].into_iter().collect();
let second: EdgeSet = [2, 3].into_iter().collect();
let third: EdgeSet = [9].into_iter().collect();
let total = EdgeSet::union_of([&first, &second, &third]);
assert_eq!(total.len(), 4);
}
#[test]
fn union_of_nothing_is_empty() {
assert!(EdgeSet::union_of([]).is_empty());
}
}