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