#!/bin/bash

# Copyright 2022 The Centipede Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This sh_test checks the size of the pc table generated by a tiny fuzz target.
# If the pc table is not small, it means some redundant instrumentation
# is applied to the runner library.

set -eu

source "$(dirname "$0")/../test_util.sh"

# Max allowed PC table size is 16 bytes, i.e. one entry.
ALLOWED_SIZE=16

echo "pc table allowed size: ${ALLOWED_SIZE}"

target="$(centipede::get_centipede_test_srcdir)/testing/empty_fuzz_target"
pc_table="${TEST_TMPDIR}/pc_table"
unused1="${TEST_TMPDIR}/unused1"
unused2="${TEST_TMPDIR}/unused2"

# Dump the pc table on disk.
CENTIPEDE_RUNNER_FLAGS=":dump_binary_info:arg1=${pc_table}:arg2=${unused1}:arg3=${unused2}:" \
  "${target}"

# Check the pc table size.
size=$(stat -c %s "${pc_table}")
echo "pc table size: ${size}"
(( size < 1 )) && die "pc table is too small: ${size}"
(( size > ALLOWED_SIZE )) && die "pc table is too large: ${size}"

echo "PASS"
