1 /* Skeleton for test programs.
2 Copyright (C) 1998-2016 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <http://www.gnu.org/licenses/>. */
32 #include <sys/resource.h>
34 #include <sys/param.h>
38 /* The test function is normally called `do_test' and it is called
39 with argc and argv as the arguments. We nevertheless provide the
40 possibility to overwrite this name. */
42 # define TEST_FUNCTION do_test (argc, argv)
45 #ifndef TEST_DATA_LIMIT
46 # define TEST_DATA_LIMIT (64 << 20) /* Data limit (bytes) to run with. */
50 /* Default timeout is twenty seconds. Tests should normally complete faster
51 than this, but if they don't, that's abnormal (a bug) anyways. */
55 #define OPT_DIRECT 1000
56 #define OPT_TESTDIR 1001
58 static struct option options
[] =
60 #ifdef CMDLINE_OPTIONS
63 { "direct", no_argument
, NULL
, OPT_DIRECT
},
64 { "test-dir", required_argument
, NULL
, OPT_TESTDIR
},
68 /* PID of the test itself. */
71 /* Directory to place temporary files in. */
72 static const char *test_dir
;
75 oom_error (const char *fn
, size_t size
)
77 printf ("%s: unable to allocate %zu bytes: %m\n", fn
, size
);
81 /* Allocate N bytes of memory dynamically, with error checking. */
82 __attribute__ ((unused
))
90 oom_error ("malloc", n
);
94 /* Allocate memory for N elements of S bytes, with error checking. */
95 __attribute__ ((unused
))
97 xcalloc (size_t n
, size_t s
)
103 oom_error ("calloc", n
* s
);
107 /* Change the size of an allocated block of memory P to N bytes,
108 with error checking. */
109 __attribute__ ((unused
))
111 xrealloc (void *p
, size_t n
)
113 void *result
= realloc (p
, n
);
114 if (result
== NULL
&& (n
> 0 || p
== NULL
))
115 oom_error ("realloc", n
);
119 /* Call asprintf with error checking. */
120 __attribute__ ((always_inline
, format (printf
, 1, 2)))
121 static __inline__
char *
122 xasprintf (const char *format
, ...)
125 if (asprintf (&result
, format
, __builtin_va_arg_pack ()) < 0)
127 printf ("error: asprintf: %m\n");
133 /* Write a message to standard output. Can be used in signal
136 __attribute__ ((unused
))
137 write_message (const char *message
)
139 ssize_t unused
__attribute__ ((unused
));
140 unused
= write (STDOUT_FILENO
, message
, strlen (message
));
143 /* List of temporary files. */
144 struct temp_name_list
150 /* Add temporary files in list. */
152 __attribute__ ((unused
))
153 add_temp_file (const char *name
)
155 struct temp_name_list
*newp
156 = (struct temp_name_list
*) xcalloc (sizeof (*newp
), 1);
157 char *newname
= strdup (name
);
160 newp
->name
= newname
;
161 if (temp_name_list
== NULL
)
162 temp_name_list
= (struct temp_name_list
*) &newp
->q
;
164 insque (newp
, temp_name_list
);
170 /* Delete all temporary files. */
172 delete_temp_files (void)
174 while (temp_name_list
!= NULL
)
176 remove (temp_name_list
->name
);
177 free (temp_name_list
->name
);
179 struct temp_name_list
*next
180 = (struct temp_name_list
*) temp_name_list
->q
.q_forw
;
181 free (temp_name_list
);
182 temp_name_list
= next
;
186 /* Create a temporary file. Return the opened file descriptor on
187 success, or -1 on failure. Write the file name to *FILENAME if
188 FILENAME is not NULL. In this case, the caller is expected to free
191 __attribute__ ((unused
))
192 create_temp_file (const char *base
, char **filename
)
197 fname
= (char *) xmalloc (strlen (test_dir
) + 1 + strlen (base
)
198 + sizeof ("XXXXXX"));
199 strcpy (stpcpy (stpcpy (stpcpy (fname
, test_dir
), "/"), base
), "XXXXXX");
201 fd
= mkstemp (fname
);
204 printf ("cannot open temporary file '%s': %m\n", fname
);
209 add_temp_file (fname
);
210 if (filename
!= NULL
)
218 /* Timeout handler. We kill the child and exit with an error. */
220 __attribute__ ((noreturn
))
221 signal_handler (int sig
__attribute__ ((unused
)))
227 /* Kill the whole process group. */
228 kill (-pid
, SIGKILL
);
229 /* In case setpgid failed in the child, kill it individually too. */
232 /* Wait for it to terminate. */
234 for (i
= 0; i
< 5; ++i
)
236 killed
= waitpid (pid
, &status
, WNOHANG
|WUNTRACED
);
240 /* Delay, give the system time to process the kill. If the
241 nanosleep() call return prematurely, all the better. We
242 won't restart it since this probably means the child process
246 ts
.tv_nsec
= 100000000;
247 nanosleep (&ts
, NULL
);
249 if (killed
!= 0 && killed
!= pid
)
251 printf ("Failed to kill test process: %m\n");
255 #ifdef CLEANUP_HANDLER
261 signal (sig
, SIG_DFL
);
265 /* If we expected this signal: good! */
266 #ifdef EXPECTED_SIGNAL
267 if (EXPECTED_SIGNAL
== SIGALRM
)
271 if (killed
== 0 || (WIFSIGNALED (status
) && WTERMSIG (status
) == SIGKILL
))
272 puts ("Timed out: killed the child process");
273 else if (WIFSTOPPED (status
))
274 printf ("Timed out: the child process was %s\n",
275 strsignal (WSTOPSIG (status
)));
276 else if (WIFSIGNALED (status
))
277 printf ("Timed out: the child process got signal %s\n",
278 strsignal (WTERMSIG (status
)));
280 printf ("Timed out: killed the child process but it exited %d\n",
281 WEXITSTATUS (status
));
283 /* Exit with an error. */
287 /* Avoid all the buffer overflow messages on stderr. */
289 __attribute__ ((unused
))
292 int fd
= open (_PATH_DEVNULL
, O_WRONLY
);
294 close (STDERR_FILENO
);
297 dup2 (fd
, STDERR_FILENO
);
300 setenv ("LIBC_FATAL_STDERR_", "1", 1);
303 /* Set fortification error handler. Used when tests want to verify that bad
304 code is caught by the library. */
306 __attribute__ ((unused
))
307 set_fortify_handler (void (*handler
) (int sig
))
311 sa
.sa_handler
= handler
;
313 sigemptyset (&sa
.sa_mask
);
315 sigaction (SIGABRT
, &sa
, NULL
);
319 /* Show people how to run the program. */
325 printf ("Usage: %s [options]\n"
327 "Environment Variables:\n"
328 " TIMEOUTFACTOR An integer used to scale the timeout\n"
329 " TMPDIR Where to place temporary files\n"
331 program_invocation_short_name
);
332 printf ("Options:\n");
333 for (i
= 0; options
[i
].name
; ++i
)
337 indent
= printf (" --%s", options
[i
].name
);
338 if (options
[i
].has_arg
== required_argument
)
339 indent
+= printf (" <arg>");
340 printf ("%*s", 25 - indent
, "");
341 switch (options
[i
].val
)
344 printf ("Run the test directly (instead of forking & monitoring)");
347 printf ("Override the TMPDIR env var");
354 /* We provide the entry point here. */
356 main (int argc
, char *argv
[])
358 int direct
= 0; /* Directly call the test function? */
361 unsigned int timeoutfactor
= 1;
364 #ifndef TEST_NO_MALLOPT
365 /* Make uses of freed and uninitialized memory known. */
366 mallopt (M_PERTURB
, 42);
369 #ifdef STDOUT_UNBUFFERED
370 setbuf (stdout
, NULL
);
373 while ((opt
= getopt_long (argc
, argv
, "+", options
, NULL
)) != -1)
385 #ifdef CMDLINE_PROCESS
390 /* If set, read the test TIMEOUTFACTOR value from the environment.
391 This value is used to scale the default test timeout values. */
392 char *envstr_timeoutfactor
= getenv ("TIMEOUTFACTOR");
393 if (envstr_timeoutfactor
!= NULL
)
395 char *envstr_conv
= envstr_timeoutfactor
;
396 unsigned long int env_fact
;
398 env_fact
= strtoul (envstr_timeoutfactor
, &envstr_conv
, 0);
399 if (*envstr_conv
== '\0' && envstr_conv
!= envstr_timeoutfactor
)
400 timeoutfactor
= MAX (env_fact
, 1);
403 /* Set TMPDIR to specified test directory. */
404 if (test_dir
!= NULL
)
406 setenv ("TMPDIR", test_dir
, 1);
408 if (chdir (test_dir
) < 0)
410 printf ("chdir: %m\n");
416 test_dir
= getenv ("TMPDIR");
417 if (test_dir
== NULL
|| test_dir
[0] == '\0')
421 /* Make sure we see all message, even those on stdout. */
422 setvbuf (stdout
, NULL
, _IONBF
, 0);
424 /* Make sure temporary files are deleted. */
425 atexit (delete_temp_files
);
427 /* Correct for the possible parameters. */
428 argv
[optind
- 1] = argv
[0];
432 /* Call the initializing function, if one is available. */
434 PREPARE (argc
, argv
);
437 const char *envstr_direct
= getenv ("TEST_DIRECT");
438 if (envstr_direct
!= NULL
)
440 FILE *f
= fopen (envstr_direct
, "w");
443 printf ("cannot open TEST_DIRECT output file '%s': %m\n",
448 fprintf (f
, "timeout=%u\ntimeoutfactor=%u\n", TIMEOUT
, timeoutfactor
);
449 #ifdef EXPECTED_STATUS
450 fprintf (f
, "exit=%u\n", EXPECTED_STATUS
);
452 #ifdef EXPECTED_SIGNAL
453 switch (EXPECTED_SIGNAL
)
456 # define init_sig(signo, name, text) \
457 case signo: fprintf (f, "signal=%s\n", name); break;
458 # include <siglist.h>
463 if (temp_name_list
!= NULL
)
465 struct temp_name_list
*n
;
466 fprintf (f
, "temp_files=(\n");
467 for (n
= temp_name_list
;
469 n
= (struct temp_name_list
*) n
->q
.q_forw
)
470 fprintf (f
, " '%s'\n", n
->name
);
478 /* If we are not expected to fork run the function immediately. */
480 return TEST_FUNCTION
;
482 /* Set up the test environment:
485 - fork and execute the function. */
490 /* This is the child. */
492 /* Try to avoid dumping core. */
493 struct rlimit core_limit
;
494 core_limit
.rlim_cur
= 0;
495 core_limit
.rlim_max
= 0;
496 setrlimit (RLIMIT_CORE
, &core_limit
);
499 /* We put the test process in its own pgrp so that if it bogusly
500 generates any job control signals, they won't hit the whole build. */
501 if (setpgid (0, 0) != 0)
502 printf ("Failed to set the process group ID: %m\n");
504 /* Execute the test function and exit with the return value. */
505 exit (TEST_FUNCTION
);
509 printf ("Cannot fork test program: %m\n");
514 signal (SIGALRM
, signal_handler
);
515 alarm (TIMEOUT
* timeoutfactor
);
517 /* Make sure we clean up if the wrapper gets interrupted. */
518 signal (SIGINT
, signal_handler
);
520 /* Wait for the regular termination. */
521 termpid
= TEMP_FAILURE_RETRY (waitpid (pid
, &status
, 0));
524 printf ("Waiting for test program failed: %m\n");
529 printf ("Oops, wrong test program terminated: expected %ld, got %ld\n",
530 (long int) pid
, (long int) termpid
);
534 /* Process terminated normaly without timeout etc. */
535 if (WIFEXITED (status
))
537 #ifndef EXPECTED_STATUS
538 # ifndef EXPECTED_SIGNAL
539 /* Simply exit with the return value of the test. */
540 return WEXITSTATUS (status
);
542 printf ("Expected signal '%s' from child, got none\n",
543 strsignal (EXPECTED_SIGNAL
));
547 if (WEXITSTATUS (status
) != EXPECTED_STATUS
)
549 printf ("Expected status %d, got %d\n",
550 EXPECTED_STATUS
, WEXITSTATUS (status
));
557 /* Process was killed by timer or other signal. */
560 #ifndef EXPECTED_SIGNAL
561 printf ("Didn't expect signal from child: got `%s'\n",
562 strsignal (WTERMSIG (status
)));
565 if (WTERMSIG (status
) != EXPECTED_SIGNAL
)
567 printf ("Incorrect signal from child: got `%s', need `%s'\n",
568 strsignal (WTERMSIG (status
)),
569 strsignal (EXPECTED_SIGNAL
));
578 /* The following functionality is only available if <pthread.h> was
579 included before this file. */
582 /* Call pthread_sigmask with error checking. */
584 xpthread_sigmask (int how
, const sigset_t
*set
, sigset_t
*oldset
)
586 if (pthread_sigmask (how
, set
, oldset
) != 0)
588 write_message ("error: pthread_setmask failed\n");
593 /* Call pthread_mutex_lock with error checking. */
594 __attribute__ ((unused
))
596 xpthread_mutex_lock (pthread_mutex_t
*mutex
)
598 int ret
= pthread_mutex_lock (mutex
);
602 printf ("error: pthread_mutex_lock: %m\n");
607 /* Call pthread_spin_lock with error checking. */
608 __attribute__ ((unused
))
610 xpthread_spin_lock (pthread_spinlock_t
*lock
)
612 int ret
= pthread_spin_lock (lock
);
616 printf ("error: pthread_spin_lock: %m\n");
621 /* Call pthread_cond_wait with error checking. */
622 __attribute__ ((unused
))
624 xpthread_cond_wait (pthread_cond_t
* cond
,
625 pthread_mutex_t
* mutex
)
627 int ret
= pthread_cond_wait (cond
, mutex
);
631 printf ("error: pthread_cond_wait: %m\n");
636 /* Call pthread_barrier_wait with error checking. */
637 __attribute__ ((unused
))
639 xpthread_barrier_wait (pthread_barrier_t
*barrier
)
641 int ret
= pthread_barrier_wait (barrier
);
642 if (ret
!= 0 && ret
!= PTHREAD_BARRIER_SERIAL_THREAD
)
645 printf ("error: pthread_barrier_wait: %m\n");
651 /* Call pthread_create with error checking. */
653 xpthread_create (pthread_attr_t
*attr
,
654 void *(*thread_func
) (void *), void *closure
)
657 int ret
= pthread_create (&thr
, attr
, thread_func
, closure
);
661 printf ("error: pthread_create: %m\n");
667 /* Call pthread_detach with error checking. */
669 xpthread_detach (pthread_t thr
)
671 int ret
= pthread_detach (thr
);
675 printf ("error: pthread_detach: %m\n");
680 /* Call pthread_join with error checking. */
681 __attribute__ ((unused
))
683 xpthread_join (pthread_t thr
)
686 int ret
= pthread_join (thr
, &result
);
690 printf ("error: pthread_join: %m\n");
696 /* Used to implement the delayed_exit function defined below. */
698 delayed_exit_thread (void *seconds_as_ptr
)
700 int seconds
= (uintptr_t) seconds_as_ptr
;
701 struct timespec delay
= { seconds
, 0 };
702 struct timespec remaining
= { 0 };
703 if (nanosleep (&delay
, &remaining
) != 0)
705 printf ("error: nanosleep: %m\n");
708 /* Exit the process sucessfully. */
713 /* Exit (with status 0) after SECONDS have elapsed, from a helper
714 thread. The process is terminated with the exit function, so
715 atexit handlers are executed. */
716 __attribute__ ((unused
))
718 delayed_exit (int seconds
)
720 /* Create the new thread with all signals blocked. */
721 sigset_t all_blocked
;
722 sigfillset (&all_blocked
);
724 xpthread_sigmask (SIG_SETMASK
, &all_blocked
, &old_set
);
725 /* Create a detached thread. */
726 pthread_t thr
= xpthread_create
727 (NULL
, delayed_exit_thread
, (void *) (uintptr_t) seconds
);
728 xpthread_detach (thr
);
729 /* Restore the original signal mask. */
730 xpthread_sigmask (SIG_SETMASK
, &old_set
, NULL
);
733 #endif /* _PTHREAD_H */