1#!/bin/bash
2
3set -eu
4
5SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
6
7TARGET=${1:-"rtcp_fuzzer"}
8CRASH_FILE=${2:-""}
9if [[ ! -z "$CRASH_FILE" && "${CRASH_FILE:0:1}" != / && "${CRASH_FILE:0:2}" != ~[/a-z] ]]; then
10	CRASH_FILE="$SCRIPTPATH"/"$CRASH_FILE"
11fi
12HALF_NCORES=$(expr $(nproc) / 2)
13HALF_NCORES=$(($HALF_NCORES > 0 ? $HALF_NCORES : 1))
14JOBS=${JOBS:-${HALF_NCORES}}
15WORKERS=${WORKERS:-${HALF_NCORES}}
16OUT=${OUT:-"$SCRIPTPATH/out"}
17SRC=$(dirname $SCRIPTPATH)
18
19echo "Fuzzer: $TARGET"
20echo "Crash file/folder: $CRASH_FILE"
21echo "Output dir: $OUT"
22
23cd "$OUT"
24
25# Extract the corpus dataset from zipfile
26mkdir -p "$TARGET"_corpus
27mkdir -p "$TARGET"_seed_corpus
28if [ -f "${TARGET}_seed_corpus.zip" ]; then
29	echo "Extracting corpus seed data"
30	unzip -oq "$TARGET"_seed_corpus.zip -d "$TARGET"_seed_corpus
31fi
32
33# Run the target
34# Use -max_len=65535 for network protocols
35# Use -timeout=25 -rss_limit_mb=2048 for time and memory limits
36if [ -z "$CRASH_FILE" ]; then
37	# No crash file supplied, start the fuzzer
38	ASAN_OPTIONS=detect_leaks=1 ./$TARGET -artifact_prefix="./$TARGET-" -print_final_stats=0 -print_corpus_stats=0 -print_coverage=0 -jobs=${JOBS} -workers=${WORKERS} "$TARGET"_corpus "$TARGET"_seed_corpus
39	# tail -f fuzz*.log
40elif [ -f "$CRASH_FILE" ]; then
41	# Run without fuzzing to reproduce a bug with a supplied crash file
42	ASAN_OPTIONS=detect_leaks=1 ./$TARGET $CRASH_FILE
43	# Rerun with GDB to reproduce and debug
44	#ASAN_OPTIONS=abort_on_error=1 gdb --args ./$TARGET $CRASH_FILE
45elif [ -d "$CRASH_FILE" ]; then
46	# Run without fuzzing, with an user supplied crashes folder
47	files=$(find "$CRASH_FILE" -maxdepth 1 -type f)
48	if [[ -z $files ]]; then
49		echo "Empty crashes folder specified!"
50		exit 1
51	fi
52	ASAN_OPTIONS=detect_leaks=1 ./$TARGET $files
53else
54	echo "Invalid crash file/folder specified!"
55	exit 1
56fi
57
58# Run without fuzzing, using the extracted corpus dataset (regression testing)
59# Use -max_len=65535 for network protocols
60# Use -timeout=25 -rss_limit_mb=2048 for time and memory limits
61# ASAN_OPTIONS=detect_leaks=1 ./$TARGET "$TARGET"_seed_corpus/*
62
63# Run the target for coverage testing
64# NAME="$TARGET".$(date +%s)
65# LLVM_PROFILE_FILE="$NAME".profraw ./$TARGET "$TARGET"_seed_corpus/*
66# llvm-profdata merge -sparse "$NAME".profraw -o "$NAME".profdata
67# llvm-cov show "$TARGET" -instr-profile="$NAME".profdata "$SRC"/rtcp.c "$SRC"/rtp.c "$SRC"/utils.c -use-color -format=html > "$NAME".html
68
69# dump crashing pattern
70# hexdump -C "$CRASH_FILE"
71
72# Convert to pcap
73# od -Ax -tx1 -v "$CRASH_FILE" > "$CRASH_FILE".hex
74# text2pcap -u1000,2000 "$CRASH_FILE".hex "$CRASH_FILE".pcap
75
76