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>
37 /* The test function is normally called `do_test' and it is called
38 with argc and argv as the arguments. We nevertheless provide the
39 possibility to overwrite this name.
41 The TEST_FUNCTION expression should have a type of 'int' and should
42 return 0 to indicate a passing test, 1 to indicate a failing test,
43 or 77 to indicate an unsupported test. Other result values could be
44 used to indicate a failing test, but the result of the expression
45 is passed to exit and exit only returns the lower 8 bits of its input.
46 A non-zero return with some values could cause a test to incorrectly
47 be considered passing when it really failed. For this reason the
48 expression should always return 0, 1, or 77.
50 The test function may print out diagnostic or warning messages as well
51 as messages about failures. These messages should be printed to stdout
52 and not stderr so that the output is properly ordered with respect to
53 the rest of the glibc testsuite run output. */
56 # define TEST_FUNCTION do_test (argc, argv)
59 #ifndef TEST_DATA_LIMIT
60 # define TEST_DATA_LIMIT (64 << 20) /* Data limit (bytes) to run with. */
64 /* Default timeout is twenty seconds. Tests should normally complete faster
65 than this, but if they don't, that's abnormal (a bug) anyways. */
69 #define OPT_DIRECT 1000
70 #define OPT_TESTDIR 1001
72 static struct option options
[] =
74 #ifdef CMDLINE_OPTIONS
77 { "direct", no_argument
, NULL
, OPT_DIRECT
},
78 { "test-dir", required_argument
, NULL
, OPT_TESTDIR
},
82 /* PID of the test itself. */
85 /* Directory to place temporary files in. */
86 static const char *test_dir
;
89 printf ("error: %s:%d: ", __FILE__, __LINE__); \
90 printf (__VA_ARGS__); \
93 #define FAIL_RET(...) \
95 _FAIL (__VA_ARGS__); \
99 #define FAIL_EXIT(value, ...) \
101 _FAIL (__VA_ARGS__); \
105 #define FAIL_EXIT1(...) FAIL_EXIT(1, __VA_ARGS__)
108 oom_error (const char *fn
, size_t size
)
110 printf ("%s: unable to allocate %zu bytes: %m\n", fn
, size
);
114 /* Allocate N bytes of memory dynamically, with error checking. */
115 __attribute__ ((unused
))
123 oom_error ("malloc", n
);
127 /* Allocate memory for N elements of S bytes, with error checking. */
128 __attribute__ ((unused
))
130 xcalloc (size_t n
, size_t s
)
136 oom_error ("calloc", n
* s
);
140 /* Change the size of an allocated block of memory P to N bytes,
141 with error checking. */
142 __attribute__ ((unused
))
144 xrealloc (void *p
, size_t n
)
146 void *result
= realloc (p
, n
);
147 if (result
== NULL
&& (n
> 0 || p
== NULL
))
148 oom_error ("realloc", n
);
152 /* Call asprintf with error checking. */
153 __attribute__ ((always_inline
, format (printf
, 1, 2)))
154 static __inline__
char *
155 xasprintf (const char *format
, ...)
158 if (asprintf (&result
, format
, __builtin_va_arg_pack ()) < 0)
160 printf ("error: asprintf: %m\n");
166 /* Write a message to standard output. Can be used in signal
169 __attribute__ ((unused
))
170 write_message (const char *message
)
172 ssize_t unused
__attribute__ ((unused
));
173 unused
= write (STDOUT_FILENO
, message
, strlen (message
));
176 /* List of temporary files. */
177 struct temp_name_list
183 /* Add temporary files in list. */
185 __attribute__ ((unused
))
186 add_temp_file (const char *name
)
188 struct temp_name_list
*newp
189 = (struct temp_name_list
*) xcalloc (sizeof (*newp
), 1);
190 char *newname
= strdup (name
);
193 newp
->name
= newname
;
194 if (temp_name_list
== NULL
)
195 temp_name_list
= (struct temp_name_list
*) &newp
->q
;
197 insque (newp
, temp_name_list
);
203 /* Delete all temporary files. */
205 delete_temp_files (void)
207 while (temp_name_list
!= NULL
)
209 remove (temp_name_list
->name
);
210 free (temp_name_list
->name
);
212 struct temp_name_list
*next
213 = (struct temp_name_list
*) temp_name_list
->q
.q_forw
;
214 free (temp_name_list
);
215 temp_name_list
= next
;
219 /* Create a temporary file. Return the opened file descriptor on
220 success, or -1 on failure. Write the file name to *FILENAME if
221 FILENAME is not NULL. In this case, the caller is expected to free
224 __attribute__ ((unused
))
225 create_temp_file (const char *base
, char **filename
)
230 fname
= (char *) xmalloc (strlen (test_dir
) + 1 + strlen (base
)
231 + sizeof ("XXXXXX"));
232 strcpy (stpcpy (stpcpy (stpcpy (fname
, test_dir
), "/"), base
), "XXXXXX");
234 fd
= mkstemp (fname
);
237 printf ("cannot open temporary file '%s': %m\n", fname
);
242 add_temp_file (fname
);
243 if (filename
!= NULL
)
251 /* Timeout handler. We kill the child and exit with an error. */
253 __attribute__ ((noreturn
))
254 signal_handler (int sig
__attribute__ ((unused
)))
260 /* Kill the whole process group. */
261 kill (-pid
, SIGKILL
);
262 /* In case setpgid failed in the child, kill it individually too. */
265 /* Wait for it to terminate. */
267 for (i
= 0; i
< 5; ++i
)
269 killed
= waitpid (pid
, &status
, WNOHANG
|WUNTRACED
);
273 /* Delay, give the system time to process the kill. If the
274 nanosleep() call return prematurely, all the better. We
275 won't restart it since this probably means the child process
279 ts
.tv_nsec
= 100000000;
280 nanosleep (&ts
, NULL
);
282 if (killed
!= 0 && killed
!= pid
)
284 printf ("Failed to kill test process: %m\n");
288 #ifdef CLEANUP_HANDLER
294 signal (sig
, SIG_DFL
);
298 /* If we expected this signal: good! */
299 #ifdef EXPECTED_SIGNAL
300 if (EXPECTED_SIGNAL
== SIGALRM
)
304 if (killed
== 0 || (WIFSIGNALED (status
) && WTERMSIG (status
) == SIGKILL
))
305 puts ("Timed out: killed the child process");
306 else if (WIFSTOPPED (status
))
307 printf ("Timed out: the child process was %s\n",
308 strsignal (WSTOPSIG (status
)));
309 else if (WIFSIGNALED (status
))
310 printf ("Timed out: the child process got signal %s\n",
311 strsignal (WTERMSIG (status
)));
313 printf ("Timed out: killed the child process but it exited %d\n",
314 WEXITSTATUS (status
));
316 /* Exit with an error. */
320 /* Avoid all the buffer overflow messages on stderr. */
322 __attribute__ ((unused
))
325 int fd
= open (_PATH_DEVNULL
, O_WRONLY
);
327 close (STDERR_FILENO
);
330 dup2 (fd
, STDERR_FILENO
);
333 setenv ("LIBC_FATAL_STDERR_", "1", 1);
336 /* Set fortification error handler. Used when tests want to verify that bad
337 code is caught by the library. */
339 __attribute__ ((unused
))
340 set_fortify_handler (void (*handler
) (int sig
))
344 sa
.sa_handler
= handler
;
346 sigemptyset (&sa
.sa_mask
);
348 sigaction (SIGABRT
, &sa
, NULL
);
352 /* Show people how to run the program. */
358 printf ("Usage: %s [options]\n"
360 "Environment Variables:\n"
361 " TIMEOUTFACTOR An integer used to scale the timeout\n"
362 " TMPDIR Where to place temporary files\n"
364 program_invocation_short_name
);
365 printf ("Options:\n");
366 for (i
= 0; options
[i
].name
; ++i
)
370 indent
= printf (" --%s", options
[i
].name
);
371 if (options
[i
].has_arg
== required_argument
)
372 indent
+= printf (" <arg>");
373 printf ("%*s", 25 - indent
, "");
374 switch (options
[i
].val
)
377 printf ("Run the test directly (instead of forking & monitoring)");
380 printf ("Override the TMPDIR env var");
387 /* We provide the entry point here. */
389 main (int argc
, char *argv
[])
391 int direct
= 0; /* Directly call the test function? */
394 unsigned int timeoutfactor
= 1;
397 #ifndef TEST_NO_MALLOPT
398 /* Make uses of freed and uninitialized memory known. */
399 mallopt (M_PERTURB
, 42);
402 #ifdef STDOUT_UNBUFFERED
403 setbuf (stdout
, NULL
);
406 while ((opt
= getopt_long (argc
, argv
, "+", options
, NULL
)) != -1)
418 #ifdef CMDLINE_PROCESS
423 /* If set, read the test TIMEOUTFACTOR value from the environment.
424 This value is used to scale the default test timeout values. */
425 char *envstr_timeoutfactor
= getenv ("TIMEOUTFACTOR");
426 if (envstr_timeoutfactor
!= NULL
)
428 char *envstr_conv
= envstr_timeoutfactor
;
429 unsigned long int env_fact
;
431 env_fact
= strtoul (envstr_timeoutfactor
, &envstr_conv
, 0);
432 if (*envstr_conv
== '\0' && envstr_conv
!= envstr_timeoutfactor
)
433 timeoutfactor
= MAX (env_fact
, 1);
436 /* Set TMPDIR to specified test directory. */
437 if (test_dir
!= NULL
)
439 setenv ("TMPDIR", test_dir
, 1);
441 if (chdir (test_dir
) < 0)
443 printf ("chdir: %m\n");
449 test_dir
= getenv ("TMPDIR");
450 if (test_dir
== NULL
|| test_dir
[0] == '\0')
454 /* Make sure we see all message, even those on stdout. */
455 setvbuf (stdout
, NULL
, _IONBF
, 0);
457 /* Make sure temporary files are deleted. */
458 atexit (delete_temp_files
);
460 /* Correct for the possible parameters. */
461 argv
[optind
- 1] = argv
[0];
465 /* Call the initializing function, if one is available. */
467 PREPARE (argc
, argv
);
470 const char *envstr_direct
= getenv ("TEST_DIRECT");
471 if (envstr_direct
!= NULL
)
473 FILE *f
= fopen (envstr_direct
, "w");
476 printf ("cannot open TEST_DIRECT output file '%s': %m\n",
481 fprintf (f
, "timeout=%u\ntimeoutfactor=%u\n", TIMEOUT
, timeoutfactor
);
482 #ifdef EXPECTED_STATUS
483 fprintf (f
, "exit=%u\n", EXPECTED_STATUS
);
485 #ifdef EXPECTED_SIGNAL
486 switch (EXPECTED_SIGNAL
)
489 # define init_sig(signo, name, text) \
490 case signo: fprintf (f, "signal=%s\n", name); break;
491 # include <siglist.h>
496 if (temp_name_list
!= NULL
)
498 struct temp_name_list
*n
;
499 fprintf (f
, "temp_files=(\n");
500 for (n
= temp_name_list
;
502 n
= (struct temp_name_list
*) n
->q
.q_forw
)
503 fprintf (f
, " '%s'\n", n
->name
);
511 /* If we are not expected to fork run the function immediately. */
513 return TEST_FUNCTION
;
515 /* Set up the test environment:
518 - fork and execute the function. */
523 /* This is the child. */
525 /* Try to avoid dumping core. */
526 struct rlimit core_limit
;
527 core_limit
.rlim_cur
= 0;
528 core_limit
.rlim_max
= 0;
529 setrlimit (RLIMIT_CORE
, &core_limit
);
532 /* We put the test process in its own pgrp so that if it bogusly
533 generates any job control signals, they won't hit the whole build. */
534 if (setpgid (0, 0) != 0)
535 printf ("Failed to set the process group ID: %m\n");
537 /* Execute the test function and exit with the return value. */
538 exit (TEST_FUNCTION
);
542 printf ("Cannot fork test program: %m\n");
547 signal (SIGALRM
, signal_handler
);
548 alarm (TIMEOUT
* timeoutfactor
);
550 /* Make sure we clean up if the wrapper gets interrupted. */
551 signal (SIGINT
, signal_handler
);
553 /* Wait for the regular termination. */
554 termpid
= TEMP_FAILURE_RETRY (waitpid (pid
, &status
, 0));
557 printf ("Waiting for test program failed: %m\n");
562 printf ("Oops, wrong test program terminated: expected %ld, got %ld\n",
563 (long int) pid
, (long int) termpid
);
567 /* Process terminated normaly without timeout etc. */
568 if (WIFEXITED (status
))
570 #ifndef EXPECTED_STATUS
571 # ifndef EXPECTED_SIGNAL
572 /* Simply exit with the return value of the test. */
573 return WEXITSTATUS (status
);
575 printf ("Expected signal '%s' from child, got none\n",
576 strsignal (EXPECTED_SIGNAL
));
580 if (WEXITSTATUS (status
) != EXPECTED_STATUS
)
582 printf ("Expected status %d, got %d\n",
583 EXPECTED_STATUS
, WEXITSTATUS (status
));
590 /* Process was killed by timer or other signal. */
593 #ifndef EXPECTED_SIGNAL
594 printf ("Didn't expect signal from child: got `%s'\n",
595 strsignal (WTERMSIG (status
)));
598 if (WTERMSIG (status
) != EXPECTED_SIGNAL
)
600 printf ("Incorrect signal from child: got `%s', need `%s'\n",
601 strsignal (WTERMSIG (status
)),
602 strsignal (EXPECTED_SIGNAL
));
611 /* The following functionality is only available if <pthread.h> was
612 included before this file. */
615 /* Call pthread_sigmask with error checking. */
617 xpthread_sigmask (int how
, const sigset_t
*set
, sigset_t
*oldset
)
619 if (pthread_sigmask (how
, set
, oldset
) != 0)
621 write_message ("error: pthread_setmask failed\n");
626 /* Call pthread_mutex_lock with error checking. */
627 __attribute__ ((unused
))
629 xpthread_mutex_lock (pthread_mutex_t
*mutex
)
631 int ret
= pthread_mutex_lock (mutex
);
635 printf ("error: pthread_mutex_lock: %m\n");
640 /* Call pthread_spin_lock with error checking. */
641 __attribute__ ((unused
))
643 xpthread_spin_lock (pthread_spinlock_t
*lock
)
645 int ret
= pthread_spin_lock (lock
);
649 printf ("error: pthread_spin_lock: %m\n");
654 /* Call pthread_cond_wait with error checking. */
655 __attribute__ ((unused
))
657 xpthread_cond_wait (pthread_cond_t
* cond
,
658 pthread_mutex_t
* mutex
)
660 int ret
= pthread_cond_wait (cond
, mutex
);
664 printf ("error: pthread_cond_wait: %m\n");
669 /* Call pthread_barrier_wait with error checking. */
670 __attribute__ ((unused
))
672 xpthread_barrier_wait (pthread_barrier_t
*barrier
)
674 int ret
= pthread_barrier_wait (barrier
);
675 if (ret
!= 0 && ret
!= PTHREAD_BARRIER_SERIAL_THREAD
)
678 printf ("error: pthread_barrier_wait: %m\n");
684 /* Call pthread_create with error checking. */
686 xpthread_create (pthread_attr_t
*attr
,
687 void *(*thread_func
) (void *), void *closure
)
690 int ret
= pthread_create (&thr
, attr
, thread_func
, closure
);
694 printf ("error: pthread_create: %m\n");
700 /* Call pthread_detach with error checking. */
702 xpthread_detach (pthread_t thr
)
704 int ret
= pthread_detach (thr
);
708 printf ("error: pthread_detach: %m\n");
713 /* Call pthread_join with error checking. */
714 __attribute__ ((unused
))
716 xpthread_join (pthread_t thr
)
719 int ret
= pthread_join (thr
, &result
);
723 printf ("error: pthread_join: %m\n");
729 /* Used to implement the delayed_exit function defined below. */
731 delayed_exit_thread (void *seconds_as_ptr
)
733 int seconds
= (uintptr_t) seconds_as_ptr
;
734 struct timespec delay
= { seconds
, 0 };
735 struct timespec remaining
= { 0 };
736 if (nanosleep (&delay
, &remaining
) != 0)
738 printf ("error: nanosleep: %m\n");
741 /* Exit the process sucessfully. */
746 /* Exit (with status 0) after SECONDS have elapsed, from a helper
747 thread. The process is terminated with the exit function, so
748 atexit handlers are executed. */
749 __attribute__ ((unused
))
751 delayed_exit (int seconds
)
753 /* Create the new thread with all signals blocked. */
754 sigset_t all_blocked
;
755 sigfillset (&all_blocked
);
757 xpthread_sigmask (SIG_SETMASK
, &all_blocked
, &old_set
);
758 /* Create a detached thread. */
759 pthread_t thr
= xpthread_create
760 (NULL
, delayed_exit_thread
, (void *) (uintptr_t) seconds
);
761 xpthread_detach (thr
);
762 /* Restore the original signal mask. */
763 xpthread_sigmask (SIG_SETMASK
, &old_set
, NULL
);
766 #endif /* _PTHREAD_H */