#!/bin/bash
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
set -e

cd deps

source versions

# clean up old files
rm -f aws-lambda-cpp-*.tar.gz && rm -f curl-*.tar.gz

# Grab Curl
wget -c https://github.com/curl/curl/archive/refs/tags/curl-$CURL_VERSION.tar.gz -O - | tar -xz

# Apply patches
(
  cd curl-curl-$CURL_VERSION && \
    patch -p1 < ../patches/0001-curl-disable_wakeup.patch
)

# Pack again and remove the folder
tar -czvf curl-$CURL_VERSION.tar.gz curl-curl-$CURL_VERSION && \
  rm -rf curl-curl-$CURL_VERSION

# Grab aws-lambda-cpp
wget -c https://github.com/awslabs/aws-lambda-cpp/archive/refs/tags/v$AWS_LAMBDA_CPP_RELEASE.tar.gz -O - | tar -xz

# Apply patches
(
  cd aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE && \
    patch -p1 < ../patches/aws-lambda-cpp-add-xray-response.patch
)

# Pack again and remove the folder
tar -czvf aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE.tar.gz aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE --no-same-owner && \
  rm -rf aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE


#!/bin/bash
# This file is copied from https://github.com/aws/aws-codebuild-docker-images/blob/f0912e4b16e427da35351fc102f0f56f4ceb938a/local_builds/codebuild_build.sh

function allOSRealPath() {
    if isOSWindows
    then
        path=""
        case $1 in
            .* ) path="$PWD/${1#./}" ;;
            /* ) path="$1" ;;
            *  ) path="/$1" ;;
        esac

        echo "/$path" | sed -e 's/\\/\//g' -e 's/://' -e 's/./\U&/3'
    else
        case $1 in
            /* ) echo "$1"; exit;;
            *  ) echo "$PWD/${1#./}"; exit;;
        esac
    fi
}

function isOSWindows() {
    if [ $OSTYPE == "msys" ]
    then
        return 0
    else
        return 1
    fi
}

function usage {
    echo "usage: codebuild_build.sh [-i image_name] [-a artifact_output_directory] [options]"
    echo "Required:"
    echo "  -i        Used to specify the customer build container image."
    echo "  -a        Used to specify an artifact output directory."
    echo "Options:"
    echo "  -l IMAGE  Used to override the default local agent image."
    echo "  -s        Used to specify source information. Defaults to the current working directory for primary source."
    echo "               * First (-s) is for primary source"
    echo "               * Use additional (-s) in <sourceIdentifier>:<sourceLocation> format for secondary source"
    echo "               * For sourceIdentifier, use a value that is fewer than 128 characters and contains only alphanumeric characters and underscores"
    echo "  -c        Use the AWS configuration and credentials from your local host. This includes ~/.aws and any AWS_* environment variables."
    echo "  -p        Used to specify the AWS CLI Profile."
    echo "  -b FILE   Used to specify a buildspec override file. Defaults to buildspec.yml in the source directory."
    echo "  -m        Used to mount the source directory to the customer build container directly."
    echo "  -d        Used to run the build container in docker privileged mode."
    echo "  -e FILE   Used to specify a file containing environment variables."
    echo "            (-e) File format expectations:"
    echo "               * Each line is in VAR=VAL format"
    echo "               * Lines beginning with # are processed as comments and ignored"
    echo "               * Blank lines are ignored"
    echo "               * File can be of type .env or .txt"
    echo "               * There is no special handling of quotation marks, meaning they will be part of the VAL"
    exit 1
}

image_flag=false
artifact_flag=false
awsconfig_flag=false
mount_src_dir_flag=false
docker_privileged_mode_flag=false

while getopts "cmdi:a:s:b:e:l:p:h" opt; do
    case $opt in
        i  ) image_flag=true; image_name=$OPTARG;;
        a  ) artifact_flag=true; artifact_dir=$OPTARG;;
        b  ) buildspec=$OPTARG;;
        c  ) awsconfig_flag=true;;
        m  ) mount_src_dir_flag=true;;
        d  ) docker_privileged_mode_flag=true;;
        s  ) source_dirs+=("$OPTARG");;
        e  ) environment_variable_file=$OPTARG;;
        l  ) local_agent_image=$OPTARG;;
        p  ) aws_profile=$OPTARG;;
        h  ) usage; exit;;
        \? ) echo "Unknown option: -$OPTARG" >&2; exit 1;;
        :  ) echo "Missing option argument for -$OPTARG" >&2; exit 1;;
        *  ) echo "Invalid option: -$OPTARG" >&2; exit 1;;
    esac
done

if  ! $image_flag
then
    echo "The image name flag (-i) must be included for a build to run" >&2
fi

if  ! $artifact_flag
then
    echo "The artifact directory (-a) must be included for a build to run" >&2
fi

if  ! $image_flag ||  ! $artifact_flag
then
    exit 1
fi

docker_command="docker run "
if isOSWindows
then
    docker_command+="-v //var/run/docker.sock:/var/run/docker.sock -e "
else
    docker_command+="-v /var/run/docker.sock:/var/run/docker.sock -e "
fi

docker_command+="\"IMAGE_NAME=$image_name\" -e \
    \"ARTIFACTS=$(allOSRealPath "$artifact_dir")\""

if [ -z "$source_dirs" ]
then
    docker_command+=" -e \"SOURCE=$(allOSRealPath "$PWD")\""
else
    for index in "${!source_dirs[@]}"; do
        if [ $index -eq 0 ]
        then
            docker_command+=" -e \"SOURCE=$(allOSRealPath "${source_dirs[$index]}")\""
        else
            identifier=${source_dirs[$index]%%:*}
            src_dir=$(allOSRealPath "${source_dirs[$index]#*:}")

            docker_command+=" -e \"SECONDARY_SOURCE_$index=$identifier:$src_dir\""
        fi
    done
fi

if [ -n "$buildspec" ]
then
    docker_command+=" -e \"BUILDSPEC=$(allOSRealPath "$buildspec")\""
fi

if [ -n "$environment_variable_file" ]
then
    environment_variable_file_path=$(allOSRealPath "$environment_variable_file")
    environment_variable_file_dir=$(dirname "$environment_variable_file_path")
    environment_variable_file_basename=$(basename "$environment_variable_file")
    docker_command+=" -v \"$environment_variable_file_dir:/LocalBuild/envFile/\" -e \"ENV_VAR_FILE=$environment_variable_file_basename\""
fi

if [ -n "$local_agent_image" ]
then
    docker_command+=" -e \"LOCAL_AGENT_IMAGE_NAME=$local_agent_image\""
fi

if $awsconfig_flag
then
    if [ -d "$HOME/.aws" ]
    then
        configuration_file_path=$(allOSRealPath "$HOME/.aws")
        docker_command+=" -e \"AWS_CONFIGURATION=$configuration_file_path\""
    else
        docker_command+=" -e \"AWS_CONFIGURATION=NONE\""
    fi

    if [ -n "$aws_profile" ]
    then
        docker_command+=" -e \"AWS_PROFILE=$aws_profile\""
    fi

    docker_command+="$(env | grep ^AWS_ | while read -r line; do echo " -e \"$line\""; done )"
fi

if $mount_src_dir_flag
then
    docker_command+=" -e \"MOUNT_SOURCE_DIRECTORY=TRUE\""
fi

if $docker_privileged_mode_flag
then
    docker_command+=" -e \"DOCKER_PRIVILEGED_MODE=TRUE\""
fi

if isOSWindows
then
    docker_command+=" -e \"INITIATOR=$USERNAME\""
else
    docker_command+=" -e \"INITIATOR=$USER\""
fi

docker_command+=" amazon/aws-codebuild-local:latest"

# Note we do not expose the AWS_SECRET_ACCESS_KEY or the AWS_SESSION_TOKEN
exposed_command=$docker_command
secure_variables=( "AWS_SECRET_ACCESS_KEY=" "AWS_SESSION_TOKEN=")
for variable in "${secure_variables[@]}"
do
    exposed_command="$(echo $exposed_command | sed "s/\($variable\)[^ ]*/\1********\"/")"
done

echo "Build Command:"
echo ""
echo $exposed_command
echo ""

eval $docker_command


#!/bin/bash
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.

set -euo pipefail

CODEBUILD_IMAGE_TAG="${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}"
DISTRO="${DISTRO:=""}"
DRYRUN="${DRYRUN-0}"

function usage {
    echo "usage: test_all.sh buildspec_yml_dir"
    echo "Runs all buildspec build-matrix combinations via test_one.sh."
    echo "Required:"
    echo "  buildspec_yml_dir      Used to specify the CodeBuild buildspec template file."
}

do_one_yaml() {
    local -r YML="$1"

    OS_DISTRIBUTION=$(grep -oE 'OS_DISTRIBUTION:\s*(\S+)' "$YML" | cut -d' ' -f2)
    DISTRO_VERSIONS=$(sed '1,/DISTRO_VERSION/d;/RUNTIME_VERSION/,$d' "$YML" | tr -d '\-" ')
    RUNTIME_VERSIONS=$(sed '1,/RUNTIME_VERSION/d;/phases/,$d' "$YML" | sed '/#.*$/d' |  tr -d '\-" ')

    for DISTRO_VERSION in $DISTRO_VERSIONS ; do
        for RUNTIME_VERSION in $RUNTIME_VERSIONS ; do
            if (( DRYRUN == 1 )) ; then
                echo DRYRUN test_one_combination "$YML" "$OS_DISTRIBUTION" "$DISTRO_VERSION" "$RUNTIME_VERSION"
            else
                test_one_combination "$YML" "$OS_DISTRIBUTION" "$DISTRO_VERSION" "$RUNTIME_VERSION"
            fi
        done
    done
}

test_one_combination() {
    local -r YML="$1"
    local -r OS_DISTRIBUTION="$2"
    local -r DISTRO_VERSION="$3"
    local -r RUNTIME_VERSION="$4"

    echo Testing:
    echo "  BUILDSPEC" "$YML"
    echo "  with" "$OS_DISTRIBUTION"-"$DISTRO_VERSION" "$RUNTIME_VERSION"

    "$(dirname "$0")"/test_one.sh "$YML" "$OS_DISTRIBUTION" "$DISTRO_VERSION" "$RUNTIME_VERSION" \
        > >(sed "s/^/$OS_DISTRIBUTION$DISTRO_VERSION-$RUNTIME_VERSION: /") 2> >(sed "s/^/$OS_DISTRIBUTION-$DISTRO_VERSION:$RUNTIME_VERSION: /" >&2)
}

main() {
    if (( $# != 1 && $# != 2)); then
        >&2 echo "Invalid number of parameters."
        usage
        exit 1
    fi

    BUILDSPEC_YML_DIR="$1"
    HAS_YML=0
    for f in "$BUILDSPEC_YML_DIR"/*"$DISTRO"*.yml ; do
        [ -f "$f" ] || continue;
        do_one_yaml "$f"
        HAS_YML=1
    done

    if (( HAS_YML == 0 )); then
        >&2 echo At least one buildspec is required.
        exit 2
    fi
}

main "$@"


#!/bin/bash
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.

set -euo pipefail

CODEBUILD_IMAGE_TAG="${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}"

function usage {
    >&2 echo "usage: test_one.sh buildspec_yml os_distribution distro_version runtime_version [env]"
    >&2 echo "Runs one buildspec version combination from a build-matrix buildspec."
    >&2 echo "Required:"
    >&2 echo "  buildspec_yml          Used to specify the CodeBuild buildspec template file."
    >&2 echo "  os_distribution        Used to specify the OS distribution to build."
    >&2 echo "  distro_version         Used to specify the distro version of <os_distribution>."
    >&2 echo "  runtime_version        Used to specify the runtime version to test on the selected <distro_version>."
    >&2 echo "Optional:"
    >&2 echo "  env                    Additional environment variables file."
}

main() {
    if (( $# != 3 && $# != 4)); then
        >&2 echo "Invalid number of parameters."
        usage
        exit 1
    fi

    BUILDSPEC_YML="$1"
    OS_DISTRIBUTION="$2"
    DISTRO_VERSION="$3"
    RUNTIME_VERSION="$4"
    EXTRA_ENV="${5-}"

    CODEBUILD_TEMP_DIR=$(mktemp -d codebuild."$OS_DISTRIBUTION"-"$DISTRO_VERSION"-"$RUNTIME_VERSION".XXXXXXXXXX)
    trap 'rm -rf $CODEBUILD_TEMP_DIR' EXIT

    # Create an env file for codebuild_build.
    ENVFILE="$CODEBUILD_TEMP_DIR/.env"
    if [ -f "$EXTRA_ENV" ]; then
        cat "$EXTRA_ENV" > "$ENVFILE"
    fi
    {
        echo ""
        echo "OS_DISTRIBUTION=$OS_DISTRIBUTION"
        echo "DISTRO_VERSION=$DISTRO_VERSION"
        echo "RUNTIME_VERSION=$RUNTIME_VERSION"
    }  >> "$ENVFILE"

    ARTIFACTS_DIR="$CODEBUILD_TEMP_DIR/artifacts"
    mkdir -p "$ARTIFACTS_DIR"

    # Run CodeBuild local agent.
    "$(dirname "$0")"/codebuild_build.sh \
        -i "$CODEBUILD_IMAGE_TAG" \
        -a "$ARTIFACTS_DIR" \
        -e "$ENVFILE" \
        -b "$BUILDSPEC_YML"
}

main "$@"


#!/bin/sh
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
set -e

ARTIFACTS_DIR=$(pwd)/deps/artifacts

if [ "$(uname)" = "Darwin" ]; then
    echo "aws-lambda-cpp does not build on OS X. Skipping the preinstall step."
else
    if [ -x "$(command -v cmake3)" ]; then
        CMAKE=cmake3
    elif [ -x "$(command -v cmake)" ]; then
        CMAKE=cmake
    else
        echo 'Error: cmake is not installed.' >&2
        exit 1
    fi

    cd deps
    . ./versions

    CURL_VERSION="${CURL_MAJOR_VERSION}.${CURL_MINOR_VERSION}.${CURL_PATCH_VERSION}"

    rm -rf ./curl-$CURL_VERSION
    rm -rf ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE

    # unpack dependencies
    tar xzf ./curl-$CURL_VERSION.tar.gz --no-same-owner && \
    tar xzf ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE.tar.gz --no-same-owner

    (
        # Build Curl
        cd curl-$CURL_VERSION && \
            ./buildconf && \
            ./configure \
                --prefix "$ARTIFACTS_DIR" \
                --disable-shared \
                --without-ssl \
                --with-pic \
                --without-zlib && \
            make && \
            make install
    )

    (
        # Build aws-lambda-cpp
        mkdir -p ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE/build && \
            cd ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE/build

        $CMAKE .. \
                -DCMAKE_CXX_FLAGS="-fPIC" \
                -DCMAKE_INSTALL_PREFIX="$ARTIFACTS_DIR" \
                -DENABLE_LTO=$ENABLE_LTO \
                -DCMAKE_MODULE_PATH="$ARTIFACTS_DIR"/lib/pkgconfig && \
            make && make install
    )
fi


#!/bin/bash
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
set -e

cd deps
source versions

# Clean up old files
rm -f aws-lambda-cpp-*.tar.gz && rm -f curl-*.tar.gz

# Grab Curl
wget -c "https://github.com/curl/curl/releases/download/curl-${CURL_MAJOR_VERSION}_${CURL_MINOR_VERSION}_${CURL_PATCH_VERSION}/curl-${CURL_MAJOR_VERSION}.${CURL_MINOR_VERSION}.${CURL_PATCH_VERSION}.tar.gz"

# Grab aws-lambda-cpp
wget -c https://github.com/awslabs/aws-lambda-cpp/archive/v$AWS_LAMBDA_CPP_RELEASE.tar.gz -O - | tar -xz

## Apply patches to aws-lambda-cpp
(
  cd aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE && \
    patch -p1 < ../patches/aws-lambda-cpp-add-xray-response.patch && \
    patch -p1 < ../patches/aws-lambda-cpp-posting-init-errors.patch && \
    patch -p1 < ../patches/aws-lambda-cpp-make-the-runtime-client-user-agent-overrideable.patch && \
    patch -p1 < ../patches/aws-lambda-cpp-make-lto-optional.patch && \
    patch -p1 < ../patches/aws-lambda-cpp-add-content-type.patch
)

## Pack again and remove the folder
tar -czvf aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE.tar.gz aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE --no-same-owner && \
  rm -rf aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE


#!/bin/bash
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.

set -euo pipefail

CODEBUILD_IMAGE_TAG="${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}"
DRYRUN="${DRYRUN-0}"

function usage {
    echo "usage: test_all.sh buildspec_yml_dir"
    echo "Runs all buildspec build-matrix combinations via test_one.sh."
    echo "Required:"
    echo "  buildspec_yml_dir      Used to specify the CodeBuild buildspec template file."
}

do_one_yaml() {
    local -r YML="$1"

    OS_DISTRIBUTION=$(grep -oE 'OS_DISTRIBUTION:\s*(\S+)' "$YML" | cut -d' ' -f2)
    DISTRO_VERSIONS=$(sed '1,/DISTRO_VERSION/d;/RUNTIME_VERSION/,$d' "$YML" | tr -d '\-" ')
    RUNTIME_VERSIONS=$(sed '1,/RUNTIME_VERSION/d;/phases/,$d' "$YML" | sed '/#.*$/d' |  tr -d '\-" ')

    for DISTRO_VERSION in $DISTRO_VERSIONS ; do
        for RUNTIME_VERSION in $RUNTIME_VERSIONS ; do
            if (( DRYRUN == 1 )) ; then
                echo DRYRUN test_one_combination "$YML" "$OS_DISTRIBUTION" "$DISTRO_VERSION" "$RUNTIME_VERSION"
            else
                test_one_combination "$YML" "$OS_DISTRIBUTION" "$DISTRO_VERSION" "$RUNTIME_VERSION"
            fi
        done
    done
}

test_one_combination() {
    local -r YML="$1"
    local -r OS_DISTRIBUTION="$2"
    local -r DISTRO_VERSION="$3"
    local -r RUNTIME_VERSION="$4"

    echo Testing:
    echo "  BUILDSPEC" "$YML"
    echo "  with" "$OS_DISTRIBUTION"-"$DISTRO_VERSION" "$RUNTIME_VERSION"

    "$(dirname "$0")"/test_one.sh "$YML" "$OS_DISTRIBUTION" "$DISTRO_VERSION" "$RUNTIME_VERSION" \
        > >(sed "s/^/$OS_DISTRIBUTION$DISTRO_VERSION-$RUNTIME_VERSION: /") 2> >(sed "s/^/$OS_DISTRIBUTION-$DISTRO_VERSION:$RUNTIME_VERSION: /" >&2)
}

main() {
    if (( $# != 1 && $# != 2)); then
        >&2 echo "Invalid number of parameters."
        usage
        exit 1
    fi

    BUILDSPEC_YML_DIR="$1"
    HAS_YML=0
    for f in "$BUILDSPEC_YML_DIR"/*.yml ; do
        [ -f "$f" ] || continue;
        do_one_yaml "$f"
        HAS_YML=1
    done

    if (( HAS_YML == 0 )); then
        >&2 echo At least one buildspec is required.
        exit 2
    fi
}

main "$@"


#!/bin/bash
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.

set -euo pipefail

CODEBUILD_IMAGE_TAG="${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}"

function usage {
    >&2 echo "usage: test_one.sh buildspec_yml os_distribution distro_version runtime_version [env]"
    >&2 echo "Runs one buildspec version combination from a build-matrix buildspec."
    >&2 echo "Required:"
    >&2 echo "  buildspec_yml          Used to specify the CodeBuild buildspec template file."
    >&2 echo "  os_distribution        Used to specify the OS distribution to build."
    >&2 echo "  distro_version         Used to specify the distro version of <os_distribution>."
    >&2 echo "  runtime_version        Used to specify the runtime version to test on the selected <distro_version>."
    >&2 echo "Optional:"
    >&2 echo "  env                    Additional environment variables file."
}

main() {
    if (( $# != 3 && $# != 4)); then
        >&2 echo "Invalid number of parameters."
        usage
        exit 1
    fi

    set -x
    BUILDSPEC_YML="$1"
    OS_DISTRIBUTION="$2"
    DISTRO_VERSION="$3"
    RUNTIME_VERSION="$4"
    EXTRA_ENV="${5-}"

    CODEBUILD_TEMP_DIR=$(mktemp -d codebuild."$OS_DISTRIBUTION"-"$DISTRO_VERSION"-"$RUNTIME_VERSION".XXXXXXXXXX)
    trap 'rm -rf $CODEBUILD_TEMP_DIR' EXIT

    # Create an env file for codebuild_build.
    ENVFILE="$CODEBUILD_TEMP_DIR/.env"
    if [ -f "$EXTRA_ENV" ]; then
        cat "$EXTRA_ENV" > "$ENVFILE"
    fi
    {
        echo ""
        echo "OS_DISTRIBUTION=$OS_DISTRIBUTION"
        echo "DISTRO_VERSION=$DISTRO_VERSION"
        echo "RUNTIME_VERSION=$RUNTIME_VERSION"
    }  >> "$ENVFILE"

    ARTIFACTS_DIR="$CODEBUILD_TEMP_DIR/artifacts"
    mkdir -p "$ARTIFACTS_DIR"

    # Run CodeBuild local agent.
    "$(dirname "$0")"/codebuild_build.sh \
        -i "$CODEBUILD_IMAGE_TAG" \
        -a "$ARTIFACTS_DIR" \
        -e "$ENVFILE" \
        -b "$BUILDSPEC_YML"
}

main "$@"


#!/bin/bash
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.

set -euo pipefail

CODEBUILD_IMAGE_TAG="${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}"

function usage {
    >&2 echo "usage: test_one.sh buildspec_yml os_distribution distro_version runtime_version [env]"
    >&2 echo "Runs one buildspec version combination from a build-matrix buildspec."
    >&2 echo "Required:"
    >&2 echo "  buildspec_yml          Used to specify the CodeBuild buildspec template file."
    >&2 echo "  os_distribution        Used to specify the OS distribution to build."
    >&2 echo "  distro_version         Used to specify the distro version of <os_distribution>."
    >&2 echo "  runtime_version        Used to specify the runtime version to test on the selected <distro_version>."
    >&2 echo "Optional:"
    >&2 echo "  env                    Additional environment variables file."
}

main() {
    if (( $# != 3 && $# != 4)); then
        >&2 echo "Invalid number of parameters."
        usage
        exit 1
    fi

    BUILDSPEC_YML="$1"
    OS_DISTRIBUTION="$2"
    DISTRO_VERSION="$3"
    RUNTIME_VERSION="$4"
    EXTRA_ENV="${5-}"

    CODEBUILD_TEMP_DIR=$(mktemp -d codebuild."$OS_DISTRIBUTION"-"$DISTRO_VERSION"-"$RUNTIME_VERSION".XXXXXXXXXX )
    trap 'rm -rf $CODEBUILD_TEMP_DIR' EXIT

    # Create an env file for codebuild_build.
    ENVFILE="$CODEBUILD_TEMP_DIR/.env"
    if [ -f "$EXTRA_ENV" ]; then
        cat "$EXTRA_ENV" > "$ENVFILE"
    fi
    {
        echo ""
        echo "OS_DISTRIBUTION=$OS_DISTRIBUTION"
        echo "DISTRO_VERSION=$DISTRO_VERSION"
        echo "RUNTIME_VERSION=$RUNTIME_VERSION"
    }  >> "$ENVFILE"

    ARTIFACTS_DIR="$CODEBUILD_TEMP_DIR/artifacts"
    mkdir -p "$ARTIFACTS_DIR"

    # Run CodeBuild local agent.
    "$(dirname "$0")"/codebuild_build.sh \
        -i "$CODEBUILD_IMAGE_TAG" \
        -a "$ARTIFACTS_DIR" \
        -e "$ENVFILE" \
        -b "$BUILDSPEC_YML"
}

main "$@"


function handler () {
  EVENT_DATA=$1
  echo "$EVENT_DATA" 1>&2;
  RESPONSE="Echoing request: '$EVENT_DATA'"

  echo $RESPONSE
}


#!/bin/sh

set -euo pipefail

# Initialization - load function handler
source $LAMBDA_TASK_ROOT/"bash_function.sh"

# Processing
while true
do
  HEADERS="$(mktemp)"
  # Get an event
  EVENT_DATA=$(curl -sS -LD "$HEADERS" -X GET "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next")
  REQUEST_ID=$(grep -Fi Lambda-Runtime-Aws-Request-Id "$HEADERS" | tr -d '[:space:]' | cut -d: -f2)

  # Execute the handler function from the script
  FN_PATH=$LAMBDA_TASK_ROOT/"bash_function.sh"
  RESPONSE=$($FN_PATH "$EVENT_DATA")

  # Send the response
  curl -X POST "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/$REQUEST_ID/response"  -d "response_from_runtime"
done


#!/bin/sh

# Spawn one child process recursively and spin
# When parent process receives a SIGTERM, child process doesn't exit

if [ -z "$DONT_SPAWN" ]
then
    DONT_SPAWN=true ./$0 &
fi

while true
do
  sleep 1
done


#!/bin/sh

set -xe

go run make_legacy_aead_tests.go -cipher aes128 -mac sha1 > aes_128_cbc_sha1_tls_tests.txt
go run make_legacy_aead_tests.go -cipher aes128 -mac sha1 -implicit-iv > aes_128_cbc_sha1_tls_implicit_iv_tests.txt

go run make_legacy_aead_tests.go -cipher aes128 -mac sha256 > aes_128_cbc_sha256_tls_tests.txt
go run make_legacy_aead_tests.go -cipher aes128 -mac sha256 -implicit-iv > aes_128_cbc_sha256_tls_implicit_iv_tests.txt

go run make_legacy_aead_tests.go -cipher aes256 -mac sha1 > aes_256_cbc_sha1_tls_tests.txt
go run make_legacy_aead_tests.go -cipher aes256 -mac sha1 -implicit-iv > aes_256_cbc_sha1_tls_implicit_iv_tests.txt

go run make_legacy_aead_tests.go -cipher 3des -mac sha1 > des_ede3_cbc_sha1_tls_tests.txt
go run make_legacy_aead_tests.go -cipher 3des -mac sha1 -implicit-iv > des_ede3_cbc_sha1_tls_implicit_iv_tests.txt

go run make_legacy_aead_tests.go -cipher aes128 -mac sha1 -stitch > aes_128_cbc_sha1_tls_stitch_tests.txt
go run make_legacy_aead_tests.go -cipher aes128 -mac sha1 -implicit-iv -stitch > aes_128_cbc_sha1_tls_stitch_implicit_iv_tests.txt

go run make_legacy_aead_tests.go -cipher aes128 -mac sha256 -stitch > aes_128_cbc_sha256_tls_stitch_tests.txt
go run make_legacy_aead_tests.go -cipher aes128 -mac sha256 -implicit-iv -stitch > aes_128_cbc_sha256_tls_stitch_implicit_iv_tests.txt

go run make_legacy_aead_tests.go -cipher aes256 -mac sha1 -stitch > aes_256_cbc_sha1_tls_stitch_tests.txt
go run make_legacy_aead_tests.go -cipher aes256 -mac sha1 -implicit-iv -stitch > aes_256_cbc_sha1_tls_stitch_implicit_iv_tests.txt

go run make_legacy_aead_tests.go -cipher aes256 -mac sha256 -stitch > aes_256_cbc_sha256_tls_stitch_tests.txt
go run make_legacy_aead_tests.go -cipher aes256 -mac sha256 -implicit-iv -stitch > aes_256_cbc_sha256_tls_stitch_implicit_iv_tests.txt


#!/bin/bash
# Copyright (c) 2016, Google Inc.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

set -e

buildDir=../build
if [ $# -gt 0 ]; then
  buildDir=$1
fi

for testSource in $(ls -1 *.cc); do
  test=$(echo $testSource | sed -e 's/\.cc$//')
  if [ ! -x $buildDir/fuzz/$test ] ; then
    echo "Failed to find binary for $test"
    exit 1
  fi
  if [ ! -d ${test}_corpus ]; then
    echo "Failed to find corpus directory for $test"
    exit 1
  fi
  if [ -d ${test}_corpus_old ]; then
    echo "Old corpus directory for $test already exists"
    exit 1
  fi
done

for testSource in $(ls -1 *.cc); do
  test=$(echo $testSource | sed -e 's/\.cc$//')
  mv ${test}_corpus ${test}_corpus_old
  mkdir ${test}_corpus
  $buildDir/fuzz/$test -max_len=50000 -merge=1 ${test}_corpus ${test}_corpus_old
  rm -Rf ${test}_corpus_old
done


#!/bin/bash
# Copyright (c) 2016, Google Inc.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

set -ex

if [[ $# -ne 2 ]]; then
  echo "Usage: $0 fuzzer_mode_build_dir no_fuzzer_mode_build_dir"
  exit 1
fi

fuzzer_mode_build_dir=$1
no_fuzzer_mode_build_dir=$2

# Sanity-check the build directories.

if ! grep -q '^FUZZ:' "$fuzzer_mode_build_dir/CMakeCache.txt"; then
  echo "$fuzzer_mode_build_dir was not built with -DFUZZ=1"
  exit 1
fi

if grep -q '^NO_FUZZER_MODE:' "$fuzzer_mode_build_dir/CMakeCache.txt"; then
  echo "$fuzzer_mode_build_dir was built with -DNO_FUZZER_MODE=1"
  exit 1
fi

if ! grep -q '^FUZZ:' "$no_fuzzer_mode_build_dir/CMakeCache.txt"; then
  echo "$no_fuzzer_mode_build_dir was not built with -DFUZZ=1"
  exit 1
fi

if ! grep -q '^NO_FUZZER_MODE:' "$no_fuzzer_mode_build_dir/CMakeCache.txt"; then
  echo "$no_fuzzer_mode_build_dir was not built with -DNO_FUZZER_MODE=1"
  exit 1
fi

# Sanity-check the current working directory.

assert_directory() {
  if [[ ! -d $1 ]]; then
    echo "$1 not found."
    exit 1
  fi
}

assert_directory client_corpus
assert_directory client_corpus_no_fuzzer_mode
assert_directory server_corpus
assert_directory server_corpus_no_fuzzer_mode
assert_directory dtls_client_corpus
assert_directory dtls_server_corpus

# Gather new transcripts. Ignore errors in running the tests.

fuzzer_mode_shim=$(readlink -f "$fuzzer_mode_build_dir/ssl/test/bssl_shim")
no_fuzzer_mode_shim=$(readlink -f \
    "$no_fuzzer_mode_build_dir/ssl/test/bssl_shim")

fuzzer_mode_handshaker=$(readlink -f \
    "$fuzzer_mode_build_dir/ssl/test/handshaker")
no_fuzzer_mode_handshaker=$(readlink -f \
    "$no_fuzzer_mode_build_dir/ssl/test/handshaker")

fuzzer_mode_transcripts=$(mktemp -d '/tmp/boringssl-transcript-fuzzer-mode.XXXXXX')
no_fuzzer_mode_transcripts=$(mktemp -d '/tmp/boringssl-transcript-no-fuzzer-mode.XXXXXX')

echo Recording fuzzer-mode transcripts
(cd ../ssl/test/runner/ && go test \
    -shim-path "$fuzzer_mode_shim" \
    -handshaker-path "$fuzzer_mode_handshaker" \
    -transcript-dir "$fuzzer_mode_transcripts" \
    -fuzzer \
    -deterministic) || true

echo Recording non-fuzzer-mode transcripts
(cd ../ssl/test/runner/ && go test \
    -shim-path "$no_fuzzer_mode_shim" \
    -handshaker-path "$no_fuzzer_mode_handshaker" \
    -transcript-dir "$no_fuzzer_mode_transcripts" \
    -deterministic)

# Minimize the existing corpora.

minimize_corpus() {
  local fuzzer="$1"
  local corpus="$2"

  echo "Minimizing ${corpus}"
  mv "$corpus" "${corpus}_old"
  mkdir "$corpus"
  "$fuzzer" -max_len=50000 -merge=1 "$corpus" "${corpus}_old"
  rm -Rf "${corpus}_old"
}

minimize_corpus "$fuzzer_mode_build_dir/fuzz/client" client_corpus
minimize_corpus "$fuzzer_mode_build_dir/fuzz/server" server_corpus
minimize_corpus "$no_fuzzer_mode_build_dir/fuzz/client" client_corpus_no_fuzzer_mode
minimize_corpus "$no_fuzzer_mode_build_dir/fuzz/server" server_corpus_no_fuzzer_mode
minimize_corpus "$fuzzer_mode_build_dir/fuzz/dtls_client" dtls_client_corpus
minimize_corpus "$fuzzer_mode_build_dir/fuzz/dtls_server" dtls_server_corpus
minimize_corpus "$fuzzer_mode_build_dir/fuzz/decode_client_hello_inner" decode_client_hello_inner_corpus

# Incorporate the new transcripts.

"$fuzzer_mode_build_dir/fuzz/client" -max_len=50000 -merge=1 client_corpus "${fuzzer_mode_transcripts}/tls/client"
"$fuzzer_mode_build_dir/fuzz/server" -max_len=50000 -merge=1 server_corpus "${fuzzer_mode_transcripts}/tls/server"
"$no_fuzzer_mode_build_dir/fuzz/client" -max_len=50000 -merge=1 client_corpus_no_fuzzer_mode "${no_fuzzer_mode_transcripts}/tls/client"
"$no_fuzzer_mode_build_dir/fuzz/server" -max_len=50000 -merge=1 server_corpus_no_fuzzer_mode "${no_fuzzer_mode_transcripts}/tls/server"
"$fuzzer_mode_build_dir/fuzz/dtls_client" -max_len=50000 -merge=1 dtls_client_corpus "${fuzzer_mode_transcripts}/dtls/client"
"$fuzzer_mode_build_dir/fuzz/dtls_server" -max_len=50000 -merge=1 dtls_server_corpus "${fuzzer_mode_transcripts}/dtls/server"
"$fuzzer_mode_build_dir/fuzz/decode_client_hello_inner" -max_len=50000 -merge=1 decode_client_hello_inner_corpus "${fuzzer_mode_transcripts}/decode_client_hello_inner"


#!/bin/bash -ex
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

# Take current contents of generated-src and move to another directory
mv ./generated-src ./generated-src-bak

# Regenerate contents of generated-src
python3 ./util/generate_build_files.py

# Check whether or not
if [[ $(diff -qr ./generated-src ./generated-src-bak) ]]; then
    echo "Contents of generated-src are not up-to-date."
    exit 1;
fi

echo "Contents of generated-src are up-to-date."


#!/bin/bash -ex
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

echo "Running objects.go to update files"
pushd crypto/obj
go run objects.go
popd

echo "Adding all changed files to the git tree"
git add -A

echo "Checking for any changes"
git diff --exit-code HEAD

echo "Running make_errors.go to update files"
go run ./util/make_errors.go ssl evp ocsp pem

echo "Adding all changed files to the git tree"
git add -A

echo "Checking for any changes"
git diff --exit-code HEAD


#!/bin/bash
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

set -x

# set default value of directory name
if [ -z "${PR_FOLDER_NAME}" ]; then export PR_FOLDER_NAME=aws-lc; fi

# Get AWS_ACCOUNT_ID
if [ -z "${AWS_ACCOUNT_ID}" ]; then AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text); fi

AWSLC_PR_ROOT=$(pwd)

cd ..

# run this from the bm_framework root directory!
AWSLC_PR_ROOT=$(pwd)/"${PR_FOLDER_NAME}"
AWSLC_PROD_ROOT=$(pwd)/aws-lc-prod

source ${AWSLC_PR_ROOT}/tests/ci/common_posix_setup.sh

# clone the various repositories we need (we already have aws-lc-pr since we need it to run this script)
git clone https://github.com/aws/aws-lc.git aws-lc-prod

# build AWSLC pr
mkdir -p "${PR_FOLDER_NAME}"/build
${CMAKE_COMMAND} -B"${PR_FOLDER_NAME}"/build -H"${PR_FOLDER_NAME}" -GNinja -DCMAKE_BUILD_TYPE=Release \
  -DBUILD_TESTING=OFF
ninja -C "${PR_FOLDER_NAME}"/build

# build FIPS compliant version of AWSLC pr
mkdir -p "${PR_FOLDER_NAME}"/fips_build
${CMAKE_COMMAND} -B"${PR_FOLDER_NAME}"/fips_build -H"${PR_FOLDER_NAME}" -GNinja -DFIPS=1 -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=TRUE
ninja -C "${PR_FOLDER_NAME}"/fips_build

# build AWSLC prod
mkdir -p aws-lc-prod/build
${CMAKE_COMMAND} -Baws-lc-prod/build -Haws-lc-prod -GNinja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
ninja -C aws-lc-prod/build

#build FIPS compliant version of AWSLC prod
mkdir -p aws-lc-prod/fips_build
${CMAKE_COMMAND} -Baws-lc-prod/fips_build -Haws-lc-prod -GNinja -DFIPS=1 -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=TRUE
ninja -C aws-lc-prod/fips_build

./"${PR_FOLDER_NAME}"/build/tool/bssl speed -timeout 1 -json > aws-lc-pr_bm.json
./"${PR_FOLDER_NAME}"/fips_build/tool/bssl speed -timeout 1 -json > aws-lc-pr_fips_bm.json

./aws-lc-prod/build/tool/bssl speed -timeout 1 -json > aws-lc-prod_bm.json
./aws-lc-prod/fips_build/tool/bssl speed -timeout 1 -json > aws-lc-prod_fips_bm.json

./"${PR_FOLDER_NAME}"/build/tool/bssl speed -filter trusttoken -timeout 1 -json > aws-lc-pr_tt_bm.json
./"${PR_FOLDER_NAME}"/fips_build/tool/bssl speed -filter trusttoken -timeout 1 -json > aws-lc-pr_tt_fips_bm.json
./aws-lc-prod/build/tool/bssl speed -filter trusttoken -timeout 1 -json > aws-lc-prod_tt_bm.json
./aws-lc-prod/fips_build/tool/bssl speed -filter trusttoken -timeout 1 -json > aws-lc-prod_tt_fips_bm.json

# convert results from .json to .csv
python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-pr_bm.json
python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-pr_fips_bm.json
python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-prod_bm.json
python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-prod_fips_bm.json

python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-pr_tt_bm.json
python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-pr_tt_fips_bm.json
python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-prod_tt_bm.json
python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-prod_tt_fips_bm.json

# once we have csvs, we want to update the main benchmark results files with the sequential trusttoken results
# files will be updated in place
python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/update_results.py aws-lc-pr_bm.csv aws-lc-pr_tt_bm.csv python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/update_results.py aws-lc-pr_fips_bm.csv aws-lc-pr_tt_fips_bm.csv python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/update_results.py aws-lc-prod_bm.csv aws-lc-prod_tt_bm.csv python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/update_results.py aws-lc-prod_fips_bm.csv aws-lc-prod_tt_fips_bm.csv

# check for regressions!
python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/compare_results.py aws-lc-prod_bm.csv aws-lc-pr_bm.csv prod_vs_pr.csv
prod_vs_pr_code="$?"
python3 "${PR_FOLDER_NAME}"/tests/ci/benchmark_framework/compare_results.py aws-lc-prod_fips_bm.csv aws-lc-pr_fips_bm.csv prod_vs_pr_fips.csv
prod_vs_pr_fips_code="$?"

# upload results to s3
aws s3 cp aws-lc-pr_bm.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/${CODEBUILD_SOURCE_VERSION}/aws-lc-pr_bm.csv"
aws s3 cp aws-lc-pr_fips_bm.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/${CODEBUILD_SOURCE_VERSION}/aws-lc-pr_fips_bm.csv"
aws s3 cp aws-lc-prod_bm.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-prod-bucket/${CODEBUILD_SOURCE_VERSION}/aws-lc-prod_bm.csv"
aws s3 cp aws-lc-prod_fips_bm.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-prod-bucket/${CODEBUILD_SOURCE_VERSION}/aws-lc-prod_fips_bm.csv"

# upload results to lastest folders in s3
aws s3 mv aws-lc-pr_bm.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/latest-${CODEBUILD_WEBHOOK_TRIGGER}/aws-lc-pr_bm.csv"
aws s3 mv aws-lc-pr_fips_bm.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/latest-${CODEBUILD_WEBHOOK_TRIGGER}/aws-lc-pr_fips_bm.csv"
aws s3 mv aws-lc-prod_bm.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-prod-bucket/latest/aws-lc-prod_bm.csv"
aws s3 mv aws-lc-prod_fips_bm.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-prod-bucket/latest/aws-lc-prod_fips_bm.csv"

# if any of the results gave an exit code of 5, there's a performance regression
# we only want to actually fail the vote if we've detected a regression in the pr version of aws-lc and tip of main of aws-lc (for fips and non-fips)
exit_fail=false
if [ "${prod_vs_pr_code}" != 0 ]; then
  aws s3 cp prod_vs_pr.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/${CODEBUILD_SOURCE_VERSION}/prod_vs_pr.csv"
  aws s3 mv prod_vs_pr.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/latest-${CODEBUILD_WEBHOOK_TRIGGER}/prod_vs_pr.csv"
  exit_fail=true
fi
if [ "${prod_vs_pr_fips_code}" != 0 ]; then
  aws s3 cp prod_vs_pr_fips.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/${CODEBUILD_SOURCE_VERSION}/prod_vs_pr_fips.csv"
  aws s3 mv prod_vs_pr_fips.csv s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/latest-${CODEBUILD_WEBHOOK_TRIGGER}/prod_vs_pr_fips.csv"
  exit_fail=true
fi

if [ "${exit_fail}" = true ]; then
  exit 1
fi


# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

if [ -v CODEBUILD_FUZZING_ROOT ]; then
  CORPUS_ROOT="${CODEBUILD_FUZZING_ROOT}/fuzzing"
else
  CORPUS_ROOT="${BUILD_ROOT}/mock_efs/fuzzing"
fi
echo "$CORPUS_ROOT"

if [ -v CODEBUILD_BUILD_ID ]; then
  BUILD_ID=$CODEBUILD_BUILD_ID
else
  # Generate a random string in bash https://unix.stackexchange.com/questions/230673/how-to-generate-a-random-string
  BUILD_ID=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 13 ; echo '')
fi
echo "$BUILD_ID"

DATE_NOW="$(date +%Y-%m-%d)"
SHARED_FAILURE_ROOT="${CORPUS_ROOT}/runs/${DATE_NOW}/${BUILD_ID}"
LOCAL_RUN_ROOT="${BUILD_ROOT}/fuzz_run_root"
rm -rf "$LOCAL_RUN_ROOT"

function put_metric_count {
  put_metric --unit Count "$@"
}

function put_metric {
  # This call to publish the metric could fail but we don't want to fail the build +e turns off exit on error
  set +e
  aws cloudwatch put-metric-data \
    --namespace AWS-LC-Fuzz \
    "$@" || echo "Publishing metric failed, continuing with the rest of the build"
  # Turn it back on for the rest of the build
  set -e
}

function run_fuzz_test {
  SHARED_FUZZ_TEST_CORPUS="${CORPUS_ROOT}/shared_corpus/${FUZZ_NAME}/shared_corpus"
  LOCAL_FUZZ_TEST_ROOT="${LOCAL_RUN_ROOT}/${FUZZ_NAME}"
  LOCAL_SHARED_CORPUS="${LOCAL_FUZZ_TEST_ROOT}/local_shared_corpus"
  LOCAL_RUN_CORPUS="${LOCAL_FUZZ_TEST_ROOT}/run_corpus"
  LOCAL_ARTIFACTS_FOLDER="${LOCAL_FUZZ_TEST_ROOT}/artifacts"
  LOCAL_FUZZ_RUN_LOGS="${LOCAL_FUZZ_TEST_ROOT}/logs"
  SUMMARY_LOG="${LOCAL_FUZZ_RUN_LOGS}/summary.log"
  mkdir -p "$SHARED_FUZZ_TEST_CORPUS" "$LOCAL_FUZZ_TEST_ROOT" "$LOCAL_RUN_CORPUS" "$LOCAL_ARTIFACTS_FOLDER" "$LOCAL_FUZZ_RUN_LOGS"

  # To avoid having each libfuzzer thread read from the shared corpus copy it to the local CodeBuild directory one time
  cp -r "$SHARED_FUZZ_TEST_CORPUS" "$LOCAL_SHARED_CORPUS"

  # Calculate starting metrics and post to CloudWatch, this counts the files in LOCAL_SHARED_CORPUS but publishes them
  # as the SharedCorpusFileCount, which it basically everything in SHARED_FUZZ_TEST_CORPUS was just copied to
  # LOCAL_SHARED_CORPUS
  ORIGINAL_CORPUS_FILE_COUNT=$(find "$LOCAL_SHARED_CORPUS" -type f | wc -l)
  put_metric_count --metric-name SharedCorpusFileCount --value "$ORIGINAL_CORPUS_FILE_COUNT" --dimensions "FuzzTest=$FUZZ_NAME"

  # Perform the actual fuzzing!
  # Step 1 run each fuzz test for the determined time. This will use the existing shared corpus copied from EFS to
  # LOCAL_SHARED_CORPUS and any files checked into the GitHub SRC_CORPUS. This runs the fuzzer with three
  # folders: the first folder is where new inputs will go (LOCAL_RUN_CORPUS), all other folders will be used as input
  # for fuzzing (LOCAL_SHARED_CORPUS and SRC_CORPUS).
  # https://llvm.org/docs/LibFuzzer.html#options
  #
  # Run with NUM_CPU_THREADS which will be physical cores on ARM and virtualized cores on x86 with hyper threading.
  # Looking at the overall system fuzz rate running 1:1 with virtualized cores provides a noticeable speed up. This
  # is slightly different than libfuzzer's recommendation of #cores/2.
  # This could fail and we want to capture that so we can publish metrics and save logs (+e)
  set +e
  FUZZ_RUN_FAILURE=0
  # 2048 is the default memory usage. https://llvm.org/docs/LibFuzzer.html
  MEM_USAGE_LIMIT=2048
  if [[ ("${FUZZ_NAME}" == *"cryptofuzz"*) && (("$(uname -p)" == 'aarch64')) ]]; then
    # On arm, libFuzzer: out-of-memory (used: 2063Mb; limit: 2048Mb)
    # Below is set based on ARM BUILD_GENERAL1_LARGE(8vCPU, 16 GB memory).
    # 2500MB x 6 / 1024 = 14.6GB
    MEM_USAGE_LIMIT=2500
    NUM_CPU_THREADS=6
  fi
  time "${FUZZ_TEST_PATH}" -rss_limit_mb=${MEM_USAGE_LIMIT} -print_final_stats=1 -timeout="$FUZZ_TEST_TIMEOUT" -max_total_time="$TIME_FOR_EACH_FUZZ" \
    -jobs="$NUM_CPU_THREADS" -workers="$NUM_CPU_THREADS" \
    -artifact_prefix="$LOCAL_ARTIFACTS_FOLDER/" \
    "$LOCAL_RUN_CORPUS" "$LOCAL_SHARED_CORPUS" "$SRC_CORPUS" 2>&1 | tee "$SUMMARY_LOG"
  # This gets the status of the fuzz run which determines if we want to fail the build or not, otherwise we'd get the results of tee
  if [ "${PIPESTATUS[0]}" == 1 ]; then
    FUZZ_RUN_FAILURE=1
  fi

  # The libfuzzer logs are written to the current working directory and need to be moved after the test is done
  mv ./*.log  "${LOCAL_FUZZ_RUN_LOGS}/."

  if [ "$FUZZ_RUN_FAILURE" == 1 ]; then
    FUZZ_TEST_FAILURE_ROOT="${SHARED_FAILURE_ROOT}/${FUZZ_NAME}"
    mkdir -p "$FUZZ_TEST_FAILURE_ROOT"

    if [[ "$FUZZ_NAME" == "cryptofuzz" ]]; then
      for ARTIFACT in "$LOCAL_ARTIFACTS_FOLDER"/*; do
        base64 $ARTIFACT
        ARTIFACT_NAME=$(basename "$ARTIFACT")
        "${FUZZ_TEST_PATH}" --debug "$ARTIFACT" | tee "${LOCAL_FUZZ_RUN_LOGS}/${ARTIFACT_NAME}.log"
      done
    fi

    cp -r "$LOCAL_FUZZ_TEST_ROOT" "$SHARED_FAILURE_ROOT"
    cp "$FUZZ_TEST_PATH" "${FUZZ_TEST_FAILURE_ROOT}/${FUZZ_NAME}"

    # If this fuzz run has failed the below metrics won't make a lot of sense, it could fail on the first input and
    # publish a TestCount of 1 which makes all the metrics look weird
    echo "${FUZZ_NAME} failed, see the above output for details. For all the logs see ${SHARED_FAILURE_ROOT} in EFS"
    exit 1
  else
    echo "Fuzz test ${FUZZ_NAME} finished successfully, not copying run logs and run corpus"
  fi

  set -e

  # Step 2 merge any new files from the run corpus and GitHub src corpus into the shared corpus, the first folder is
  # where to merge the new corpus (SHARED_FUZZ_TEST_CORPUS), the second two are where to read new inputs from
  # (LOCAL_RUN_CORPUS and SRC_CORPUS).
  time "${FUZZ_TEST_PATH}" -merge=1 "$SHARED_FUZZ_TEST_CORPUS" "$LOCAL_RUN_CORPUS" "$SRC_CORPUS"

  # Calculate interesting metrics and post results to CloudWatch, this checks the shared (EFS) corpus after the new test
  # run corpus has been merged in
  FINAL_SHARED_CORPUS_FILE_COUNT=$(find "$SHARED_FUZZ_TEST_CORPUS" -type f | wc -l)
  put_metric_count --metric-name SharedCorpusFileCount --value "$FINAL_SHARED_CORPUS_FILE_COUNT" --dimensions "FuzzTest=$FUZZ_NAME"

  RUN_CORPUS_FILE_COUNT=$(find "$LOCAL_RUN_CORPUS" -type f | wc -l)
  put_metric_count --metric-name RunCorpusFileCount --value "$RUN_CORPUS_FILE_COUNT" --dimensions "FuzzTest=$FUZZ_NAME,Platform=$PLATFORM"

  TEST_COUNT=$(grep -o "stat::number_of_executed_units: [0-9]*" "$SUMMARY_LOG" | awk '{test_count += $2} END {print test_count}')
  put_metric_count --metric-name TestCount --value "$TEST_COUNT" --dimensions "FuzzTest=$FUZZ_NAME,Platform=$PLATFORM"

  TESTS_PER_SECOND=$((TEST_COUNT/TIME_FOR_EACH_FUZZ))
  put_metric --metric-name TestRate --value "$TESTS_PER_SECOND" --unit Count/Second --dimensions "FuzzTest=$FUZZ_NAME,Platform=$PLATFORM"

  FEATURE_COVERAGE=$(grep -o "ft: [0-9]*" "$SUMMARY_LOG" | awk '{print $2}' | sort -n | tail -1)
  put_metric_count --metric-name FeatureCoverage --value "$FEATURE_COVERAGE" --dimensions "FuzzTest=$FUZZ_NAME,Platform=$PLATFORM"

  BLOCK_COVERAGE=$(grep -o "cov: [0-9]*" "$SUMMARY_LOG" | awk '{print $2}' | sort -n | tail -1)
  put_metric_count --metric-name BlockCoverage --value "$BLOCK_COVERAGE" --dimensions "FuzzTest=$FUZZ_NAME,Platform=$PLATFORM"

  echo "${FUZZ_NAME} starting shared ${ORIGINAL_CORPUS_FILE_COUNT} final shared ${FINAL_SHARED_CORPUS_FILE_COUNT} new files ${RUN_CORPUS_FILE_COUNT} total test count ${TEST_COUNT} test rate ${TESTS_PER_SECOND} code coverage ${BLOCK_COVERAGE} feature coverage ${FEATURE_COVERAGE}"
}


# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

if [ -v CODEBUILD_SRC_DIR ]; then
  SRC_ROOT="$CODEBUILD_SRC_DIR"
else
  SRC_ROOT=$(pwd)
fi
echo "$SRC_ROOT"

cd ../
SYS_ROOT=$(pwd)
cd $SRC_ROOT

BUILD_ROOT="${SRC_ROOT}/test_build_dir"
echo "$BUILD_ROOT"

PLATFORM=$(uname -m)

NUM_CPU_THREADS=''
KERNEL_NAME=$(uname -s)
if [[ "${KERNEL_NAME}" == "Darwin" ]]; then
  # On MacOS, /proc/cpuinfo does not exist.
  NUM_CPU_THREADS=$(sysctl -n hw.ncpu)
else
  # Assume KERNEL_NAME is Linux.
  NUM_CPU_THREADS=$(grep -c ^processor /proc/cpuinfo)
  if [[ $PLATFORM == "aarch64" ]]; then
    CPU_PART=$(grep -Po -m 1 'CPU part.*:\s\K.*' /proc/cpuinfo)
    NUM_CPU_PART=$(grep -c $CPU_PART /proc/cpuinfo)
    # Set capabilities via the static flags for valgrind tests.
    # This is because valgrind reports the instruction
    #   mrs %0, MIDR_EL1
    # which fetches the CPU part number, as illegal.
    # For some reason, valgrind also reports SHA512 instructions illegal,
    # so the SHA512 capability is not included below.
    VALGRIND_STATIC_CAP_FLAGS="-DOPENSSL_STATIC_ARMCAP -DOPENSSL_STATIC_ARMCAP_NEON"
    VALGRIND_STATIC_CAP_FLAGS+=" -DOPENSSL_STATIC_ARMCAP_AES -DOPENSSL_STATIC_ARMCAP_PMULL "
    VALGRIND_STATIC_CAP_FLAGS+=" -DOPENSSL_STATIC_ARMCAP_SHA1 -DOPENSSL_STATIC_ARMCAP_SHA256 "
    if [[ $NUM_CPU_PART == $NUM_CPU_THREADS ]] && [[ ${CPU_PART} =~ 0x[dD]40 ]]; then
      VALGRIND_STATIC_CAP_FLAGS+=" -DOPENSSL_STATIC_ARMCAP_SHA3 -DOPENSSL_STATIC_ARMCAP_NEOVERSE_V1"
    fi
  fi
fi

# Pick cmake3 if possible. We don't know of any OS that installs a cmake3
# executable that is not at least version 3.0.
if [[ -x "$(command -v cmake3)" ]] ; then
  CMAKE_COMMAND="cmake3"
else
  CMAKE_COMMAND="cmake"
fi

function run_build {
  local cflags=("$@")
  rm -rf "$BUILD_ROOT"
  mkdir -p "$BUILD_ROOT"
  cd "$BUILD_ROOT" || exit 1

  if [[ "${AWSLC_32BIT}" == "1" ]]; then
    cflags+=("-DCMAKE_TOOLCHAIN_FILE=${SRC_ROOT}/util/32-bit-toolchain.cmake")
  fi

  if [[ -x "$(command -v ninja)" ]]; then
    echo "Using Ninja build system (ninja)."
    BUILD_COMMAND="ninja"
    cflags+=(-GNinja)
  elif [[ -x "$(command -v ninja-build)" ]]; then
    echo "Using Ninja build system (ninja-build)."
    BUILD_COMMAND="ninja-build"
    cflags+=(-GNinja)
  else
    echo "Using Make."
    BUILD_COMMAND="make -j${NUM_CPU_THREADS}"
  fi

  ${CMAKE_COMMAND} "${cflags[@]}" "$SRC_ROOT"
  $BUILD_COMMAND
  cd "$SRC_ROOT"
}

function run_cmake_custom_target {
  $BUILD_COMMAND -C "$BUILD_ROOT" "$@"
}

function build_and_test {
  run_build "$@"
  run_cmake_custom_target 'run_tests'
}

function generate_symbols_file {
  # read_symbols.go currently only support static libraries
  if [ ! -f  "$BUILD_ROOT"/crypto/libcrypto.a ]; then
    echo "Static library not found: ${BUILD_ROOT}/crypto/libcrypto.a"
    exit 1
  fi

  go run "$SRC_ROOT"/util/read_symbols.go -out "$BUILD_ROOT"/symbols_crypto.txt "$BUILD_ROOT"/crypto/libcrypto.a
  go run "$SRC_ROOT"/util/read_symbols.go -out "$BUILD_ROOT"/symbols_ssl.txt "$BUILD_ROOT"/ssl/libssl.a

  # The $BUILD_ROOT gets deleted on each run. symbols.txt must be placed elsewhere.
  cat "$BUILD_ROOT"/symbols_crypto.txt  "$BUILD_ROOT"/symbols_ssl.txt >  "$SRC_ROOT"/symbols.txt
}

function verify_symbols_prefixed {
  go run "$SRC_ROOT"/util/read_symbols.go -out "$BUILD_ROOT"/symbols_final_crypto.txt "$BUILD_ROOT"/crypto/libcrypto.a
  go run "$SRC_ROOT"/util/read_symbols.go -out "$BUILD_ROOT"/symbols_final_ssl.txt "$BUILD_ROOT"/ssl/libssl.a
  # For grep's basic regular expression language the meta-characters (e.g. "?",
  # "|", etc.) are interpreted as literal characters. To keep their
  # meta-character semantics, they must be escaped with "\".
  # Deciphering the pattern "^_\?\(bignum\|curve25519_x25519\)":
  #  * "^": anchor at start of line.
  #  * "_\?": might contain underscore.
  #  * "\(bignum\|curve25519_x25519\)": match string of either "bignum" or "curve25519_x25519".
  # Recall that the option "-v" reverse the pattern matching. So, we are really
  # filtering out lines that contain either "bignum" or "curve25519_x25519".
  cat "$BUILD_ROOT"/symbols_final_crypto.txt  "$BUILD_ROOT"/symbols_final_ssl.txt | grep -v -e '^_\?\(bignum\|curve25519_x25519\)' >  "$SRC_ROOT"/symbols_final.txt
  # Now filter out every line that has the unique prefix $CUSTOM_PREFIX. If we
  # have any lines left, then some symbol(s) weren't prefixed, unexpectedly.
  if [ $(grep -c -v ${CUSTOM_PREFIX}  "$SRC_ROOT"/symbols_final.txt) -ne 0 ]; then
    echo "Symbol(s) missing prefix!"
    exit 1
  fi
}

function build_prefix_and_test {
  CUSTOM_PREFIX=aws_lc_1_1_0
  run_build "$@"
  generate_symbols_file
  run_build "$@" "-DBORINGSSL_PREFIX=${CUSTOM_PREFIX}" "-DBORINGSSL_PREFIX_SYMBOLS=${SRC_ROOT}/symbols.txt"
  verify_symbols_prefixed
  run_cmake_custom_target 'run_tests'
}

function fips_build_and_test {
  run_build "$@" -DFIPS=1
  # Upon completion of the build process. The moduleâ€™s status can be verified by 'tool/bssl isfips'.
  # https://csrc.nist.gov/CSRC/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp3678.pdf
  # FIPS mode is enabled when 'defined(BORINGSSL_FIPS) && !defined(OPENSSL_ASAN)'.
  # https://github.com/aws/aws-lc/blob/220e266d4e415cf0101388b89a2bd855e0e4e203/crypto/fipsmodule/is_fips.c#L22
  expect_fips_mode=1
  for build_flag in "$@"
  do
    if [[ "${build_flag}" == '-DASAN=1' ]]; then
      expect_fips_mode=0
      break
    fi
  done
  module_status=$("${BUILD_ROOT}/tool/bssl" isfips)
  [[ "${expect_fips_mode}" == "${module_status}" ]] || { echo >&2 "FIPS Mode validation failed."; exit 1; }
  # Run tests.
  run_cmake_custom_target 'run_tests'
  "${BUILD_ROOT}/util/fipstools/test_fips"
}

function build_and_test_valgrind {
  if [[ $PLATFORM == "aarch64" ]]; then
    run_build "$@" -DCMAKE_C_FLAGS="$VALGRIND_STATIC_CAP_FLAGS"
    run_cmake_custom_target 'run_tests_valgrind'

    # Disable all capabilities and run again
    # (We don't use the env. variable OPENSSL_armcap because it is currently
    #  restricted to the case of runtime discovery of capabilities
    #  in cpu_aarch64_linux.c)
    run_build "$@" -DCMAKE_C_FLAGS="-DOPENSSL_STATIC_ARMCAP"
    run_cmake_custom_target 'run_tests_valgrind'
  else
    run_build "$@"
    run_cmake_custom_target 'run_tests_valgrind'
  fi
}

function build_and_test_ssl_runner_valgrind {
  export AWS_LC_GO_TEST_TIMEOUT="60m"

  if [[ $PLATFORM == "aarch64" ]]; then
    run_build "$@" -DCMAKE_C_FLAGS="$VALGRIND_STATIC_CAP_FLAGS"
  else
    run_build "$@"
  fi
    run_cmake_custom_target 'run_ssl_runner_tests_valgrind'
}

function build_and_test_with_sde {
  run_build "$@"
  run_cmake_custom_target 'run_tests_with_sde'
}

function build_and_run_minimal_test {
  run_build "$@"
  run_cmake_custom_target 'run_minimal_tests'
}

# Install local build of AWS-LC for integration testing.
function aws_lc_build() {
  AWS_LC_DIR=${1}
  BUILD_FOLDER=${2}
  INSTALL_FOLDER=${3}

  echo "Building AWS-LC to ${BUILD_FOLDER} and installing to ${INSTALL_FOLDER} with CFlags "${@:4}""
  ${CMAKE_COMMAND} ${AWS_LC_DIR} -GNinja "-B${BUILD_FOLDER}" "-DCMAKE_INSTALL_PREFIX=${INSTALL_FOLDER}" "${@:4}"
  ninja -C ${BUILD_FOLDER} install
  ls -R ${INSTALL_FOLDER}
  rm -rf ${BUILD_FOLDER:?}/*
}

function print_executable_information {
  EXE_NAME=${1}
  EXE_ARGUMENT=${2}
  LABEL=${3}

  echo ""
  echo "${LABEL}:"
  if command -v ${EXE_NAME} &> /dev/null
  then
    ${EXE_NAME} ${EXE_ARGUMENT}
  else
    echo "${EXE_NAME} not found"
  fi
}

print_executable_information "cmake" "--version" "CMake version"
print_executable_information "cmake3" "--version" "CMake version (cmake3 executable)"
print_executable_information "go" "version" "Go version"
print_executable_information "perl" "--version" "Perl version"
# Ninja executable names are not uniform over operating systems
print_executable_information "ninja-build" "--version" "Ninja version (ninja-build executable)"
print_executable_information "ninja" "--version" "Ninja version (ninja executable)"
print_executable_information "gcc" "--version" "gcc version"
print_executable_information "g++" "--version" "g++ version"
print_executable_information "clang" "--version" "clang version"
print_executable_information "clang++" "--version" "clang++ version"
print_executable_information "cc" "--version" "cc version"
print_executable_information "c++" "--version" "c++ version"
print_executable_information "make" "--version" "Make version"
print_executable_information "rustup" "show" "Rust toolchain"
echo ""
echo "Operating system information:"
uname -a
echo ""
echo "Environment variables:"
env


# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

#$1 is the prefix for the ssm document, echos the doc name so we can capture the output
create_ssm_document() {
  local doc_name
  doc_name="$1"_ssm_document_"${CODEBUILD_SOURCE_VERSION}"
  aws ssm create-document --content file://tests/ci/cdk/cdk/ssm/"$1"_ssm_document.yaml \
    --name "${doc_name}" \
    --document-type Command \
    --document-format YAML >/dev/null
  echo "${doc_name}"
}

#$1 is the document name, $2 is the instance ids, $3 is the cloudwatch log group name.
function run_ssm_command() {
  local command_id
  command_id="$(aws ssm send-command --instance-ids "${2}" \
    --document-name "${1}" \
    --cloud-watch-output-config CloudWatchLogGroupName="${3}",CloudWatchOutputEnabled=true \
    --query Command.CommandId --output text)"
  echo "${command_id}"
}


#!/bin/bash

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

set -exuo pipefail

# -e: Exit on any failure
# -x: Print the command before running
# -u: Any variable that is not set will cause an error if used
# -o pipefail: Makes sure to exit a pipeline with a non-zero error code if any command in the pipeline exists with a
#              non-zero error code.

# Device Farm project to designate Device Farm runs. The two device pools defined below should also belong to this project.
AWSLC_DEVICEFARM_PROJECT='arn:aws:devicefarm:us-west-2:620771051181:project:d1e78543-a776-49c5-9452-9a2b3448b728'
# Device pool arn for FIPS.
AWSLC_FIPS_DEVICEFARM_DEVICE_POOL='arn:aws:devicefarm:us-west-2:620771051181:devicepool:d1e78543-a776-49c5-9452-9a2b3448b728/4726586b-cdbc-4dc0-98a5-38e7448e3691'
# Device pool arn for non-FIPS.
AWSLC_NON_FIPS_DEVICEFARM_DEVICE_POOL='arn:aws:devicefarm:us-west-2:620771051181:devicepool:d1e78543-a776-49c5-9452-9a2b3448b728/4e72604c-86eb-41b6-9383-7797c04328b4'

###########################
# Main and related helper #
###########################

function script_helper() {
  cat <<EOF
This script helps compile AWSLCAndroidTestRunner and kick off the device farm python script with the arguments needed.

Options:
    --help                          Displays this help menu
    --test-name						          Name of current test.
    --devicefarm-project-arn        The devicefarm project's arn. Default to team account's.
    --devicefarm-device-pool-arn    The device pool's arn.
    --fips                          If we're compiling for FIPS or not. Will always compile for the FIPS, shared, release build.
    --release                       If we're compiling for Release or Debug.
    --shared                        If we're compiling for Shared or Static.
    --action                        Required. The value can be:
	                                   'start-job': kicks off a device farm job.
EOF
}

function export_global_variables() {
  # If these variables are not set or empty, defaults are exported, but the |main-apk| and |test-apk| must be set.
  if [[ -z "${ANDROID_TEST_NAME+x}" || -z "${ANDROID_TEST_NAME}" ]]; then
    export ANDROID_TEST_NAME='AWS-LC Android Test'
  fi
  if [[ -z "${DEVICEFARM_PROJECT+x}" || -z "${DEVICEFARM_PROJECT}" ]]; then
    export DEVICEFARM_PROJECT=$AWSLC_DEVICEFARM_PROJECT
  fi
  if [[ -z "${FIPS+x}" || -z "${FIPS}" ]]; then
    export FIPS=false
  fi
  if [[ -z "${RELEASE+x}" || -z "${RELEASE}" ]]; then
    export RELEASE=false
  fi
  if [[ -z "${SHARED+x}" || -z "${SHARED}" ]]; then
    export SHARED=false
  fi
  if [[ -z "${DEVICEFARM_DEVICE_POOL+x}" || -z "${DEVICEFARM_DEVICE_POOL}" ]]; then
    if [[ "${FIPS}" = true ]]; then
      # Device pool arn for FIPS.
      export DEVICEFARM_DEVICE_POOL=$AWSLC_FIPS_DEVICEFARM_DEVICE_POOL
    else
      # Device pool arn for non-FIPS.
      export DEVICEFARM_DEVICE_POOL=$AWSLC_NON_FIPS_DEVICEFARM_DEVICE_POOL
    fi
  fi
  if [[ -z "${AWS_REGION+x}" || -z "${AWS_REGION}" ]]; then
    export AWS_REGION='us-west-2'
  fi
}

function compile_for_android() {
  # |ANDROID_APK| and |ANDROID_TEST_APK| are apk names corresponding to the settings in the test runner gradle file.
  # The working directory of this script should under `tests/ci`.
  # AWSLCAndroidTestRunner should be at `tests/ci/android/AWSLCAndroidTestRunner`.
  pushd android/AWSLCAndroidTestRunner
  export ANDROID_APK_LOCATION='android/AWSLCAndroidTestRunner/app/build/outputs/apk'
  if [[ "${FIPS}" = true ]]; then
    if [[ "${SHARED}" = true ]]; then
      # FIPS (Release Shared)
      ./gradlew assembleDebug assembleAndroidTest -PFIPS -PShared --offline
    else
      # FIPS (Release Static), go dependencies need to be copied from AWS-LC.
      mkdir app/src/main/cpp/util
      cp -r ../../../../util/godeps.go app/src/main/cpp/util/godeps.go
      cp -r ../../../../go.mod app/src/main/cpp/go.mod
      cp -r ../../../../go.sum app/src/main/cpp/go.sum
      ./gradlew assembleDebug assembleAndroidTest -PFIPS --offline
    fi
    export ANDROID_APK="${ANDROID_APK_LOCATION}/debug/awslc_fips.apk"
    export ANDROID_TEST_APK="${ANDROID_APK_LOCATION}/androidTest/debug/awslc_fips-androidTest.apk"
  else
    if [[ "${RELEASE}" = true ]]; then
      if [[ "${SHARED}" = true ]]; then
        # Release Shared
        ./gradlew assembleDebug assembleAndroidTest -PRelease -PShared --offline
        export ANDROID_APK="${ANDROID_APK_LOCATION}/debug/awslc_shared_rel.apk"
        export ANDROID_TEST_APK="${ANDROID_APK_LOCATION}/androidTest/debug/awslc_shared_rel-androidTest.apk"
      else
        # Release Static
        ./gradlew assembleDebug assembleAndroidTest -PRelease --offline
        export ANDROID_APK="${ANDROID_APK_LOCATION}/debug/awslc_static_rel.apk"
        export ANDROID_TEST_APK="${ANDROID_APK_LOCATION}/androidTest/debug/awslc_static_rel-androidTest.apk"
      fi
    else
      if [[ "${SHARED}" = true ]]; then
        # Debug Shared
        ./gradlew assembleDebug assembleAndroidTest -PShared --offline
        export ANDROID_APK="${ANDROID_APK_LOCATION}/debug/awslc_shared_dbg.apk"
        export ANDROID_TEST_APK="${ANDROID_APK_LOCATION}/androidTest/debug/awslc_shared_dbg-androidTest.apk"
      else
        # Debug Static
        ./gradlew assembleDebug assembleAndroidTest --offline
        export ANDROID_APK="${ANDROID_APK_LOCATION}/debug/awslc_static_dbg.apk"
        export ANDROID_TEST_APK="${ANDROID_APK_LOCATION}/androidTest/debug/awslc_static_dbg-androidTest.apk"
      fi
    fi
  fi
  popd
}

function main() {
  # parse arguments.
  while [[ $# -gt 0 ]]; do
    case ${1} in
    --help)
      script_helper
      exit 0
      ;;
    --test-name)
      export ANDROID_TEST_NAME="${2}"
      shift
      ;;
    --devicefarm-project-arn)
      export DEVICEFARM_PROJECT="${2}"
      shift
      ;;
    --devicefarm-device-pool-arn)
      export DEVICEFARM_DEVICE_POOL="${2}"
      shift
      ;;
    --fips)
      export FIPS="${2}"
      shift
      ;;
    --release)
      export RELEASE="${2}"
      shift
      ;;
    --shared)
      export SHARED="${2}"
      shift
      ;;
    --action)
      export ACTION="${2}"
      shift
      ;;
    *)
      echo "${1} is not supported."
      exit 1
      ;;
    esac
    # Check next option -- key/value.
    shift
  done

  # Make sure action is set.
  if [[ -z "${ACTION+x}" || -z "${ACTION}" ]]; then
    echo "${ACTION} is required input."
    exit 1
  fi

  # Export global variables, which provides the contexts needed by ci setup/destroy.
  export_global_variables

  # Execute the action.
  case ${ACTION} in
  start-job)
    compile_for_android
    python3 -u ./devicefarm_job.py
    ;;
  *)
    echo "--action is required. Use '--help' to see allowed actions."
    exit 1
    ;;
  esac
}

# Invoke main
main "$@"


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

# The build and test time is not meant to be scientific benchmark, just to get a rough sense of changes overtime.
# In case there is a weird change over time this recorded additional information about the host to the logs.
lscpu

branch=$(echo "$CODEBUILD_WEBHOOK_TRIGGER" | cut -d '/' -f2)
common_dimensions="Branch=${branch}"

commit_timestamp=$(git show -s --format=%ct)

function put_metric {
  # This call to publish the metric could fail but we don't want to fail the build +e turns off exit on error
  set +e
  aws cloudwatch put-metric-data \
    --timestamp "$commit_timestamp" \
    --namespace AWS-LC \
    "$@" || echo "Publishing metric failed, continuing with the rest of the build"
  # Turn it back on for the rest of the build
  set -e
}

# Return the size of an object or total for the folder (summarize)
function size {
  du --bytes --apparent-size --summarize "$@" | cut -f1
}

SOURCE_CODE_SIZE=$(size "$SRC_ROOT")
put_metric --metric-name FolderSize --value "$SOURCE_CODE_SIZE" --unit Bytes --dimensions "Folder=root,${common_dimensions}"

for FOLDER_PATH in "$SRC_ROOT"/*/ ; do
    FOLDER_SIZE=$(size "$FOLDER_PATH")
    FOLDER=$(basename "$FOLDER_PATH")
    put_metric --metric-name FolderSize --value "$FOLDER_SIZE" --unit Bytes --dimensions "Folder=${FOLDER},${common_dimensions}"
done

function run_build_and_collect_metrics {
  cmake_build_flags=("-DCMAKE_BUILD_TYPE=Release")
  if [[ "$small" == "ON" ]]; then
    build_size="Small"
    cmake_build_flags+=("-DOPENSSL_SMALL=1")
  else
    build_size="Large"
  fi
  if [[ "$no_assembly" == "ON" ]]; then
    assembly="NoAsm"
    cmake_build_flags+=("-DOPENSSL_NO_ASM=1")
  else
    assembly="Asm"
  fi

  cmake_build_flags+=("-DBUILD_SHARED_LIBS=${shared_library}")
  if [[ "$shared_library" == "ON" ]]; then
    linking="Shared"
    lib_extension="so"
  else
    linking="Static"
    lib_extension="a"
  fi
  if [[ "$fips" == "ON" ]]; then
    fips_mode="FIPS"
    cmake_build_flags+=("-DFIPS=1")
  else
    fips_mode="NotFIPS"
  fi
  size_common_dimensions="${common_dimensions},Optimization=Release,BuildSize=${build_size},Assembly=${assembly},CPU=${PLATFORM},Linking=${linking},FIPS=${fips_mode}"

  build_start=$(date +%s)
  run_build "${cmake_build_flags[@]}"
  build_end=$(date +%s)
  build_time=$((build_end-build_start))
  put_metric --metric-name BuildTime --value "$build_time" --unit Seconds --dimensions "$size_common_dimensions"

  test_start=$(date +%s)
  run_cmake_custom_target 'run_tests'
  test_end=$(date +%s)
  test_time=$((test_end-test_start))
  put_metric --metric-name TestTime --value "$test_time" --unit Seconds --dimensions "$size_common_dimensions"

  libcrypto_size=$(size "${BUILD_ROOT}/crypto/libcrypto.${lib_extension}")
  libssl_size=$(size "${BUILD_ROOT}/ssl/libssl.${lib_extension}")
  tool_size=$(size "${BUILD_ROOT}/tool/bssl")
  put_metric --metric-name LibCryptoSize --value "$libcrypto_size" --unit Bytes --dimensions "${size_common_dimensions}"
  put_metric --metric-name LibSSLSize --value "$libssl_size" --unit Bytes --dimensions "${size_common_dimensions}"
  put_metric --metric-name ToolSize --value "$tool_size" --unit Bytes --dimensions "${size_common_dimensions}"

  pushd .
  cd "$BUILD_ROOT"
  for file_path in $(find . -type f -name "*.o"); do
    object_size=$(size "${BUILD_ROOT}/${file_path}")
    # Cleanup the file names ./crypto/fipsmodule/CMakeFiles/fipsmodule.dir/bcm.c.o -> crypto/fipsmodule/bcm.c.o
    # sed has there own regex format, [[:alpha:]] matches one Alphabetic character
    file_name=$(sed -e "s/CMakeFiles\///g" -e "s/[[:alpha:]]*\.dir\///g" <<< "$file_path" | cut -c 3-)
    put_metric --metric-name ObjectSize --value "$object_size" --unit Bytes --dimensions "File=${file_name},${size_common_dimensions}"
  done
  popd
}

fips=OFF
for shared_library in ON OFF; do
  for small in ON OFF; do
    for no_assembly in ON OFF; do
      run_build_and_collect_metrics
    done
  done
done

# We only care about two FIPS dimensions
shared_library=ON
small=OFF
no_assembly=OFF
fips=ON
run_build_and_collect_metrics

# The static FIPS build only works on Linux platforms.
if [[ ("$(uname -s)" == 'Linux'*) && (("$(uname -p)" == 'x86_64'*) || ("$(uname -p)" == 'aarch64'*)) ]]; then
  shared_library=OFF
  run_build_and_collect_metrics
fi


#!/bin/bash -ex
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

install_dir="$(pwd)/../libcrypto_install_dir"
openssl_url='https://github.com/openssl/openssl.git'
openssl_1_1_branch='OpenSSL_1_1_1-stable'
openssl_1_0_branch='OpenSSL_1_0_2-stable'
# OpenSSL 3.0 branch still isn't stable yet, so we lock down
# a tag to prevent build failures that they introduced from
# failing our CI.
openssl_3_0_branch='openssl-3.0.5'

function build_aws_lc_fips {
  echo "building aws-lc in FIPS mode"
  run_build \
      -DCMAKE_INSTALL_PREFIX="${install_dir}/aws-lc-fips" \
      -DFIPS=1 \
      -DENABLE_DILITHIUM=ON \
      -DCMAKE_BUILD_TYPE=RelWithDebInfo
  pushd "$BUILD_ROOT"
  ninja install
  popd
}

function build_openssl_1_0 {
    echo "building OpenSSL 1.0"
    git clone --depth 1 --branch "${openssl_1_0_branch}" "${openssl_url}" "../openssl-1.0"
    pushd "../openssl-1.0"
    mkdir -p "${install_dir}/openssl-1.0"
    ./config --prefix="${install_dir}/openssl-1.0" --openssldir="${install_dir}/openssl-1.0" -d
    make "-j${NUM_CPU_THREADS}" > /dev/null
    make install_sw
    popd
    rm -rf "../openssl-1.0"
}

function build_openssl_1_1 {
    echo "building OpenSSL 1.1"
    git clone --depth 1 --branch "${openssl_1_1_branch}" "${openssl_url}" "../openssl-1.1"
    pushd "../openssl-1.1"
    mkdir -p "${install_dir}/openssl-1.1"
    ./config --prefix="${install_dir}/openssl-1.1" --openssldir="${install_dir}/openssl-1.1" -d
    make "-j${NUM_CPU_THREADS}" > /dev/null
    make install_sw
    popd
    rm -rf "../openssl-1.1"
}

function build_openssl_3_0 {
    echo "building OpenSSL 3.0"
    git clone --depth 1 --branch "${openssl_3_0_branch}" "${openssl_url}" "../openssl-3.0"
    pushd "../openssl-3.0"
    mkdir -p "${install_dir}/openssl-3.0"
    ./Configure --prefix="${install_dir}/openssl-3.0" --openssldir="${install_dir}/openssl-3.0" -d
    make "-j${NUM_CPU_THREADS}" > /dev/null
    make install_sw
    popd
    rm -rf "../openssl-3.0"
}

# We build each tool individually so we can have more insight into what is failing

# Building AWS-LC always builds bssl (which includes the speed tool) with the "local" libcrypto. We
# also support building speed.cc with an "external" aws-lc libcrypto (and openssl). This is useful
# when we want to compare the performance of a particular FIPS release against mainline if mainline
# has changes in speed.cc that could affect the comparison of the FIPS to non-FIPS, or if new
# algorithms have been added to speed.cc
build_aws_lc_fips
echo "Testing awslc_bm with AWS-LC FIPS"
run_build -DAWSLC_INSTALL_DIR="${install_dir}/aws-lc-fips" -DASAN=1 -DCMAKE_BUILD_TYPE=RelWithDebInfo
"${BUILD_ROOT}/tool/awslc_bm"

# Run the "local" benchmark that was built with the AWS-LC FIPS benchmark, only do this once because this tool
# is always the same regardless of what additional external libcrypto is built
"${BUILD_ROOT}/tool/bssl" speed

build_openssl_1_0
echo "Testing ossl_bm with OpenSSL 1.0"
run_build -DOPENSSL_1_0_INSTALL_DIR="${install_dir}/openssl-1.0" -DASAN=1 -DCMAKE_BUILD_TYPE=RelWithDebInfo
"${BUILD_ROOT}/tool/ossl_1_0_bm"

build_openssl_1_1
echo "Testing ossl_bm with OpenSSL 1.1"
run_build -DOPENSSL_1_1_INSTALL_DIR="${install_dir}/openssl-1.1" -DASAN=1 -DCMAKE_BUILD_TYPE=RelWithDebInfo
"${BUILD_ROOT}/tool/ossl_1_1_bm"

build_openssl_3_0
echo "Testing ossl_bm with OpenSSL 3.0"
run_build -DOPENSSL_3_0_INSTALL_DIR="${install_dir}/openssl-3.0" -DASAN=1 -DCMAKE_BUILD_TYPE=RelWithDebInfo
"${BUILD_ROOT}/tool/ossl_3_0_bm"


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

# Please run from project root folder!
# You'll want to set the codebuild env variables set if running locally
source tests/ci/common_ssm_setup.sh

# cleanup code
cleanup() {
  set +e
  # kill ec2 instances after we're done w/ them
  for id in ${instance_ids};do
    aws ec2 terminate-instances --instance-ids "${id}"
  done

  # delete the various documents that we created
  for name in ${ssm_document_names};do
    aws ssm delete-document --name "${name}"
  done
}

# we wanna run the cleanup code on exit
trap cleanup EXIT

# print some information for reference
echo GitHub PR Number: "${CODEBUILD_WEBHOOK_TRIGGER}"
echo GitHub Commit Version: "${CODEBUILD_SOURCE_VERSION}"
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
echo AWS Account ID: "${AWS_ACCOUNT_ID}"
echo GitHub Repo Link: "${CODEBUILD_SOURCE_REPO_URL}"

# get information for ec2 instances
vpc_id="$(aws ec2 describe-vpcs --filter Name=tag:Name,Values=aws-lc-ci-bm-framework/aws-lc-ci-bm-framework-ec2-vpc --query Vpcs[*].VpcId --output text)"
sg_id="$(aws ec2 describe-security-groups --filter Name=vpc-id,Values="${vpc_id}" --filter Name=group-name,Values=bm_framework_ec2_sg --query SecurityGroups[*].GroupId --output text)"
subnet_id="$(aws ec2 describe-subnets --filter Name=vpc-id,Values="${vpc_id}" --filter Name=state,Values=available --filter Name=tag:Name,Values=aws-lc-ci-bm-framework/aws-lc-ci-bm-framework-ec2-vpc/PrivateSubnet1 --query Subnets[*].SubnetId --output text)"

#$1 is nohw type, $2 is OPENSSL_ia32cap value
generate_ssm_document_file() {
  # use sed to replace placeholder values inside preexisting document
  sed -e "s,{AWS_ACCOUNT_ID},${AWS_ACCOUNT_ID},g" \
    -e "s,{PR_NUM},${CODEBUILD_WEBHOOK_TRIGGER},g" \
    -e "s,{COMMIT_ID},${CODEBUILD_SOURCE_VERSION},g" \
    -e "s,{GITHUB_REPO},${CODEBUILD_SOURCE_REPO_URL},g" \
    -e "s,{OPENSSL_ia32cap},$2,g" \
    -e "s,{NOHW_TYPE},$1,g" \
    tests/ci/cdk/cdk/ssm/bm_framework_ssm_document.yaml \
    >tests/ci/cdk/cdk/ssm/bm_framework_"$1"_ssm_document.yaml
}

# create the ssm documents that will be used for the various ssm commands
generate_ssm_document_file "" ""
generate_ssm_document_file "nosha" "~0x100000000"
generate_ssm_document_file "noavx" "~0x1000000000000000:0xC0010020"

#$1 for ami, $2 for instance-type, echos the instance id so we can capture the output
create_ec2_instances() {
  local instance_id
  instance_id="$(aws ec2 run-instances --image-id "$1" --count 1 \
    --instance-type "$2" --security-group-ids "${sg_id}" --subnet-id "${subnet_id}" \
    --block-device-mappings 'DeviceName="/dev/sda1",Ebs={DeleteOnTermination=True,VolumeSize=200}' \
    --tag-specifications 'ResourceType="instance",Tags=[{Key="aws-lc",Value="aws-lc-ci-bm-framework-ec2-x86-instance"}]' \
    --iam-instance-profile Name=aws-lc-ci-bm-framework-ec2-profile \
    --placement 'AvailabilityZone=us-west-2a' \
    --query Instances[*].InstanceId --output text)"
  echo "${instance_id}"
}

# create ec2 instances for x86 and arm
x86_id=$(create_ec2_instances "ami-01773ce53581acf22" "c5.metal")
arm_id=$(create_ec2_instances "ami-018e246d8c0f39ae5" "c6g.metal")
x86_nosha_id=$(create_ec2_instances "ami-01773ce53581acf22" "m5.metal")
x86_noavx_id=$(create_ec2_instances "ami-01773ce53581acf22" "c5.metal")
instance_ids="${x86_id} ${arm_id} ${x86_nosha_id} ${x86_noavx_id}"

# if any of the ids are blank, ec2 creation failed
if [[ -z "${x86_id}" ]] || [[ -z "${arm_id}" ]] || [[ -z "${x86_nosha_id}" ]] || [[ -z "${x86_noavx_id}" ]];  then
  exit 1
fi

# Give a few minutes for the ec2 instances to be ready
sleep 60

for i in {1..30}; do
  ready=true
  for id in ${instance_ids}; do
    status=$(aws ssm describe-instance-information --filter Key="InstanceIds",Values="${id}" \
    --query InstanceInformationList[*].PingStatus --output text)
    if [ "${status}" != Online ]; then
      ready=false
    fi
  done
  if [ "${ready}" = true ]; then
    break
  fi
  echo "Wait for instances to be able to run the SSM commands"

  # if we've hit the 30 minute mark and still aren't ready, then something has gone wrong
  if [ "${i}" = 30 ]; then exit 1; fi
  sleep 60
done

# Create, and run ssm command for arm & x86
ssm_doc_name=$(create_ssm_document "bm_framework_")
nosha_ssm_doc_name=$(create_ssm_document "bm_framework_nosha")
noavx_ssm_doc_name=$(create_ssm_document "bm_framework_noavx")
ssm_document_names="${ssm_doc_name} ${nosha_ssm_doc_name} ${noavx_ssm_doc_name}"

# delete contents of 'latest' folders before uploading anything new to them
aws s3 rm s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/latest-${CODEBUILD_WEBHOOK_TRIGGER}" --recursive
aws s3 rm s3://"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-prod-bucket/latest" --recursive

cloudwatch_group_name="aws-lc-ci-bm-framework-cw-logs"
x86_ssm_command_id=$(run_ssm_command "${ssm_doc_name}" "${x86_id}" "${cloudwatch_group_name}")
arm_ssm_command_id=$(run_ssm_command "${ssm_doc_name}" "${arm_id}" "${cloudwatch_group_name}")
nosha_ssm_command_id=$(run_ssm_command "${nosha_ssm_doc_name}" "${x86_nosha_id}" "${cloudwatch_group_name}")
noavx_ssm_command_id=$(run_ssm_command "${noavx_ssm_doc_name}" "${x86_noavx_id}" "${cloudwatch_group_name}")
ssm_command_ids="${x86_ssm_command_id} ${arm_ssm_command_id} ${nosha_ssm_command_id} ${noavx_ssm_command_id}"

# Give some time for the commands to run
for i in {1..30}; do
  echo "${i}: Continue to wait 3 min for SSM commands to finish."
  sleep 180
  done=true
  success=true
  # for each command, check its status
  for id in ${ssm_command_ids}; do
    ssm_command_status="$(aws ssm list-commands --command-id "${id}" --query Commands[*].Status --output text)"
    ssm_target_count="$(aws ssm list-commands --command-id "${id}" --query Commands[*].TargetCount --output text)"
    ssm_completed_count="$(aws ssm list-commands --command-id "${id}" --query Commands[*].CompletedCount --output text)"
    if [[ ${ssm_command_status} == 'Success' && ${ssm_completed_count} == "${ssm_target_count}" ]]; then
      echo "SSM command ${id} finished successfully."
    elif [[ ${ssm_command_status} == 'Failed' && ${ssm_completed_count} == "${ssm_target_count}" ]]; then
      echo "SSM command ${id} failed."
      success=false
    else
      done=false
    fi
  done

  # if after the loop finish and done is still true, then we're done
  if [ "${done}" = true ]; then
    echo "All SSM commands have finished."

    # if success is still true here, then none of the commands failed
    if [ "${success}" != true ]; then
      echo "An SSM command failed!"
      exit 1
    fi
    break
  fi
done


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

# Sourcing these files check for environment variables which may be unset so wait to enable -u
source tests/ci/common_fuzz.sh
source "${FUZZ_ROOT}/fuzz_env.sh"
# After loading everything any undefined variables should fail the build
set -u

rm -rf "$BUILD_ROOT"
mkdir -p "$BUILD_ROOT"
cd "$BUILD_ROOT"

# Build AWS-LC based on https://github.com/guidovranken/cryptofuzz/blob/master/docs/openssl.md
${CMAKE_COMMAND} -DCMAKE_CXX_FLAGS="$CXXFLAGS" -DCMAKE_C_FLAGS="$CFLAGS" -DBORINGSSL_ALLOW_CXX_RUNTIME=1 \
  -GNinja -DBUILD_TESTING=OFF -DBUILD_LIBSSL=OFF -DCMAKE_BUILD_TYPE=RelWithDebInfo ../
ninja
cd ../

# CRYPTOFUZZ_AWSLC will enable AES_256_XTS in upstream code. See `V610453347`.
# TODO: remove CRYPTOFUZZ_BORINGSSL when CRYPTOFUZZ_AWSLC is fully integrated.
export CXXFLAGS="$CXXFLAGS -DCRYPTOFUZZ_BORINGSSL -DCRYPTOFUZZ_AWSLC"
export OPENSSL_INCLUDE_PATH=`realpath include/`
export OPENSSL_LIBCRYPTO_A_PATH=`realpath ${BUILD_ROOT}/crypto/libcrypto.a`

# For cryptofuzz development only, override CRYPTOFUZZ_SRC with CUSTOM_CRYPTOFUZZ_REPO_DIR.
CUSTOM_CRYPTOFUZZ_REPO_DIR=''
if [[ -z "${CUSTOM_CRYPTOFUZZ_REPO_DIR}" ]]; then
  echo "CUSTOM_CRYPTOFUZZ_REPO_DIR is empty."
else
  export CRYPTOFUZZ_SRC="${CUSTOM_CRYPTOFUZZ_REPO_DIR}"
  # Local development does not need differential fuzzing.
  # Remove these libs related build flags.
  export CXXFLAGS="${CXXFLAGS// -DCRYPTOFUZZ_BOTAN/}"
  export CXXFLAGS="${CXXFLAGS// -DCRYPTOFUZZ_CRYPTOPP/}"
  cd "$CRYPTOFUZZ_SRC"
  # This step is to generate required header and cpp files.
  python3 gen_repository.py
fi

# Build the common OpenSSL module with AWS-LC
cd "${CRYPTOFUZZ_SRC}/modules/openssl"
make "-j${NUM_CPU_THREADS}"

export CFLAGS="${CFLAGS} -I $OPENSSL_INCLUDE_PATH"
export CXXFLAGS="${CXXFLAGS} -I $OPENSSL_INCLUDE_PATH"
export LIBFUZZER_LINK="-fsanitize=fuzzer"

# Build the overall cryptofuzz and generate_corpus binary
cd "$CRYPTOFUZZ_SRC"
rm -rf cryptofuzz
rm -rf generate_corpus
make "-j${NUM_CPU_THREADS}" cryptofuzz generate_corpus

# Common AWS-LC fuzzing setup, the cryptofuzz binary is in this folder so FUZZ_TEST_PATH=FUZZ_NAME
FUZZ_NAME="cryptofuzz"
FUZZ_TEST_PATH="${CRYPTOFUZZ_SRC}/${FUZZ_NAME}"
SRC_CORPUS="$CRYPTOFUZZ_SEED_CORPUS"

# For cryptofuzz development only, uncomment below code to generate new corpus.
# rm -rf "$CRYPTOFUZZ_SEED_CORPUS" && mkdir "$CRYPTOFUZZ_SEED_CORPUS"
# ./generate_corpus "$CRYPTOFUZZ_SEED_CORPUS"

# Perform the actual fuzzing. We want the total build time to be about 45 minutes:
# 5 minutes for building AWS-LC and Cryptofuzz
# 16 minutes (1000 seconds) of fuzzing
# 24 minutes of cleanup and merging in new inputs
TIME_FOR_EACH_FUZZ=1000

# Some fuzz tests can take a while but still pass. This is a tradeoff: less false positive noise, but some inputs that take
# a long time could lead to a denial of service avenue. We're mostly interested in correctness and memory safety at this
# time so we're willing to take the fit on fuzz speed
FUZZ_TEST_TIMEOUT=30

# Call the common fuzzing logic
run_fuzz_test


#!/bin/bash -ex
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

echo "Testing AWS-LC shared library in FIPS Release mode."
fips_build_and_test -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=1

# Static FIPS build works only on Linux platforms.
if [[ ("$(uname -s)" == 'Linux'*) && (("$(uname -p)" == 'x86_64'*) || ("$(uname -p)" == 'aarch64'*)) ]]; then
  echo "Testing AWS-LC static library in FIPS Release mode."
  fips_build_and_test -DCMAKE_BUILD_TYPE=Release

  echo "Testing AWS-LC static breakable build"
  run_build -DFIPS=1 -DCMAKE_C_FLAGS="-DBORINGSSL_FIPS_BREAK_TESTS"
  cd $SRC_ROOT
  ./util/fipstools/test-break-kat.sh

  # These build parameters may be needed by our aws-lc-fips-sys Rust package
  run_build -DFIPS=1 -DBUILD_LIBSSL=OFF -DBUILD_TESTING=OFF
fi

# The AL2 version of Clang does not have all of the required artifacts for address sanitizer, see P45594051
if [[ "${AWSLC_NO_ASM_FIPS}" == "1" ]]; then
  if [[ ("$(uname -p)" == 'x86_64'*) ]]; then
    echo "Building with Clang and testing AWS-LC in FIPS Release mode with address sanitizer."
    fips_build_and_test -DASAN=1 -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=1
  else
    # See the comment in run_posix_santizers.sh for more context. ASAN on Arm has a huge performance impact on ssl_test
    # which causes it to take over 2 hours to complete.
    echo "Building with Clang and testing AWS-LC in FIPS Release mode with address sanitizer only running crypto_test"
    run_build -DFIPS=1 -DASAN=1 -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=1
    go run util/all_tests.go -build-dir "$BUILD_ROOT"
  fi
fi

echo "Testing shared AWS-LC in FIPS Debug mode in a different folder."
BUILD_ROOT=$(mktemp -d)
fips_build_and_test -DCMAKE_BUILD_TYPE=Debug -DBUILD_SHARED_LIBS=1


#!/bin/bash -ex
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

AWS_LC_DIR=${PWD##*/}
cd ../
ROOT=$(pwd)

rm -rf aws-lc-verification-build
git clone --recurse-submodules https://github.com/awslabs/aws-lc-verification.git aws-lc-verification-build
cd aws-lc-verification-build
# aws-lc-verification has aws-lc as one submodule under 'src' dir.
# Below is to copy code of **target** aws-lc to 'src' dir.
rm -rf ./src/* && cp -r "${ROOT}/${AWS_LC_DIR}/"* ./src
# execute the entry to saw scripts.
./SAW/scripts/docker_entrypoint.sh
cd ..
rm -rf aws-lc-verification-build


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

# Sourcing these files check for environment variables which may be unset so wait to enable -u
source tests/ci/common_fuzz.sh
# Running the build also checks for unset variables
run_build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DFUZZ=1 -DASAN=1 -DBUILD_TESTING=OFF
# After loading everything any undefined variables should fail the build
set -u
# We want our CI to take about 45 minutes:
# 2 minutes to build AWS-LC
# 25 minutes (1500 seconds) for all fuzzing
# 18 minutes for cleanup and merging files
if [[ $PLATFORM == "aarch64" ]]; then
  # Arm sanitizers are very slow which causes the clean up time to take longer per
  # fuzz test, only run for 16 minutes
  TOTAL_FUZZ_TEST_TIME=1000
else
  TOTAL_FUZZ_TEST_TIME=1500
fi

FUZZ_TEST_TIMEOUT=5

FUZZ_TESTS=$(find "${BUILD_ROOT}/fuzz" -type f -executable)
NUM_FUZZ_TESTS=$(echo "$FUZZ_TESTS" | wc -l)
TIME_FOR_EACH_FUZZ=$((TOTAL_FUZZ_TEST_TIME/NUM_FUZZ_TESTS))

for FUZZ_TEST_PATH in $FUZZ_TESTS;do
  FUZZ_NAME=$(basename "$FUZZ_TEST_PATH")
  SRC_CORPUS="${SRC_ROOT}/fuzz/${FUZZ_NAME}_corpus"

  run_fuzz_test
done


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

export CMAKE_BUILD_PARALLEL_LEVEL=${NUM_CPU_THREADS}

# Set up environment.

# ROOT
#  |
#  - AWS_LC_DIR
#  |
#  - SCRATCH_FOLDER
#    |
#    - BUILD_DIR
#    - install-shared
#    - install-static
#    - install-both
#    - MYAPP_SRC

# Assumes script is executed from the root of aws-lc directory
AWS_LC_DIR=$(pwd)
ROOT=$(realpath ${AWS_LC_DIR}/..)

SCRATCH_DIR=${ROOT}/SCRATCH_AWSLC_INSTALL_SHARED_AND_STATIC
mkdir -p ${SCRATCH_DIR}
rm -rf ${SCRATCH_DIR}/*

function fail() {
    echo "test failure: $1"
    exit 1
}

function install_aws_lc() {
    local INSTALL_DIR=${SCRATCH_DIR}/$1
    local BUILD_SHARED_LIBS=$2

    local BUILD_DIR=${SCRATCH_DIR}/build
    rm -rf ${BUILD_DIR}
    ${CMAKE_COMMAND} -H${AWS_LC_DIR} -B${BUILD_DIR} -GNinja -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF -D${BUILD_SHARED_LIBS}
    ${CMAKE_COMMAND} --build ${BUILD_DIR} --target install
}

# create installation with shared libssl.so/libcrypto.so
install_aws_lc install-shared BUILD_SHARED_LIBS=ON

# create installation with static libssl.a/libcrypto.a
install_aws_lc install-static BUILD_SHARED_LIBS=OFF

# create installation with both shared libssl.so/libcrypto.so and static libssl.a/libcrypto.a
install_aws_lc install-both BUILD_SHARED_LIBS=OFF
install_aws_lc install-both BUILD_SHARED_LIBS=ON

# write out source of a small cmake project, containing:
# - mylib: a library that uses AWS-LC
# - myapp: executable that uses mylib
MYAPP_SRC_DIR=${SCRATCH_DIR}/myapp-src
rm -rf ${MYAPP_SRC_DIR}
mkdir -p ${MYAPP_SRC_DIR}

cat <<EOF > ${MYAPP_SRC_DIR}/mylib.c
#include <openssl/ssl.h>
void mylib_init(void) {
    OPENSSL_init_ssl(0, NULL);
}
EOF

cat <<EOF > ${MYAPP_SRC_DIR}/myapp.c
extern void mylib_init(void);
int main() {
    mylib_init();
}
EOF

cat <<EOF > ${MYAPP_SRC_DIR}/CMakeLists.txt
cmake_minimum_required (VERSION 3.0)
project (myapp C)
add_library(mylib mylib.c)
find_package(ssl REQUIRED)
target_link_libraries(mylib PRIVATE AWS::ssl)
add_executable(myapp myapp.c)
target_link_libraries(myapp PRIVATE mylib)
EOF

# build myapp and mylib, confirm that expected type of libssl and libcrypto are used
build_myapp() {
    local BUILD_SHARED_LIBS=$1 # ("BUILD_SHARED_LIBS=ON" or "BUILD_SHARED_LIBS=OFF")
    local AWS_LC_INSTALL_DIR=$2 # which install dir should be used
    local EXPECT_USE_LIB_TYPE=$3 # (".so" or ".a") which types of libssl and libcrypto are expected to be used

    local BUILD_DIR=${SCRATCH_DIR}/build
    rm -rf ${BUILD_DIR}

    cmake -H${MYAPP_SRC_DIR} -B${BUILD_DIR} -GNinja -D${BUILD_SHARED_LIBS} -DCMAKE_PREFIX_PATH=${SCRATCH_DIR}/${AWS_LC_INSTALL_DIR}
    cmake --build ${BUILD_DIR}
    ldd ${BUILD_DIR}/myapp

    test_lib_use ${BUILD_DIR}/myapp libssl ${EXPECT_USE_LIB_TYPE}
    test_lib_use ${BUILD_DIR}/myapp libcrypto ${EXPECT_USE_LIB_TYPE}
}

# test that app is using expected library
test_lib_use() {
    local APP=$1 # app to examine
    local LIB_NAME=$2 # name of lib that app should be using, without file extension
    local EXPECT_USE_LIB_TYPE=$3 # (".so" or ".a") expected type of lib that app should be using

    if ldd ${APP} | grep -q ${LIB_NAME}.so; then
        local ACTUAL_USE_LIB_TYPE=.so
    else
        local ACTUAL_USE_LIB_TYPE=.a
    fi

    if [ ${ACTUAL_USE_LIB_TYPE} != ${EXPECT_USE_LIB_TYPE} ]; then
        fail "used ${LIB_NAME}${ACTUAL_USE_LIB_TYPE}, but expected to use ${LIB_NAME}${EXPECT_USE_LIB_TYPE}"
    fi
}

# if only shared libssl.so/libcrypto.so are available, that's what should get used
build_myapp BUILD_SHARED_LIBS=ON install-shared .so
build_myapp BUILD_SHARED_LIBS=OFF install-shared .so

# if only static libssl.a/libcrypto.a are available, that's what should get used
build_myapp BUILD_SHARED_LIBS=ON install-static .a
build_myapp BUILD_SHARED_LIBS=OFF install-static .a

# if both shared libssl.so/libcrypto.so and static libssl.a/libcrypto.a are available...
build_myapp BUILD_SHARED_LIBS=ON install-both .so # myapp should use libssl.so/libcrypto.so
build_myapp BUILD_SHARED_LIBS=OFF install-both .a # myapp should use libssl.a/libcrypto.a

# ------------------------------------------------------- #
#           Test for the static library constructor       #
# ------------------------------------------------------- #
rm -rf ${MYAPP_SRC_DIR}
mkdir -p ${MYAPP_SRC_DIR}

cat <<EOF > ${MYAPP_SRC_DIR}/static_constructor_test.c
#include <stdint.h>
#include "openssl/bn.h"
extern uint8_t OPENSSL_cpucap_initialized;
int main() {
  BIGNUM *a = BN_new();
  return (OPENSSL_cpucap_initialized == 1 ? 0 : 1);
}
EOF

# create installation with static libcrypto.a
install_aws_lc install-static BUILD_SHARED_LIBS=OFF

# compile the test app with libcrypto.a
${CC} ${MYAPP_SRC_DIR}/static_constructor_test.c ${SCRATCH_DIR}/install-static/lib/libcrypto.a -pthread -I${SCRATCH_DIR}/install-static/include -o ${MYAPP_SRC_DIR}/static_constructor_test

# verify that the test app returns success
${MYAPP_SRC_DIR}/static_constructor_test || fail "static library constructor has not been executed"


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

# gcc 4.1.3 is used in our CI because ubuntu 7.10's `gcc4.1.3` and
# `GNU assembler 2.18` resembles rhel5's binutils the most. SSE4
# assembly instructions are not supported in ubuntu 7.04, while rhel5
# and ubuntu 7.10 do.
echo "Testing gcc 4.1.2 / 4.1.3 support."

# Go is disabled because go tries to fetch from the server when building,
# but the certificates on the ancient ubuntu are expired and the ancient
# tools are insufficient to update the certificates.
# The build flags used are the same as our ancient internal build.
run_build  -DDISABLE_GO=ON -DBUILD_TESTING=OFF -DBUILD_LIBSSL=OFF -DCMAKE_BUILD_TYPE=Debug -DMY_ASSEMBLER_IS_TOO_OLD_FOR_AVX=ON -std=gnu99 -fgnu89-inline


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

# Please run from project root folder!
# You'll want to set the codebuild env variables set if running locally
source tests/ci/common_ssm_setup.sh

# cleanup code
cleanup() {
  set +e
  # delete the various documents that we created
  for name in ${ssm_document_names};do
    aws ssm delete-document --name "${name}"
  done
}

# we wanna run the cleanup code on exit
trap cleanup EXIT

# print some information for reference
echo GitHub PR Number: "${CODEBUILD_WEBHOOK_TRIGGER}"
echo GitHub Branch Name: "${CODEBUILD_WEBHOOK_HEAD_REF}"
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
echo AWS Account ID: "${AWS_ACCOUNT_ID}"
echo GitHub Repo Link: "${CODEBUILD_SOURCE_REPO_URL}"
export cloudwatch_group_name="aws-lc-ci-macos-arm-cw-logs"
export s3_bucket_name="aws-lc-codebuild"

# get information for ec2 instances
ec2_instance="$(aws ec2 describe-instances --filter "Name=tag:Name,Values=aws-lc-ci-macos-arm-ec2-instance" "Name=instance-state-name,Values=running" --query Reservations[*].Instances[*].InstanceId --output text)"

generate_ssm_document_file() {
  # use sed to replace placeholder values inside preexisting document
  sed -e "s,{AWS_ACCOUNT_ID},${AWS_ACCOUNT_ID},g" \
    -e "s,{PR_NUM},${CODEBUILD_WEBHOOK_TRIGGER//pr\/},g" \
    -e "s,{SOURCE},${CODEBUILD_SOURCE_REPO_URL},g" \
    -e "s,{S3_BUCKET},${s3_bucket_name},g" \
    tests/ci/cdk/cdk/ssm/m1_tests_ssm_document.yaml \
    >tests/ci/cdk/cdk/ssm/macos_arm_ssm_document.yaml
}

# create the ssm documents that will be used for the various ssm commands
generate_ssm_document_file

# Create, and run ssm command.
ssm_doc_name=$(create_ssm_document "macos_arm")
ssm_document_names="${ssm_doc_name}"

m1_ssm_command_id=$(run_ssm_command "${ssm_doc_name}" "${ec2_instance}" ${cloudwatch_group_name})

run_url="https://${AWS_REGION}.console.aws.amazon.com/cloudwatch/home?region=${AWS_REGION}\
#logsV2:log-groups/log-group/${cloudwatch_group_name}/log-events/\
${m1_ssm_command_id}\$252F${ec2_instance}\$252FrunShellScript\$252Fstdout"

echo "Actual Run in EC2 can be observered at CloudWatch URL: ${run_url}"

# Give some time for the commands to run
done=false
success=false
for i in {1..45}; do
  echo "${i}: Continue to wait 2 min for SSM commands to finish."
  sleep 120

  ssm_command_status="$(aws ssm list-commands --command-id "${m1_ssm_command_id}" --query Commands[*].Status --output text)"
  ssm_target_count="$(aws ssm list-commands --command-id "${m1_ssm_command_id}" --query Commands[*].TargetCount --output text)"
  ssm_completed_count="$(aws ssm list-commands --command-id "${m1_ssm_command_id}" --query Commands[*].CompletedCount --output text)"
  if [[ ${ssm_command_status} == 'Success' && ${ssm_completed_count} == "${ssm_target_count}" ]]; then
    echo "SSM command ${m1_ssm_command_id} finished successfully."
    success=true
    done=true
  elif [[ ${ssm_command_status} == 'Failed' && ${ssm_completed_count} == "${ssm_target_count}" ]]; then
    echo "SSM command ${m1_ssm_command_id} failed."
    done=true
  else
    # Still running.
    done=false
  fi

  # if after the loop finish and done is still true, then we're done
  if [ "${done}" = true ]; then
    echo "M1 SSM command has finished."

    # if success is still true here, then none of the commands failed
    if [ "${success}" == true ]; then
      echo "M1 SSM command succeeded!"
      exit 0
    else
      echo "M1 SSM command failed!"
      exit 1
    fi
    break
  fi
done
exit 1


#!/bin/bash -ex
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

echo "Testing AWS-LC without Go in debug mode."
build_and_run_minimal_test -DDISABLE_GO=ON

echo "Testing AWS-LC without Go in release mode."
build_and_run_minimal_test -DDISABLE_GO=ON -DCMAKE_BUILD_TYPE=Release

echo "Testing shared lib AWS-LC without Go in release mode."
build_and_run_minimal_test -DDISABLE_GO=ON -DBUILD_SHARED_LIBS=1 -DCMAKE_BUILD_TYPE=Release

# build AWS-LC without Perl/Go.
echo "Testing AWS-LC without Perl/Go in debug mode."
build_and_run_minimal_test -DDISABLE_GO=ON -DDISABLE_PERL=ON

echo "Testing AWS-LC without Perl/Go in release mode."
build_and_run_minimal_test -DDISABLE_GO=ON -DDISABLE_PERL=ON -DCMAKE_BUILD_TYPE=Release

echo "Testing shared lib AWS-LC without Perl/Go in release mode."
build_and_run_minimal_test -DDISABLE_GO=ON -DDISABLE_PERL=ON -DBUILD_SHARED_LIBS=1 -DCMAKE_BUILD_TYPE=Release


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

build_type=Release
cflags=("-DCMAKE_BUILD_TYPE=${build_type}")
if [ $(uname -p) == "aarch64" ]; then
  # BoringSSL provides two sets tests: the C/C++ tests and the blackbox tests.
  # Details: https://github.com/google/boringssl/blob/master/BUILDING.md
  # The blackbox tests (run `go test` under `ssl/test/runner`) take 30 minutes to complete on ARM when ASAN clang flag enabled.
  # But the blackbox tests take less than 2 minutes to complete on other test dimensions -- X86 ASAN and ARM (when ASAN disabled).
  # Instead of running the two sets tests, only the former test is executed here. ssl runner tests are covered by |run_ssl_asan_tests.sh|.
  # https://github.com/google/sanitizers/issues/1331
  echo "Building AWS-LC in ${build_type} mode with address sanitizer, and running only non ssl test."
  run_build -DASAN=1 "${cflags[@]}"
  go run util/all_tests.go -build-dir "$BUILD_ROOT"
else
  echo "Testing AWS-LC in ${build_type} mode with address sanitizer."
  build_and_test -DASAN=1 "${cflags[@]}"
fi

echo "Testing AWS-LC in ${build_type} mode with control flow integrity sanitizer."
build_and_test -DCFI=1 "${cflags[@]}"

echo "Testing AWS-LC in ${build_type} mode with undefined behavior sanitizer."
export UBSAN_OPTIONS=print_stacktrace=1
build_and_test -DUBSAN=1 "${cflags[@]}"
unset UBSAN_OPTIONS

if [ $(uname -p) == "aarch64" ]; then
  # ARM MSAN runs get stuck on PoolTest.Threads for over an hour https://github.com/aws/aws-lc/issues/13
  echo "Building AWS-LC in ${build_type} mode with memory sanitizer."
  run_build -DMSAN=1 -DUSE_CUSTOM_LIBCXX=1 "${cflags[@]}"
else
  echo "Testing AWS-LC in ${build_type} mode with memory sanitizer."
  build_and_test -DMSAN=1 -DUSE_CUSTOM_LIBCXX=1 "${cflags[@]}"
fi

if [ $(uname -p) == "x86_64" ]; then
  # x86 TSAN runs get stuck on PoolTest.Threads for over an hour https://github.com/aws/aws-lc/issues/13
  echo "Building AWS-LC in ${build_type} mode with thread sanitizer."
  run_build -DTSAN=1 -DUSE_CUSTOM_LIBCXX=1 "${cflags[@]}"
else
  echo "Testing AWS-LC in ${build_type} mode with thread sanitizer."
  build_and_test -DTSAN=1 -DUSE_CUSTOM_LIBCXX=1 "${cflags[@]}"
fi


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

echo "Testing AWS-LC in debug mode."
build_and_test

echo "Testing AWS-LC in release mode."
build_and_test -DCMAKE_BUILD_TYPE=Release

echo "Testing AWS-LC with Dilithium3 enabled."
build_and_test -DENABLE_DILITHIUM=ON

echo "Testing AWS-LC small compilation."
build_and_test -DOPENSSL_SMALL=1 -DCMAKE_BUILD_TYPE=Release

echo "Testing AWS-LC with libssl off."
build_and_test -DBUILD_LIBSSL=OFF -DCMAKE_BUILD_TYPE=Release

echo "Testing AWS-LC in no asm mode."
build_and_test -DOPENSSL_NO_ASM=1 -DCMAKE_BUILD_TYPE=Release

echo "Testing building shared lib."
build_and_test -DBUILD_SHARED_LIBS=1 -DCMAKE_BUILD_TYPE=Release

if [[ "${AWSLC_C99_TEST}" == "1" ]]; then
    echo "Testing the C99 compatability of AWS-LC headers."
    ./tests/coding_guidelines/c99_gcc_test.sh
fi

if [[ "${AWSLC_CODING_GUIDELINES_TEST}" == "1" ]]; then
  echo "Testing that AWS-LC is compliant with the coding guidelines."
  source ./tests/coding_guidelines/coding_guidelines_test.sh
fi

# Lightly verify that uncommon build options does not break the build. Fist
# define a list of typical build options to verify the special build option with
build_options_to_test=("" "-DBUILD_SHARED_LIBS=1" "-DCMAKE_BUILD_TYPE=Release" "-DBUILD_SHARED_LIBS=1 -DCMAKE_BUILD_TYPE=Release")

## Build option: MY_ASSEMBLER_IS_TOO_OLD_FOR_AVX
for build_option in "${build_options_to_test[@]}"; do
  run_build ${build_option} -DMY_ASSEMBLER_IS_TOO_OLD_FOR_AVX=ON
done

## Build option: MY_ASSEMBLER_IS_TOO_OLD_FOR_512AVX
for build_option in "${build_options_to_test[@]}"; do
  run_build ${build_option} -DMY_ASSEMBLER_IS_TOO_OLD_FOR_512AVX=ON
done


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

echo "Testing a prefix build of AWS-LC in debug mode."
build_prefix_and_test

echo "Testing a prefix build of AWS-LC in release mode."
build_prefix_and_test -DCMAKE_BUILD_TYPE=Release

echo "Testing a prefix build of AWS-LC small compilation."
build_prefix_and_test -DOPENSSL_SMALL=1 -DCMAKE_BUILD_TYPE=Release

echo "Testing a prefix build of AWS-LC in no asm mode."
build_prefix_and_test -DOPENSSL_NO_ASM=1 -DCMAKE_BUILD_TYPE=Release


#!/bin/bash
set -exo pipefail
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

# BoringSSL has 7k+ ssl runner tests, and the total number of the runner tests keep increasing.
# When ASAN enabled, the tests take more than 1 hour to finish. The cause relates to https://github.com/google/sanitizers/issues/1331
# To reduce the total time, these tests will be executed in diff CodeBuild dimensions.
# Env var |AWS_LC_SSL_RUNNER_START_INDEX| and |AWS_LC_SSL_RUNNER_END_INDEX| will be used with this script to split runner tests.
source tests/ci/common_posix_setup.sh

build_type=Release
cflags=("-DCMAKE_BUILD_TYPE=${build_type}")

if [ $(uname -p) == "aarch64" ]; then
  echo "Executing AWS-LC SSL runner tests in ${build_type} mode with address sanitizer."
  run_build -DASAN=1 "${cflags[@]}"
  run_cmake_custom_target 'run_ssl_runner_tests'
fi


#!/bin/bash -ex
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

echo "Testing AWS-LC in debug mode under Valgrind."
build_and_test_ssl_runner_valgrind


#!/bin/bash -ex
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

echo "Testing AWS-LC in debug mode under Intel's SDE."
build_and_test_with_sde

echo "Testing AWS-LC in release mode under Intel's SDE."
build_and_test_with_sde -DCMAKE_BUILD_TYPE=Release


#!/bin/bash -ex
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR ISC

source tests/ci/common_posix_setup.sh

echo "Testing AWS-LC in debug mode under Valgrind."
build_and_test_valgrind