test-skeleton.c: Use stdout for error messages
[platform/upstream/glibc.git] / test-skeleton.c
1 /* Skeleton for test programs.
2    Copyright (C) 1998-2014 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
5
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.
10
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.
15
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/>.  */
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <getopt.h>
23 #include <malloc.h>
24 #include <paths.h>
25 #include <search.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/resource.h>
32 #include <sys/wait.h>
33 #include <sys/param.h>
34 #include <time.h>
35
36 /* The test function is normally called `do_test' and it is called
37    with argc and argv as the arguments.  We nevertheless provide the
38    possibility to overwrite this name.  */
39 #ifndef TEST_FUNCTION
40 # define TEST_FUNCTION do_test (argc, argv)
41 #endif
42
43 #ifndef TEST_DATA_LIMIT
44 # define TEST_DATA_LIMIT (64 << 20) /* Data limit (bytes) to run with.  */
45 #endif
46
47 #define OPT_DIRECT 1000
48 #define OPT_TESTDIR 1001
49
50 static struct option options[] =
51 {
52 #ifdef CMDLINE_OPTIONS
53   CMDLINE_OPTIONS
54 #endif
55   { "direct", no_argument, NULL, OPT_DIRECT },
56   { "test-dir", required_argument, NULL, OPT_TESTDIR },
57   { NULL, 0, NULL, 0 }
58 };
59
60 /* PID of the test itself.  */
61 static pid_t pid;
62
63 /* Directory to place temporary files in.  */
64 static const char *test_dir;
65
66 /* List of temporary files.  */
67 struct temp_name_list
68 {
69   struct qelem q;
70   const char *name;
71 } *temp_name_list;
72
73 /* Add temporary files in list.  */
74 static void
75 __attribute__ ((unused))
76 add_temp_file (const char *name)
77 {
78   struct temp_name_list *newp
79     = (struct temp_name_list *) calloc (sizeof (*newp), 1);
80   if (newp != NULL)
81     {
82       newp->name = name;
83       if (temp_name_list == NULL)
84         temp_name_list = (struct temp_name_list *) &newp->q;
85       else
86         insque (newp, temp_name_list);
87     }
88 }
89
90 /* Delete all temporary files.  */
91 static void
92 delete_temp_files (void)
93 {
94   while (temp_name_list != NULL)
95     {
96       remove (temp_name_list->name);
97       temp_name_list = (struct temp_name_list *) temp_name_list->q.q_forw;
98     }
99 }
100
101 /* Create a temporary file.  */
102 static int
103 __attribute__ ((unused))
104 create_temp_file (const char *base, char **filename)
105 {
106   char *fname;
107   int fd;
108
109   fname = (char *) malloc (strlen (test_dir) + 1 + strlen (base)
110                            + sizeof ("XXXXXX"));
111   if (fname == NULL)
112     {
113       puts ("out of memory");
114       return -1;
115     }
116   strcpy (stpcpy (stpcpy (stpcpy (fname, test_dir), "/"), base), "XXXXXX");
117
118   fd = mkstemp (fname);
119   if (fd == -1)
120     {
121       printf ("cannot open temporary file '%s': %m\n", fname);
122       free (fname);
123       return -1;
124     }
125
126   add_temp_file (fname);
127   if (filename != NULL)
128     *filename = fname;
129
130   return fd;
131 }
132
133 /* Timeout handler.  We kill the child and exit with an error.  */
134 static void
135 __attribute__ ((noreturn))
136 signal_handler (int sig __attribute__ ((unused)))
137 {
138   int killed;
139   int status;
140
141   /* Send signal.  */
142   kill (pid, SIGKILL);
143
144   /* Wait for it to terminate.  */
145   int i;
146   for (i = 0; i < 5; ++i)
147     {
148       killed = waitpid (pid, &status, WNOHANG|WUNTRACED);
149       if (killed != 0)
150         break;
151
152       /* Delay, give the system time to process the kill.  If the
153          nanosleep() call return prematurely, all the better.  We
154          won't restart it since this probably means the child process
155          finally died.  */
156       struct timespec ts;
157       ts.tv_sec = 0;
158       ts.tv_nsec = 100000000;
159       nanosleep (&ts, NULL);
160     }
161   if (killed != 0 && killed != pid)
162     {
163       printf ("Failed to kill test process: %m\n");
164       exit (1);
165     }
166
167 #ifdef CLEANUP_HANDLER
168   CLEANUP_HANDLER;
169 #endif
170
171   if (sig == SIGINT)
172     {
173       signal (sig, SIG_DFL);
174       raise (sig);
175     }
176
177   /* If we expected this signal: good!  */
178 #ifdef EXPECTED_SIGNAL
179   if (EXPECTED_SIGNAL == SIGALRM)
180     exit (0);
181 #endif
182
183   if (killed == 0 || (WIFSIGNALED (status) && WTERMSIG (status) == SIGKILL))
184     puts ("Timed out: killed the child process");
185   else if (WIFSTOPPED (status))
186     printf ("Timed out: the child process was %s\n",
187             strsignal (WSTOPSIG (status)));
188   else if (WIFSIGNALED (status))
189     printf ("Timed out: the child process got signal %s\n",
190             strsignal (WTERMSIG (status)));
191   else
192     printf ("Timed out: killed the child process but it exited %d\n",
193             WEXITSTATUS (status));
194
195   /* Exit with an error.  */
196   exit (1);
197 }
198
199 /* Set fortification error handler.  Used when tests want to verify that bad
200    code is caught by the library.  */
201 static void
202 __attribute__ ((unused))
203 set_fortify_handler (void (*handler) (int sig))
204 {
205   struct sigaction sa;
206
207   sa.sa_handler = handler;
208   sa.sa_flags = 0;
209   sigemptyset (&sa.sa_mask);
210
211   sigaction (SIGABRT, &sa, NULL);
212
213   /* Avoid all the buffer overflow messages on stderr.  */
214   int fd = open (_PATH_DEVNULL, O_WRONLY);
215   if (fd == -1)
216     close (STDERR_FILENO);
217   else
218     {
219       dup2 (fd, STDERR_FILENO);
220       close (fd);
221     }
222   setenv ("LIBC_FATAL_STDERR_", "1", 1);
223 }
224
225 /* We provide the entry point here.  */
226 int
227 main (int argc, char *argv[])
228 {
229   int direct = 0;       /* Directly call the test function?  */
230   int status;
231   int opt;
232   unsigned int timeoutfactor = 1;
233   pid_t termpid;
234
235   /* Make uses of freed and uninitialized memory known.  */
236   mallopt (M_PERTURB, 42);
237
238 #ifdef STDOUT_UNBUFFERED
239   setbuf (stdout, NULL);
240 #endif
241
242   while ((opt = getopt_long (argc, argv, "+", options, NULL)) != -1)
243     switch (opt)
244       {
245       case '?':
246         exit (1);
247       case OPT_DIRECT:
248         direct = 1;
249         break;
250       case OPT_TESTDIR:
251         test_dir = optarg;
252         break;
253 #ifdef CMDLINE_PROCESS
254         CMDLINE_PROCESS
255 #endif
256       }
257
258   /* If set, read the test TIMEOUTFACTOR value from the environment.
259      This value is used to scale the default test timeout values. */
260   char *envstr_timeoutfactor = getenv ("TIMEOUTFACTOR");
261   if (envstr_timeoutfactor != NULL)
262     {
263       char *envstr_conv = envstr_timeoutfactor;
264       unsigned long int env_fact;
265
266       env_fact = strtoul (envstr_timeoutfactor, &envstr_conv, 0);
267       if (*envstr_conv == '\0' && envstr_conv != envstr_timeoutfactor)
268         timeoutfactor = MAX (env_fact, 1);
269     }
270
271   /* Set TMPDIR to specified test directory.  */
272   if (test_dir != NULL)
273     {
274       setenv ("TMPDIR", test_dir, 1);
275
276       if (chdir (test_dir) < 0)
277         {
278           printf ("chdir: %m\n");
279           exit (1);
280         }
281     }
282   else
283     {
284       test_dir = getenv ("TMPDIR");
285       if (test_dir == NULL || test_dir[0] == '\0')
286         test_dir = "/tmp";
287     }
288
289   /* Make sure we see all message, even those on stdout.  */
290   setvbuf (stdout, NULL, _IONBF, 0);
291
292   /* make sure temporary files are deleted.  */
293   atexit (delete_temp_files);
294
295   /* Correct for the possible parameters.  */
296   argv[optind - 1] = argv[0];
297   argv += optind - 1;
298   argc -= optind - 1;
299
300   /* Call the initializing function, if one is available.  */
301 #ifdef PREPARE
302   PREPARE (argc, argv);
303 #endif
304
305   /* If we are not expected to fork run the function immediately.  */
306   if (direct)
307     return TEST_FUNCTION;
308
309   /* Set up the test environment:
310      - prevent core dumps
311      - set up the timer
312      - fork and execute the function.  */
313
314   pid = fork ();
315   if (pid == 0)
316     {
317       /* This is the child.  */
318 #ifdef RLIMIT_CORE
319       /* Try to avoid dumping core.  */
320       struct rlimit core_limit;
321       core_limit.rlim_cur = 0;
322       core_limit.rlim_max = 0;
323       setrlimit (RLIMIT_CORE, &core_limit);
324 #endif
325
326 #ifdef RLIMIT_DATA
327       /* Try to avoid eating all memory if a test leaks.  */
328       struct rlimit data_limit;
329       if (getrlimit (RLIMIT_DATA, &data_limit) == 0)
330         {
331           if (TEST_DATA_LIMIT == RLIM_INFINITY)
332             data_limit.rlim_cur = data_limit.rlim_max;
333           else if (data_limit.rlim_cur > (rlim_t) TEST_DATA_LIMIT)
334             data_limit.rlim_cur = MIN ((rlim_t) TEST_DATA_LIMIT,
335                                        data_limit.rlim_max);
336           if (setrlimit (RLIMIT_DATA, &data_limit) < 0)
337             printf ("setrlimit: RLIMIT_DATA: %m\n");
338         }
339       else
340         printf ("getrlimit: RLIMIT_DATA: %m\n");
341 #endif
342
343       /* We put the test process in its own pgrp so that if it bogusly
344          generates any job control signals, they won't hit the whole build.  */
345       setpgid (0, 0);
346
347       /* Execute the test function and exit with the return value.   */
348       exit (TEST_FUNCTION);
349     }
350   else if (pid < 0)
351     {
352       printf ("Cannot fork test program: %m\n");
353       exit (1);
354     }
355
356   /* Set timeout.  */
357 #ifndef TIMEOUT
358   /* Default timeout is two seconds.  */
359 # define TIMEOUT 2
360 #endif
361   signal (SIGALRM, signal_handler);
362   alarm (TIMEOUT * timeoutfactor);
363
364   /* Make sure we clean up if the wrapper gets interrupted.  */
365   signal (SIGINT, signal_handler);
366
367   /* Wait for the regular termination.  */
368   termpid = TEMP_FAILURE_RETRY (waitpid (pid, &status, 0));
369   if (termpid == -1)
370     {
371       printf ("Waiting for test program failed: %m\n");
372       exit (1);
373     }
374   if (termpid != pid)
375     {
376       printf ("Oops, wrong test program terminated: expected %ld, got %ld\n",
377               (long int) pid, (long int) termpid);
378       exit (1);
379     }
380
381 #ifndef EXPECTED_SIGNAL
382   /* We don't expect any signal.  */
383 # define EXPECTED_SIGNAL 0
384 #endif
385   if (WTERMSIG (status) != EXPECTED_SIGNAL)
386     {
387       if (EXPECTED_SIGNAL != 0)
388         {
389           if (WTERMSIG (status) == 0)
390             printf ("Expected signal '%s' from child, got none\n",
391                     strsignal (EXPECTED_SIGNAL));
392           else
393             printf ("Incorrect signal from child: got `%s', need `%s'\n",
394                     strsignal (WTERMSIG (status)),
395                     strsignal (EXPECTED_SIGNAL));
396         }
397       else
398         printf ("Didn't expect signal from child: got `%s'\n",
399                 strsignal (WTERMSIG (status)));
400       exit (1);
401     }
402
403   /* Simply exit with the return value of the test.  */
404 #ifndef EXPECTED_STATUS
405   return WEXITSTATUS (status);
406 #else
407   if (WEXITSTATUS (status) != EXPECTED_STATUS)
408     {
409       printf ("Expected status %d, got %d\n",
410               EXPECTED_STATUS, WEXITSTATUS (status));
411       exit (1);
412     }
413
414   return 0;
415 #endif
416 }