blob: fcd0752850b7d6576321499ca8a378353e3fbec0 [file] [log] [blame]
Gilles Peskined1b5f6f2020-04-23 17:33:36 +02001## Common shell functions used by demo scripts programs/*/*.sh.
2
3## How to write a demo script
4## ==========================
5##
6## Include this file near the top of each demo script:
7## . "${0%/*}/../demo_common.sh"
8##
9## As the last thing in the script, call the cleanup function.
10##
11## You can use the functions and variables described below.
12
13set -e -u
14
15## $root_dir is the root directory of the Mbed TLS source tree.
16root_dir="${0%/*}"
17n=4 # limit the search depth
18while ! [ -d "$root_dir/programs" ] || ! [ -d "$root_dir/library" ]; do
19 if [ $n -eq 0 ]; then
20 echo >&2 "This doesn't seem to be an Mbed TLS source tree."
21 exit 125
22 fi
23 n=$((n - 1))
24 case $root_dir in
25 .) root_dir="..";;
26 ..|?*/..) root_dir="$root_dir/..";;
27 ?*/*) root_dir="${root_dir%/*}";;
28 /*) root_dir="/";;
29 *) root_dir=".";;
30 esac
31done
32
33## $programs_dir is the directory containing the sample programs.
34programs_dir="$root_dir/programs"
35
36## msg LINE...
37## msg <TEXT_ORIGIN
38## Display an informational message.
39msg () {
40 if [ $# -eq 0 ]; then
41 sed 's/^/# /'
42 else
43 for x in "$@"; do
44 echo "# $x"
45 done
46 fi
47}
48
49## run "Message" COMMAND ARGUMENT...
50## Display the message, then run COMMAND with the specified arguments.
51run () {
52 echo
53 echo "# $1"
54 shift
55 echo "+ $*"
56 "$@"
57}
58
59## Like '!', but stop on failure with 'set -e'
60not () {
61 if "$@"; then false; fi
62}
63
64## run_bad "Message" COMMAND ARGUMENT...
65## Like run, but the command is expected to fail.
66run_bad () {
67 echo
68 echo "$1 This must fail."
69 shift
70 echo "+ ! $*"
71 not "$@"
72}
73
Gilles Peskine958be362020-04-23 17:50:26 +020074## config_has SYMBOL...
75## Succeeds if the library configuration has all SYMBOLs set.
76config_has () {
77 for x in "$@"; do
78 "$programs_dir/test/query_compile_time_config" "$x"
79 done
80}
81
Gilles Peskined1b5f6f2020-04-23 17:33:36 +020082## Add the names of files to clean up to this whitespace-separated variable.
83## The file names must not contain whitespace characters.
84files_to_clean=
85
86
87
88################################################################
89## End of the public interfaces. Code beyond this point is not
90## meant to be called directly from a demo script.
91
92cleanup () {
93 rm -f -- $files_to_clean
94}
95trap 'cleanup; trap - HUP; kill -HUP $$' HUP
96trap 'cleanup; trap - INT; kill -INT $$' INT
97trap 'cleanup; trap - TERM; kill -TERM $$' TERM
Gilles Peskine958be362020-04-23 17:50:26 +020098
99if config_has MBEDTLS_ENTROPY_NV_SEED; then
100 # Create a seedfile that's sufficiently long in all library configurations.
101 # This is necessary for programs that use randomness.
102 # Assume that the name of the seedfile is the default name.
103 files_to_clean="$files_to_clean seedfile"
104 dd if=/dev/urandom of=seedfile ibs=64 obs=64 count=1
105fi