init.sh: enable MALLOC_PERTURB_
[gnulib.git] / tests / init.sh
1 # source this file; set up for tests
2
3 # Copyright (C) 2009, 2010 Free Software Foundation, Inc.
4
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 # Using this file in a test
19 # =========================
20 #
21 # The typical skeleton of a test looks like this:
22 #
23 #   #!/bin/sh
24 #   . "${srcdir=.}/init.sh"; path_prepend_ .
25 #   Execute some commands.
26 #   Note that these commands are executed in a subdirectory, therefore you
27 #   need to prepend "../" to relative filenames in the build directory.
28 #   Note that the "path_prepend_ ." is useful only if the body of your
29 #   test invokes programs residing in the initial directory.
30 #   For example, if the programs you want to test are in src/, and this test
31 #   script is named tests/test-1, then you would use "path_prepend_ ../src",
32 #   or perhaps export PATH='$(abs_top_builddir)/src$(PATH_SEPARATOR)'"$$PATH"
33 #   to all tests via automake's TESTS_ENVIRONMENT.
34 #   Set the exit code 0 for success, 77 for skipped, or 1 or other for failure.
35 #   Use the skip_ and fail_ functions to print a diagnostic and then exit
36 #   with the corresponding exit code.
37 #   Exit $?
38
39 # Executing a test that uses this file
40 # ====================================
41 #
42 # Running a single test:
43 #   $ make check TESTS=test-foo.sh
44 #
45 # Running a single test, with verbose output:
46 #   $ make check TESTS=test-foo.sh VERBOSE=yes
47 #
48 # Running a single test, with single-stepping:
49 #   1. Go into a sub-shell:
50 #   $ bash
51 #   2. Set relevant environment variables from TESTS_ENVIRONMENT in the
52 #      Makefile:
53 #   $ export srcdir=../../tests # this is an example
54 #   3. Execute the commands from the test, copy&pasting them one by one:
55 #   $ . "$srcdir/init.sh"; path_prepend_ .
56 #   ...
57 #   4. Finally
58 #   $ exit
59
60 # We require $(...) support unconditionally.
61 # We require a few additional shell features only when $EXEEXT is nonempty,
62 # in order to support automatic $EXEEXT emulation:
63 # - hyphen-containing alias names
64 # - we prefer to use ${var#...} substitution, rather than having
65 #   to work around lack of support for that feature.
66 # The following code attempts to find a shell with support for these features
67 # and re-exec's it.  If not, it skips the current test.
68
69 gl_shell_test_script_='
70 test $(echo y) = y || exit 1
71 test -z "$EXEEXT" && exit 0
72 shopt -s expand_aliases
73 alias a-b="echo zoo"
74 v=abx
75      test ${v%x} = ab \
76   && test ${v#a} = bx \
77   && test $(a-b) = zoo
78 '
79
80 if test "x$1" = "x--no-reexec"; then
81   shift
82 else
83   for re_shell_ in "${CONFIG_SHELL:-no_shell}" /bin/sh bash dash zsh pdksh fail
84   do
85     test "$re_shell_" = no_shell && continue
86     test "$re_shell_" = fail && skip_ failed to find an adequate shell
87     if "$re_shell_" -c "$gl_shell_test_script_" 2>/dev/null; then
88       exec "$re_shell_" "$0" --no-reexec "$@"
89       echo "$ME_: exec failed" 1>&2
90       exit 127
91     fi
92   done
93 fi
94
95 test -n "$EXEEXT" && shopt -s expand_aliases
96
97 # Enable glibc's malloc-perturbing option.
98 # This is cheap and useful for exposing code that depends on the fact that
99 # malloc-related functions often return memory that is mostly zeroed.
100 # If you have the time and cycles, use valgrind to do an even better job.
101 ${MALLOC_PERTURB_=87}
102 export MALLOC_PERTURB_
103
104 # We use a trap below for cleanup.  This requires us to go through
105 # hoops to get the right exit status transported through the handler.
106 # So use `Exit STATUS' instead of `exit STATUS' inside of the tests.
107 # Turn off errexit here so that we don't trip the bug with OSF1/Tru64
108 # sh inside this function.
109 Exit () { set +e; (exit $1); exit $1; }
110
111 # Print warnings (e.g., about skipped and failed tests) to this file number.
112 # Override by defining to say, 9, in init.cfg, and putting say,
113 # "export ...ENVVAR_SETTINGS...; exec 9>&2; $(SHELL)" in the definition
114 # of TESTS_ENVIRONMENT in your tests/Makefile.am file.
115 # This is useful when using automake's parallel tests mode, to print
116 # the reason for skip/failure to console, rather than to the .log files.
117 : ${stderr_fileno_=2}
118
119 warn_() { echo "$@" 1>&$stderr_fileno_; }
120 fail_() { warn_ "$ME_: failed test: $@"; Exit 1; }
121 skip_() { warn_ "$ME_: skipped test: $@"; Exit 77; }
122 framework_failure_() { warn_ "$ME_: set-up failure: $@"; Exit 1; }
123
124 # This is a stub function that is run upon trap (upon regular exit and
125 # interrupt).  Override it with a per-test function, e.g., to unmount
126 # a partition, or to undo any other global state changes.
127 cleanup_() { :; }
128
129 if ( diff --version < /dev/null 2>&1 | grep GNU ) 2>&1 > /dev/null; then
130   compare() { diff -u "$@"; }
131 elif ( cmp --version < /dev/null 2>&1 | grep GNU ) 2>&1 > /dev/null; then
132   compare() { cmp -s "$@"; }
133 else
134   compare() { cmp "$@"; }
135 fi
136
137 # An arbitrary prefix to help distinguish test directories.
138 testdir_prefix_() { printf gt; }
139
140 # Run the user-overridable cleanup_ function, remove the temporary
141 # directory and exit with the incoming value of $?.
142 remove_tmp_()
143 {
144   __st=$?
145   cleanup_
146   # cd out of the directory we're about to remove
147   cd "$initial_cwd_" || cd / || cd /tmp
148   chmod -R u+rwx "$test_dir_"
149   # If removal fails and exit status was to be 0, then change it to 1.
150   rm -rf "$test_dir_" || { test $__st = 0 && __st=1; }
151   exit $__st
152 }
153
154 # Given a directory name, DIR, if every entry in it that matches *.exe
155 # contains only the specified bytes (see the case stmt below), then print
156 # a space-separated list of those names and return 0.  Otherwise, don't
157 # print anything and return 1.  Naming constraints apply also to DIR.
158 find_exe_basenames_()
159 {
160   feb_dir_=$1
161   feb_fail_=0
162   feb_result_=
163   feb_sp_=
164   for feb_file_ in $feb_dir_/*.exe; do
165     case $feb_file_ in
166       *[!-a-zA-Z/0-9_.+]*) feb_fail_=1; break;;
167       *) # Remove leading file name components as well as the .exe suffix.
168          feb_file_=${feb_file_##*/}
169          feb_file_=${feb_file_%.exe}
170          feb_result_="$feb_result_$feb_sp_$feb_file_";;
171     esac
172     feb_sp_=' '
173   done
174   test $feb_fail_ = 0 && printf %s "$feb_result_"
175   return $feb_fail_
176 }
177
178 # Consider the files in directory, $1.
179 # For each file name of the form PROG.exe, create an alias named
180 # PROG that simply invokes PROG.exe, then return 0.  If any selected
181 # file name or the directory name, $1, contains an unexpected character,
182 # define no function and return 1.
183 create_exe_shims_()
184 {
185   case $EXEEXT in
186     '') return 0 ;;
187     .exe) ;;
188     *) echo "$0: unexpected \$EXEEXT value: $EXEEXT" 1>&2; return 1 ;;
189   esac
190
191   base_names_=`find_exe_basenames_ $1` \
192     || { echo "$0 (exe_shim): skipping directory: $1" 1>&2; return 1; }
193
194   if test -n "$base_names_"; then
195     for base_ in $base_names_; do
196       alias "$base_"="$base_$EXEEXT"
197     done
198   fi
199
200   return 0
201 }
202
203 # Use this function to prepend to PATH an absolute name for each
204 # specified, possibly-$initial_cwd_-relative, directory.
205 path_prepend_()
206 {
207   while test $# != 0; do
208     path_dir_=$1
209     case $path_dir_ in
210       '') fail_ "invalid path dir: '$1'";;
211       /*) abs_path_dir_=$path_dir_;;
212       *) abs_path_dir_=`cd "$initial_cwd_/$path_dir_" && echo "$PWD"` \
213            || fail_ "invalid path dir: $path_dir_";;
214     esac
215     case $abs_path_dir_ in
216       *:*) fail_ "invalid path dir: '$abs_path_dir_'";;
217     esac
218     PATH="$abs_path_dir_:$PATH"
219
220     # Create an alias, FOO, for each FOO.exe in this directory.
221     create_exe_shims_ "$abs_path_dir_" \
222       || fail_ "something failed (above): $abs_path_dir_"
223     shift
224   done
225   export PATH
226 }
227
228 setup_()
229 {
230   test "$VERBOSE" = yes && set -x
231
232   initial_cwd_=$PWD
233   ME_=`expr "./$0" : '.*/\(.*\)$'`
234
235   pfx_=`testdir_prefix_`
236   test_dir_=`mktempd_ "$initial_cwd_" "$pfx_-$ME_.XXXX"` \
237     || fail_ "failed to create temporary directory in $initial_cwd_"
238   cd "$test_dir_"
239
240   # These trap statements ensure that the temporary directory, $test_dir_,
241   # is removed upon exit as well as upon receipt of any of the listed signals.
242   trap remove_tmp_ 0
243   for sig_ in 1 2 3 13 15; do
244     eval "trap 'Exit $(expr $sig_ + 128)' $sig_"
245   done
246 }
247
248 # Create a temporary directory, much like mktemp -d does.
249 # Written by Jim Meyering.
250 #
251 # Usage: mktempd_ /tmp phoey.XXXXXXXXXX
252 #
253 # First, try to use the mktemp program.
254 # Failing that, we'll roll our own mktemp-like function:
255 #  - try to get random bytes from /dev/urandom
256 #  - failing that, generate output from a combination of quickly-varying
257 #      sources and gzip.  Ignore non-varying gzip header, and extract
258 #      "random" bits from there.
259 #  - given those bits, map to file-name bytes using tr, and try to create
260 #      the desired directory.
261 #  - make only $MAX_TRIES_ attempts
262
263 # Helper function.  Print $N pseudo-random bytes from a-zA-Z0-9.
264 rand_bytes_()
265 {
266   n_=$1
267
268   # Maybe try openssl rand -base64 $n_prime_|tr '+/=\012' abcd first?
269   # But if they have openssl, they probably have mktemp, too.
270
271   chars_=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
272   dev_rand_=/dev/urandom
273   if test -r "$dev_rand_"; then
274     # Note: 256-length($chars_) == 194; 3 copies of $chars_ is 186 + 8 = 194.
275     dd ibs=$n_ count=1 if=$dev_rand_ 2>/dev/null \
276       | LC_ALL=C tr -c $chars_ 01234567$chars_$chars_$chars_
277     return
278   fi
279
280   n_plus_50_=`expr $n_ + 50`
281   cmds_='date; date +%N; free; who -a; w; ps auxww; ps ef; netstat -n'
282   data_=` (eval "$cmds_") 2>&1 | gzip `
283
284   # Ensure that $data_ has length at least 50+$n_
285   while :; do
286     len_=`echo "$data_"|wc -c`
287     test $n_plus_50_ -le $len_ && break;
288     data_=` (echo "$data_"; eval "$cmds_") 2>&1 | gzip `
289   done
290
291   echo "$data_" \
292     | dd bs=1 skip=50 count=$n_ 2>/dev/null \
293     | LC_ALL=C tr -c $chars_ 01234567$chars_$chars_$chars_
294 }
295
296 mktempd_()
297 {
298   case $# in
299   2);;
300   *) fail_ "Usage: $ME DIR TEMPLATE";;
301   esac
302
303   destdir_=$1
304   template_=$2
305
306   MAX_TRIES_=4
307
308   # Disallow any trailing slash on specified destdir:
309   # it would subvert the post-mktemp "case"-based destdir test.
310   case $destdir_ in
311   /) ;;
312   */) fail_ "invalid destination dir: remove trailing slash(es)";;
313   esac
314
315   case $template_ in
316   *XXXX) ;;
317   *) fail_ "invalid template: $template_ (must have a suffix of at least 4 X's)";;
318   esac
319
320   fail=0
321
322   # First, try to use mktemp.
323   d=`unset TMPDIR; mktemp -d -t -p "$destdir_" "$template_" 2>/dev/null` \
324     || fail=1
325
326   # The resulting name must be in the specified directory.
327   case $d in "$destdir_"*);; *) fail=1;; esac
328
329   # It must have created the directory.
330   test -d "$d" || fail=1
331
332   # It must have 0700 permissions.  Handle sticky "S" bits.
333   perms=`ls -dgo "$d" 2>/dev/null|tr S -` || fail=1
334   case $perms in drwx------*) ;; *) fail=1;; esac
335
336   test $fail = 0 && {
337     echo "$d"
338     return
339   }
340
341   # If we reach this point, we'll have to create a directory manually.
342
343   # Get a copy of the template without its suffix of X's.
344   base_template_=`echo "$template_"|sed 's/XX*$//'`
345
346   # Calculate how many X's we've just removed.
347   template_length_=`echo "$template_" | wc -c`
348   nx_=`echo "$base_template_" | wc -c`
349   nx_=`expr $template_length_ - $nx_`
350
351   err_=
352   i_=1
353   while :; do
354     X_=`rand_bytes_ $nx_`
355     candidate_dir_="$destdir_/$base_template_$X_"
356     err_=`mkdir -m 0700 "$candidate_dir_" 2>&1` \
357       && { echo "$candidate_dir_"; return; }
358     test $MAX_TRIES_ -le $i_ && break;
359     i_=`expr $i_ + 1`
360   done
361   fail_ "$err_"
362 }
363
364 # If you want to override the testdir_prefix_ function,
365 # or to add more utility functions, use this file.
366 test -f "$srcdir/init.cfg" \
367   && . "$srcdir/init.cfg"
368
369 setup_ "$@"