OSDN Git Service

1c3badb102ef16893d3e97fbe473f82ecf725274
[uclinux-h8/uClibc.git] / test / 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, see
18    <http://www.gnu.org/licenses/>.  */
19
20 #include <errno.h>
21 #include <getopt.h>
22 #include <malloc.h>
23 #include <search.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <sys/resource.h>
30 #include <sys/wait.h>
31 #include <sys/param.h>
32 #include <time.h>
33 #include <features.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': %s\n", fname, strerror(errno));
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 = 0;
138   int status;
139   int i;
140
141   /* Send signal.  */
142   kill (pid, SIGKILL);
143
144   /* Wait for it to terminate.  */
145   for (i = 0; i < 5; ++i)
146     {
147       struct timespec ts;
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       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 static void
193 __attribute__ ((noreturn))
194 handler_killpid(int sig)
195 {
196         kill(pid, SIGKILL); /* kill test */
197         signal(sig, SIG_DFL);
198         raise(sig); /* kill ourself */
199         _exit(128 + sig); /* paranoia */
200 }
201
202 /* We provide the entry point here.  */
203 int
204 main (int argc, char *argv[])
205 {
206 #ifdef __ARCH_USE_MMU__
207   int direct = 0;       /* Directly call the test function?  */
208 #else
209   int direct = 1;
210 #endif
211   int status;
212   int opt;
213   unsigned int timeoutfactor = 1;
214   pid_t termpid;
215   char *envstr_timeoutfactor;
216
217   /* Make uses of freed and uninitialized memory known.  */
218 #ifdef __MALLOC_STANDARD__
219 #ifndef M_PERTURB
220 # define M_PERTURB -6
221 #endif
222   mallopt (M_PERTURB, 42);
223 #endif
224
225 #ifdef STDOUT_UNBUFFERED
226   setbuf (stdout, NULL);
227 #endif
228
229   while ((opt = getopt_long (argc, argv, "+", options, NULL)) != -1)
230     switch (opt)
231       {
232       case '?':
233         exit (1);
234       case OPT_DIRECT:
235         direct = 1;
236         break;
237       case OPT_TESTDIR:
238         test_dir = optarg;
239         break;
240 #ifdef CMDLINE_PROCESS
241         CMDLINE_PROCESS
242 #endif
243       }
244
245   /* If set, read the test TIMEOUTFACTOR value from the environment.
246      This value is used to scale the default test timeout values. */
247   envstr_timeoutfactor = getenv ("TIMEOUTFACTOR");
248   if (envstr_timeoutfactor != NULL)
249     {
250       char *envstr_conv = envstr_timeoutfactor;
251       unsigned long int env_fact;
252
253       env_fact = strtoul (envstr_timeoutfactor, &envstr_conv, 0);
254       if (*envstr_conv == '\0' && envstr_conv != envstr_timeoutfactor)
255         timeoutfactor = MAX (env_fact, 1);
256     }
257
258   /* Set TMPDIR to specified test directory.  */
259   if (test_dir != NULL)
260     {
261       setenv ("TMPDIR", test_dir, 1);
262
263       if (chdir (test_dir) < 0)
264         {
265           perror ("chdir");
266           exit (1);
267         }
268     }
269   else
270     {
271       test_dir = getenv ("TMPDIR");
272       if (test_dir == NULL || test_dir[0] == '\0')
273         test_dir = "/tmp";
274     }
275
276   /* Make sure we see all message, even those on stdout.  */
277   setvbuf (stdout, NULL, _IONBF, 0);
278
279   /* make sure temporary files are deleted.  */
280   atexit (delete_temp_files);
281
282   /* Correct for the possible parameters.  */
283   argv[optind - 1] = argv[0];
284   argv += optind - 1;
285   argc -= optind - 1;
286
287   /* Call the initializing function, if one is available.  */
288 #ifdef PREPARE
289   PREPARE (argc, argv);
290 #endif
291
292   /* If we are not expected to fork run the function immediately.  */
293   if (direct)
294     return TEST_FUNCTION;
295
296   /* Set up the test environment:
297      - prevent core dumps
298      - set up the timer
299      - fork and execute the function.  */
300
301 #if defined __ARCH_USE_MMU__ || ! defined __UCLIBC__
302   pid = fork ();
303   if (pid == 0)
304     {
305       /* This is the child.  */
306 #ifdef RLIMIT_DATA
307       struct rlimit data_limit;
308 #endif
309 #ifdef RLIMIT_CORE
310       /* Try to avoid dumping core.  */
311       struct rlimit core_limit;
312       core_limit.rlim_cur = 0;
313       core_limit.rlim_max = 0;
314       setrlimit (RLIMIT_CORE, &core_limit);
315 #endif
316
317 #ifdef RLIMIT_DATA
318       /* Try to avoid eating all memory if a test leaks.  */
319       if (getrlimit (RLIMIT_DATA, &data_limit) == 0)
320         {
321           if (TEST_DATA_LIMIT == RLIM_INFINITY)
322             data_limit.rlim_cur = data_limit.rlim_max;
323           else if (data_limit.rlim_cur > (rlim_t) TEST_DATA_LIMIT)
324             data_limit.rlim_cur = MIN ((rlim_t) TEST_DATA_LIMIT,
325                                        data_limit.rlim_max);
326           if (setrlimit (RLIMIT_DATA, &data_limit) < 0)
327             perror ("setrlimit: RLIMIT_DATA");
328         }
329       else
330         perror ("getrlimit: RLIMIT_DATA");
331 #endif
332
333       /* We put the test process in its own pgrp so that if it bogusly
334          generates any job control signals, they won't hit the whole build.  */
335       setpgid (0, 0);
336
337       /* Execute the test function and exit with the return value.   */
338       exit (TEST_FUNCTION);
339     }
340   else if (pid < 0)
341 #endif
342     {
343       perror ("Cannot fork test program");
344       exit (1);
345     }
346
347   signal (SIGTERM, handler_killpid);
348   signal (SIGINT, handler_killpid);
349   signal (SIGQUIT, handler_killpid);
350
351   /* Set timeout.  */
352 #ifndef TIMEOUT
353   /* Default timeout is two seconds.  */
354 # define TIMEOUT 2
355 #endif
356   signal (SIGALRM, timeout_handler);
357   alarm (TIMEOUT * timeoutfactor);
358
359   /* Wait for the regular termination.  */
360   termpid = TEMP_FAILURE_RETRY (waitpid (pid, &status, 0));
361   if (termpid == -1)
362     {
363       printf ("Waiting for test program failed: %s\n", strerror(errno));
364       exit (1);
365     }
366   if (termpid != pid)
367     {
368       printf ("Oops, wrong test program terminated: expected %ld, got %ld\n",
369               (long int) pid, (long int) termpid);
370       exit (1);
371     }
372
373 #ifndef EXPECTED_SIGNAL
374   /* We don't expect any signal.  */
375 # define EXPECTED_SIGNAL 0
376 #endif
377   if (WTERMSIG (status) != EXPECTED_SIGNAL)
378     {
379       if (EXPECTED_SIGNAL != 0)
380         {
381           if (WTERMSIG (status) == 0)
382             fprintf (stderr,
383                      "Expected signal '%s' from child, got none\n",
384                      strsignal (EXPECTED_SIGNAL));
385           else
386             fprintf (stderr,
387                      "Incorrect signal from child: got `%s', need `%s'\n",
388                      strsignal (WTERMSIG (status)),
389                      strsignal (EXPECTED_SIGNAL));
390         }
391       else
392         fprintf (stderr, "Didn't expect signal from child: got `%s'\n",
393                  strsignal (WTERMSIG (status)));
394       exit (1);
395     }
396
397   /* Simply exit with the return value of the test.  */
398 #ifndef EXPECTED_STATUS
399   return WEXITSTATUS (status);
400 #else
401   if (WEXITSTATUS (status) != EXPECTED_STATUS)
402     {
403       fprintf (stderr, "Expected status %d, got %d\n",
404                EXPECTED_STATUS, WEXITSTATUS (status));
405       exit (1);
406     }
407
408   return 0;
409 #endif
410 }