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 # define TEST_FUNCTION do_test (argc, argv)
44 #ifndef TEST_DATA_LIMIT
45 # define TEST_DATA_LIMIT (64 << 20) /* Data limit (bytes) to run with. */
49 /* Default timeout is twenty seconds. Tests should normally complete faster
50 than this, but if they don't, that's abnormal (a bug) anyways. */
54 #define OPT_DIRECT 1000
55 #define OPT_TESTDIR 1001
57 static struct option options
[] =
59 #ifdef CMDLINE_OPTIONS
62 { "direct", no_argument
, NULL
, OPT_DIRECT
},
63 { "test-dir", required_argument
, NULL
, OPT_TESTDIR
},
67 /* PID of the test itself. */
70 /* Directory to place temporary files in. */
71 static const char *test_dir
;
74 printf ("error: %s:%d: ", __FILE__, __LINE__); \
75 printf (__VA_ARGS__); \
78 #define FAIL_RET(...) \
80 _FAIL (__VA_ARGS__); \
84 #define FAIL_EXIT(value, ...) \
86 _FAIL (__VA_ARGS__); \
90 #define FAIL_EXIT1(...) FAIL_EXIT(1, __VA_ARGS__)
93 oom_error (const char *fn
, size_t size
)
95 printf ("%s: unable to allocate %zu bytes: %m\n", fn
, size
);
99 /* Allocate N bytes of memory dynamically, with error checking. */
100 __attribute__ ((unused
))
108 oom_error ("malloc", n
);
112 /* Allocate memory for N elements of S bytes, with error checking. */
113 __attribute__ ((unused
))
115 xcalloc (size_t n
, size_t s
)
121 oom_error ("calloc", n
* s
);
125 /* Change the size of an allocated block of memory P to N bytes,
126 with error checking. */
127 __attribute__ ((unused
))
129 xrealloc (void *p
, size_t n
)
131 void *result
= realloc (p
, n
);
132 if (result
== NULL
&& (n
> 0 || p
== NULL
))
133 oom_error ("realloc", n
);
137 /* Call asprintf with error checking. */
138 __attribute__ ((always_inline
, format (printf
, 1, 2)))
139 static __inline__
char *
140 xasprintf (const char *format
, ...)
143 if (asprintf (&result
, format
, __builtin_va_arg_pack ()) < 0)
145 printf ("error: asprintf: %m\n");
151 /* Write a message to standard output. Can be used in signal
154 __attribute__ ((unused
))
155 write_message (const char *message
)
157 ssize_t unused
__attribute__ ((unused
));
158 unused
= write (STDOUT_FILENO
, message
, strlen (message
));
161 /* List of temporary files. */
162 struct temp_name_list
168 /* Add temporary files in list. */
170 __attribute__ ((unused
))
171 add_temp_file (const char *name
)
173 struct temp_name_list
*newp
174 = (struct temp_name_list
*) xcalloc (sizeof (*newp
), 1);
175 char *newname
= strdup (name
);
178 newp
->name
= newname
;
179 if (temp_name_list
== NULL
)
180 temp_name_list
= (struct temp_name_list
*) &newp
->q
;
182 insque (newp
, temp_name_list
);
188 /* Delete all temporary files. */
190 delete_temp_files (void)
192 while (temp_name_list
!= NULL
)
194 remove (temp_name_list
->name
);
195 free (temp_name_list
->name
);
197 struct temp_name_list
*next
198 = (struct temp_name_list
*) temp_name_list
->q
.q_forw
;
199 free (temp_name_list
);
200 temp_name_list
= next
;
204 /* Create a temporary file. Return the opened file descriptor on
205 success, or -1 on failure. Write the file name to *FILENAME if
206 FILENAME is not NULL. In this case, the caller is expected to free
209 __attribute__ ((unused
))
210 create_temp_file (const char *base
, char **filename
)
215 fname
= (char *) xmalloc (strlen (test_dir
) + 1 + strlen (base
)
216 + sizeof ("XXXXXX"));
217 strcpy (stpcpy (stpcpy (stpcpy (fname
, test_dir
), "/"), base
), "XXXXXX");
219 fd
= mkstemp (fname
);
222 printf ("cannot open temporary file '%s': %m\n", fname
);
227 add_temp_file (fname
);
228 if (filename
!= NULL
)
236 /* Timeout handler. We kill the child and exit with an error. */
238 __attribute__ ((noreturn
))
239 signal_handler (int sig
__attribute__ ((unused
)))
245 /* Kill the whole process group. */
246 kill (-pid
, SIGKILL
);
247 /* In case setpgid failed in the child, kill it individually too. */
250 /* Wait for it to terminate. */
252 for (i
= 0; i
< 5; ++i
)
254 killed
= waitpid (pid
, &status
, WNOHANG
|WUNTRACED
);
258 /* Delay, give the system time to process the kill. If the
259 nanosleep() call return prematurely, all the better. We
260 won't restart it since this probably means the child process
264 ts
.tv_nsec
= 100000000;
265 nanosleep (&ts
, NULL
);
267 if (killed
!= 0 && killed
!= pid
)
269 printf ("Failed to kill test process: %m\n");
273 #ifdef CLEANUP_HANDLER
279 signal (sig
, SIG_DFL
);
283 /* If we expected this signal: good! */
284 #ifdef EXPECTED_SIGNAL
285 if (EXPECTED_SIGNAL
== SIGALRM
)
289 if (killed
== 0 || (WIFSIGNALED (status
) && WTERMSIG (status
) == SIGKILL
))
290 puts ("Timed out: killed the child process");
291 else if (WIFSTOPPED (status
))
292 printf ("Timed out: the child process was %s\n",
293 strsignal (WSTOPSIG (status
)));
294 else if (WIFSIGNALED (status
))
295 printf ("Timed out: the child process got signal %s\n",
296 strsignal (WTERMSIG (status
)));
298 printf ("Timed out: killed the child process but it exited %d\n",
299 WEXITSTATUS (status
));
301 /* Exit with an error. */
305 /* Avoid all the buffer overflow messages on stderr. */
307 __attribute__ ((unused
))
310 int fd
= open (_PATH_DEVNULL
, O_WRONLY
);
312 close (STDERR_FILENO
);
315 dup2 (fd
, STDERR_FILENO
);
318 setenv ("LIBC_FATAL_STDERR_", "1", 1);
321 /* Set fortification error handler. Used when tests want to verify that bad
322 code is caught by the library. */
324 __attribute__ ((unused
))
325 set_fortify_handler (void (*handler
) (int sig
))
329 sa
.sa_handler
= handler
;
331 sigemptyset (&sa
.sa_mask
);
333 sigaction (SIGABRT
, &sa
, NULL
);
337 /* Show people how to run the program. */
343 printf ("Usage: %s [options]\n"
345 "Environment Variables:\n"
346 " TIMEOUTFACTOR An integer used to scale the timeout\n"
347 " TMPDIR Where to place temporary files\n"
349 program_invocation_short_name
);
350 printf ("Options:\n");
351 for (i
= 0; options
[i
].name
; ++i
)
355 indent
= printf (" --%s", options
[i
].name
);
356 if (options
[i
].has_arg
== required_argument
)
357 indent
+= printf (" <arg>");
358 printf ("%*s", 25 - indent
, "");
359 switch (options
[i
].val
)
362 printf ("Run the test directly (instead of forking & monitoring)");
365 printf ("Override the TMPDIR env var");
372 /* We provide the entry point here. */
374 main (int argc
, char *argv
[])
376 int direct
= 0; /* Directly call the test function? */
379 unsigned int timeoutfactor
= 1;
382 #ifndef TEST_NO_MALLOPT
383 /* Make uses of freed and uninitialized memory known. */
384 mallopt (M_PERTURB
, 42);
387 #ifdef STDOUT_UNBUFFERED
388 setbuf (stdout
, NULL
);
391 while ((opt
= getopt_long (argc
, argv
, "+", options
, NULL
)) != -1)
403 #ifdef CMDLINE_PROCESS
408 /* If set, read the test TIMEOUTFACTOR value from the environment.
409 This value is used to scale the default test timeout values. */
410 char *envstr_timeoutfactor
= getenv ("TIMEOUTFACTOR");
411 if (envstr_timeoutfactor
!= NULL
)
413 char *envstr_conv
= envstr_timeoutfactor
;
414 unsigned long int env_fact
;
416 env_fact
= strtoul (envstr_timeoutfactor
, &envstr_conv
, 0);
417 if (*envstr_conv
== '\0' && envstr_conv
!= envstr_timeoutfactor
)
418 timeoutfactor
= MAX (env_fact
, 1);
421 /* Set TMPDIR to specified test directory. */
422 if (test_dir
!= NULL
)
424 setenv ("TMPDIR", test_dir
, 1);
426 if (chdir (test_dir
) < 0)
428 printf ("chdir: %m\n");
434 test_dir
= getenv ("TMPDIR");
435 if (test_dir
== NULL
|| test_dir
[0] == '\0')
439 /* Make sure we see all message, even those on stdout. */
440 setvbuf (stdout
, NULL
, _IONBF
, 0);
442 /* Make sure temporary files are deleted. */
443 atexit (delete_temp_files
);
445 /* Correct for the possible parameters. */
446 argv
[optind
- 1] = argv
[0];
450 /* Call the initializing function, if one is available. */
452 PREPARE (argc
, argv
);
455 const char *envstr_direct
= getenv ("TEST_DIRECT");
456 if (envstr_direct
!= NULL
)
458 FILE *f
= fopen (envstr_direct
, "w");
461 printf ("cannot open TEST_DIRECT output file '%s': %m\n",
466 fprintf (f
, "timeout=%u\ntimeoutfactor=%u\n", TIMEOUT
, timeoutfactor
);
467 #ifdef EXPECTED_STATUS
468 fprintf (f
, "exit=%u\n", EXPECTED_STATUS
);
470 #ifdef EXPECTED_SIGNAL
471 switch (EXPECTED_SIGNAL
)
474 # define init_sig(signo, name, text) \
475 case signo: fprintf (f, "signal=%s\n", name); break;
476 # include <siglist.h>
481 if (temp_name_list
!= NULL
)
483 struct temp_name_list
*n
;
484 fprintf (f
, "temp_files=(\n");
485 for (n
= temp_name_list
;
487 n
= (struct temp_name_list
*) n
->q
.q_forw
)
488 fprintf (f
, " '%s'\n", n
->name
);
496 /* If we are not expected to fork run the function immediately. */
498 return TEST_FUNCTION
;
500 /* Set up the test environment:
503 - fork and execute the function. */
508 /* This is the child. */
510 /* Try to avoid dumping core. */
511 struct rlimit core_limit
;
512 core_limit
.rlim_cur
= 0;
513 core_limit
.rlim_max
= 0;
514 setrlimit (RLIMIT_CORE
, &core_limit
);
517 /* We put the test process in its own pgrp so that if it bogusly
518 generates any job control signals, they won't hit the whole build. */
519 if (setpgid (0, 0) != 0)
520 printf ("Failed to set the process group ID: %m\n");
522 /* Execute the test function and exit with the return value. */
523 exit (TEST_FUNCTION
);
527 printf ("Cannot fork test program: %m\n");
532 signal (SIGALRM
, signal_handler
);
533 alarm (TIMEOUT
* timeoutfactor
);
535 /* Make sure we clean up if the wrapper gets interrupted. */
536 signal (SIGINT
, signal_handler
);
538 /* Wait for the regular termination. */
539 termpid
= TEMP_FAILURE_RETRY (waitpid (pid
, &status
, 0));
542 printf ("Waiting for test program failed: %m\n");
547 printf ("Oops, wrong test program terminated: expected %ld, got %ld\n",
548 (long int) pid
, (long int) termpid
);
552 /* Process terminated normaly without timeout etc. */
553 if (WIFEXITED (status
))
555 #ifndef EXPECTED_STATUS
556 # ifndef EXPECTED_SIGNAL
557 /* Simply exit with the return value of the test. */
558 return WEXITSTATUS (status
);
560 printf ("Expected signal '%s' from child, got none\n",
561 strsignal (EXPECTED_SIGNAL
));
565 if (WEXITSTATUS (status
) != EXPECTED_STATUS
)
567 printf ("Expected status %d, got %d\n",
568 EXPECTED_STATUS
, WEXITSTATUS (status
));
575 /* Process was killed by timer or other signal. */
578 #ifndef EXPECTED_SIGNAL
579 printf ("Didn't expect signal from child: got `%s'\n",
580 strsignal (WTERMSIG (status
)));
583 if (WTERMSIG (status
) != EXPECTED_SIGNAL
)
585 printf ("Incorrect signal from child: got `%s', need `%s'\n",
586 strsignal (WTERMSIG (status
)),
587 strsignal (EXPECTED_SIGNAL
));
596 /* The following functionality is only available if <pthread.h> was
597 included before this file. */
600 /* Call pthread_sigmask with error checking. */
602 xpthread_sigmask (int how
, const sigset_t
*set
, sigset_t
*oldset
)
604 if (pthread_sigmask (how
, set
, oldset
) != 0)
606 write_message ("error: pthread_setmask failed\n");
611 /* Call pthread_mutex_lock with error checking. */
612 __attribute__ ((unused
))
614 xpthread_mutex_lock (pthread_mutex_t
*mutex
)
616 int ret
= pthread_mutex_lock (mutex
);
620 printf ("error: pthread_mutex_lock: %m\n");
625 /* Call pthread_spin_lock with error checking. */
626 __attribute__ ((unused
))
628 xpthread_spin_lock (pthread_spinlock_t
*lock
)
630 int ret
= pthread_spin_lock (lock
);
634 printf ("error: pthread_spin_lock: %m\n");
639 /* Call pthread_cond_wait with error checking. */
640 __attribute__ ((unused
))
642 xpthread_cond_wait (pthread_cond_t
* cond
,
643 pthread_mutex_t
* mutex
)
645 int ret
= pthread_cond_wait (cond
, mutex
);
649 printf ("error: pthread_cond_wait: %m\n");
654 /* Call pthread_barrier_wait with error checking. */
655 __attribute__ ((unused
))
657 xpthread_barrier_wait (pthread_barrier_t
*barrier
)
659 int ret
= pthread_barrier_wait (barrier
);
660 if (ret
!= 0 && ret
!= PTHREAD_BARRIER_SERIAL_THREAD
)
663 printf ("error: pthread_barrier_wait: %m\n");
669 /* Call pthread_create with error checking. */
671 xpthread_create (pthread_attr_t
*attr
,
672 void *(*thread_func
) (void *), void *closure
)
675 int ret
= pthread_create (&thr
, attr
, thread_func
, closure
);
679 printf ("error: pthread_create: %m\n");
685 /* Call pthread_detach with error checking. */
687 xpthread_detach (pthread_t thr
)
689 int ret
= pthread_detach (thr
);
693 printf ("error: pthread_detach: %m\n");
698 /* Call pthread_join with error checking. */
699 __attribute__ ((unused
))
701 xpthread_join (pthread_t thr
)
704 int ret
= pthread_join (thr
, &result
);
708 printf ("error: pthread_join: %m\n");
714 /* Used to implement the delayed_exit function defined below. */
716 delayed_exit_thread (void *seconds_as_ptr
)
718 int seconds
= (uintptr_t) seconds_as_ptr
;
719 struct timespec delay
= { seconds
, 0 };
720 struct timespec remaining
= { 0 };
721 if (nanosleep (&delay
, &remaining
) != 0)
723 printf ("error: nanosleep: %m\n");
726 /* Exit the process sucessfully. */
731 /* Exit (with status 0) after SECONDS have elapsed, from a helper
732 thread. The process is terminated with the exit function, so
733 atexit handlers are executed. */
734 __attribute__ ((unused
))
736 delayed_exit (int seconds
)
738 /* Create the new thread with all signals blocked. */
739 sigset_t all_blocked
;
740 sigfillset (&all_blocked
);
742 xpthread_sigmask (SIG_SETMASK
, &all_blocked
, &old_set
);
743 /* Create a detached thread. */
744 pthread_t thr
= xpthread_create
745 (NULL
, delayed_exit_thread
, (void *) (uintptr_t) seconds
);
746 xpthread_detach (thr
);
747 /* Restore the original signal mask. */
748 xpthread_sigmask (SIG_SETMASK
, &old_set
, NULL
);
751 #endif /* _PTHREAD_H */