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