Consolidate fallocate{64} implementations
[platform/upstream/glibc.git] / test-skeleton.c
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.
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 twenty seconds.  Tests should normally complete faster
50      than this, but if they don't, that's abnormal (a bug) anyways.  */
51 # define TIMEOUT 20
52 #endif
53
54 #define OPT_DIRECT 1000
55 #define OPT_TESTDIR 1001
56
57 static struct option options[] =
58 {
59 #ifdef CMDLINE_OPTIONS
60   CMDLINE_OPTIONS
61 #endif
62   { "direct", no_argument, NULL, OPT_DIRECT },
63   { "test-dir", required_argument, NULL, OPT_TESTDIR },
64   { NULL, 0, NULL, 0 }
65 };
66
67 /* PID of the test itself.  */
68 static pid_t pid;
69
70 /* Directory to place temporary files in.  */
71 static const char *test_dir;
72
73 #define _FAIL(...) \
74   printf ("error: %s:%d: ", __FILE__, __LINE__); \
75   printf (__VA_ARGS__); \
76   printf ("\n"); \
77
78 #define FAIL_RET(...) \
79   ({ \
80      _FAIL (__VA_ARGS__); \
81      return 1; \
82   })
83
84 #define FAIL_EXIT(value, ...) \
85   ({ \
86      _FAIL (__VA_ARGS__); \
87      exit (value); \
88   })
89
90 #define FAIL_EXIT1(...) FAIL_EXIT(1, __VA_ARGS__)
91
92 static void
93 oom_error (const char *fn, size_t size)
94 {
95   printf ("%s: unable to allocate %zu bytes: %m\n", fn, size);
96   exit (1);
97 }
98
99 /* Allocate N bytes of memory dynamically, with error checking.  */
100 __attribute__ ((unused))
101 static void *
102 xmalloc (size_t n)
103 {
104   void *p;
105
106   p = malloc (n);
107   if (p == NULL)
108     oom_error ("malloc", n);
109   return p;
110 }
111
112 /* Allocate memory for N elements of S bytes, with error checking.  */
113 __attribute__ ((unused))
114 static void *
115 xcalloc (size_t n, size_t s)
116 {
117   void *p;
118
119   p = calloc (n, s);
120   if (p == NULL)
121     oom_error ("calloc", n * s);
122   return p;
123 }
124
125 /* Change the size of an allocated block of memory P to N bytes,
126    with error checking.  */
127 __attribute__ ((unused))
128 static void *
129 xrealloc (void *p, size_t n)
130 {
131   void *result = realloc (p, n);
132   if (result == NULL && (n > 0 || p == NULL))
133     oom_error ("realloc", n);
134   return result;
135 }
136
137 /* Call asprintf with error checking.  */
138 __attribute__ ((always_inline, format (printf, 1, 2)))
139 static __inline__ char *
140 xasprintf (const char *format, ...)
141 {
142   char *result;
143   if (asprintf (&result, format, __builtin_va_arg_pack ()) < 0)
144     {
145       printf ("error: asprintf: %m\n");
146       exit (1);
147     }
148   return result;
149 }
150
151 /* Write a message to standard output.  Can be used in signal
152    handlers.  */
153 static void
154 __attribute__ ((unused))
155 write_message (const char *message)
156 {
157   ssize_t unused __attribute__ ((unused));
158   unused = write (STDOUT_FILENO, message, strlen (message));
159 }
160
161 /* List of temporary files.  */
162 struct temp_name_list
163 {
164   struct qelem q;
165   char *name;
166 } *temp_name_list;
167
168 /* Add temporary files in list.  */
169 static void
170 __attribute__ ((unused))
171 add_temp_file (const char *name)
172 {
173   struct temp_name_list *newp
174     = (struct temp_name_list *) xcalloc (sizeof (*newp), 1);
175   char *newname = strdup (name);
176   if (newname != NULL)
177     {
178       newp->name = newname;
179       if (temp_name_list == NULL)
180         temp_name_list = (struct temp_name_list *) &newp->q;
181       else
182         insque (newp, temp_name_list);
183     }
184   else
185     free (newp);
186 }
187
188 /* Delete all temporary files.  */
189 static void
190 delete_temp_files (void)
191 {
192   while (temp_name_list != NULL)
193     {
194       remove (temp_name_list->name);
195       free (temp_name_list->name);
196
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;
201     }
202 }
203
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
207    *FILENAME.  */
208 static int
209 __attribute__ ((unused))
210 create_temp_file (const char *base, char **filename)
211 {
212   char *fname;
213   int fd;
214
215   fname = (char *) xmalloc (strlen (test_dir) + 1 + strlen (base)
216                             + sizeof ("XXXXXX"));
217   strcpy (stpcpy (stpcpy (stpcpy (fname, test_dir), "/"), base), "XXXXXX");
218
219   fd = mkstemp (fname);
220   if (fd == -1)
221     {
222       printf ("cannot open temporary file '%s': %m\n", fname);
223       free (fname);
224       return -1;
225     }
226
227   add_temp_file (fname);
228   if (filename != NULL)
229     *filename = fname;
230   else
231     free (fname);
232
233   return fd;
234 }
235
236 /* Timeout handler.  We kill the child and exit with an error.  */
237 static void
238 __attribute__ ((noreturn))
239 signal_handler (int sig __attribute__ ((unused)))
240 {
241   int killed;
242   int status;
243
244   assert (pid > 1);
245   /* Kill the whole process group.  */
246   kill (-pid, SIGKILL);
247   /* In case setpgid failed in the child, kill it individually too.  */
248   kill (pid, SIGKILL);
249
250   /* Wait for it to terminate.  */
251   int i;
252   for (i = 0; i < 5; ++i)
253     {
254       killed = waitpid (pid, &status, WNOHANG|WUNTRACED);
255       if (killed != 0)
256         break;
257
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
261          finally died.  */
262       struct timespec ts;
263       ts.tv_sec = 0;
264       ts.tv_nsec = 100000000;
265       nanosleep (&ts, NULL);
266     }
267   if (killed != 0 && killed != pid)
268     {
269       printf ("Failed to kill test process: %m\n");
270       exit (1);
271     }
272
273 #ifdef CLEANUP_HANDLER
274   CLEANUP_HANDLER;
275 #endif
276
277   if (sig == SIGINT)
278     {
279       signal (sig, SIG_DFL);
280       raise (sig);
281     }
282
283   /* If we expected this signal: good!  */
284 #ifdef EXPECTED_SIGNAL
285   if (EXPECTED_SIGNAL == SIGALRM)
286     exit (0);
287 #endif
288
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)));
297   else
298     printf ("Timed out: killed the child process but it exited %d\n",
299             WEXITSTATUS (status));
300
301   /* Exit with an error.  */
302   exit (1);
303 }
304
305 /* Avoid all the buffer overflow messages on stderr.  */
306 static void
307 __attribute__ ((unused))
308 ignore_stderr (void)
309 {
310   int fd = open (_PATH_DEVNULL, O_WRONLY);
311   if (fd == -1)
312     close (STDERR_FILENO);
313   else
314     {
315       dup2 (fd, STDERR_FILENO);
316       close (fd);
317     }
318   setenv ("LIBC_FATAL_STDERR_", "1", 1);
319 }
320
321 /* Set fortification error handler.  Used when tests want to verify that bad
322    code is caught by the library.  */
323 static void
324 __attribute__ ((unused))
325 set_fortify_handler (void (*handler) (int sig))
326 {
327   struct sigaction sa;
328
329   sa.sa_handler = handler;
330   sa.sa_flags = 0;
331   sigemptyset (&sa.sa_mask);
332
333   sigaction (SIGABRT, &sa, NULL);
334   ignore_stderr ();
335 }
336
337 /* Show people how to run the program.  */
338 static void
339 usage (void)
340 {
341   size_t i;
342
343   printf ("Usage: %s [options]\n"
344           "\n"
345           "Environment Variables:\n"
346           "  TIMEOUTFACTOR          An integer used to scale the timeout\n"
347           "  TMPDIR                 Where to place temporary files\n"
348           "\n",
349           program_invocation_short_name);
350   printf ("Options:\n");
351   for (i = 0; options[i].name; ++i)
352     {
353       int indent;
354
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)
360         {
361         case OPT_DIRECT:
362           printf ("Run the test directly (instead of forking & monitoring)");
363           break;
364         case OPT_TESTDIR:
365           printf ("Override the TMPDIR env var");
366           break;
367         }
368       printf ("\n");
369     }
370 }
371
372 /* We provide the entry point here.  */
373 int
374 main (int argc, char *argv[])
375 {
376   int direct = 0;       /* Directly call the test function?  */
377   int status;
378   int opt;
379   unsigned int timeoutfactor = 1;
380   pid_t termpid;
381
382 #ifndef TEST_NO_MALLOPT
383   /* Make uses of freed and uninitialized memory known.  */
384   mallopt (M_PERTURB, 42);
385 #endif
386
387 #ifdef STDOUT_UNBUFFERED
388   setbuf (stdout, NULL);
389 #endif
390
391   while ((opt = getopt_long (argc, argv, "+", options, NULL)) != -1)
392     switch (opt)
393       {
394       case '?':
395         usage ();
396         exit (1);
397       case OPT_DIRECT:
398         direct = 1;
399         break;
400       case OPT_TESTDIR:
401         test_dir = optarg;
402         break;
403 #ifdef CMDLINE_PROCESS
404         CMDLINE_PROCESS
405 #endif
406       }
407
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)
412     {
413       char *envstr_conv = envstr_timeoutfactor;
414       unsigned long int env_fact;
415
416       env_fact = strtoul (envstr_timeoutfactor, &envstr_conv, 0);
417       if (*envstr_conv == '\0' && envstr_conv != envstr_timeoutfactor)
418         timeoutfactor = MAX (env_fact, 1);
419     }
420
421   /* Set TMPDIR to specified test directory.  */
422   if (test_dir != NULL)
423     {
424       setenv ("TMPDIR", test_dir, 1);
425
426       if (chdir (test_dir) < 0)
427         {
428           printf ("chdir: %m\n");
429           exit (1);
430         }
431     }
432   else
433     {
434       test_dir = getenv ("TMPDIR");
435       if (test_dir == NULL || test_dir[0] == '\0')
436         test_dir = "/tmp";
437     }
438
439   /* Make sure we see all message, even those on stdout.  */
440   setvbuf (stdout, NULL, _IONBF, 0);
441
442   /* Make sure temporary files are deleted.  */
443   atexit (delete_temp_files);
444
445   /* Correct for the possible parameters.  */
446   argv[optind - 1] = argv[0];
447   argv += optind - 1;
448   argc -= optind - 1;
449
450   /* Call the initializing function, if one is available.  */
451 #ifdef PREPARE
452   PREPARE (argc, argv);
453 #endif
454
455   const char *envstr_direct = getenv ("TEST_DIRECT");
456   if (envstr_direct != NULL)
457     {
458       FILE *f = fopen (envstr_direct, "w");
459       if (f == NULL)
460         {
461           printf ("cannot open TEST_DIRECT output file '%s': %m\n",
462                   envstr_direct);
463           exit (1);
464         }
465
466       fprintf (f, "timeout=%u\ntimeoutfactor=%u\n", TIMEOUT, timeoutfactor);
467 #ifdef EXPECTED_STATUS
468       fprintf (f, "exit=%u\n", EXPECTED_STATUS);
469 #endif
470 #ifdef EXPECTED_SIGNAL
471       switch (EXPECTED_SIGNAL)
472         {
473         default: abort ();
474 # define init_sig(signo, name, text) \
475         case signo: fprintf (f, "signal=%s\n", name); break;
476 # include <siglist.h>
477 # undef init_sig
478         }
479 #endif
480
481       if (temp_name_list != NULL)
482         {
483           struct temp_name_list *n;
484           fprintf (f, "temp_files=(\n");
485           for (n = temp_name_list;
486                n != NULL;
487                n = (struct temp_name_list *) n->q.q_forw)
488             fprintf (f, "  '%s'\n", n->name);
489           fprintf (f, ")\n");
490         }
491
492       fclose (f);
493       direct = 1;
494     }
495
496   /* If we are not expected to fork run the function immediately.  */
497   if (direct)
498     return TEST_FUNCTION;
499
500   /* Set up the test environment:
501      - prevent core dumps
502      - set up the timer
503      - fork and execute the function.  */
504
505   pid = fork ();
506   if (pid == 0)
507     {
508       /* This is the child.  */
509 #ifdef RLIMIT_CORE
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);
515 #endif
516
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");
521
522       /* Execute the test function and exit with the return value.   */
523       exit (TEST_FUNCTION);
524     }
525   else if (pid < 0)
526     {
527       printf ("Cannot fork test program: %m\n");
528       exit (1);
529     }
530
531   /* Set timeout.  */
532   signal (SIGALRM, signal_handler);
533   alarm (TIMEOUT * timeoutfactor);
534
535   /* Make sure we clean up if the wrapper gets interrupted.  */
536   signal (SIGINT, signal_handler);
537
538   /* Wait for the regular termination.  */
539   termpid = TEMP_FAILURE_RETRY (waitpid (pid, &status, 0));
540   if (termpid == -1)
541     {
542       printf ("Waiting for test program failed: %m\n");
543       exit (1);
544     }
545   if (termpid != pid)
546     {
547       printf ("Oops, wrong test program terminated: expected %ld, got %ld\n",
548               (long int) pid, (long int) termpid);
549       exit (1);
550     }
551
552   /* Process terminated normaly without timeout etc.  */
553   if (WIFEXITED (status))
554     {
555 #ifndef EXPECTED_STATUS
556 # ifndef EXPECTED_SIGNAL
557       /* Simply exit with the return value of the test.  */
558       return WEXITSTATUS (status);
559 # else
560       printf ("Expected signal '%s' from child, got none\n",
561               strsignal (EXPECTED_SIGNAL));
562       exit (1);
563 # endif
564 #else
565       if (WEXITSTATUS (status) != EXPECTED_STATUS)
566         {
567           printf ("Expected status %d, got %d\n",
568                   EXPECTED_STATUS, WEXITSTATUS (status));
569           exit (1);
570         }
571
572       return 0;
573 #endif
574     }
575   /* Process was killed by timer or other signal.  */
576   else
577     {
578 #ifndef EXPECTED_SIGNAL
579       printf ("Didn't expect signal from child: got `%s'\n",
580               strsignal (WTERMSIG (status)));
581       exit (1);
582 #else
583       if (WTERMSIG (status) != EXPECTED_SIGNAL)
584         {
585           printf ("Incorrect signal from child: got `%s', need `%s'\n",
586                   strsignal (WTERMSIG (status)),
587                   strsignal (EXPECTED_SIGNAL));
588           exit (1);
589         }
590
591       return 0;
592 #endif
593     }
594 }
595
596 /* The following functionality is only available if <pthread.h> was
597    included before this file.  */
598 #ifdef _PTHREAD_H
599
600 /* Call pthread_sigmask with error checking.  */
601 static void
602 xpthread_sigmask (int how, const sigset_t *set, sigset_t *oldset)
603 {
604   if (pthread_sigmask (how, set, oldset) != 0)
605     {
606       write_message ("error: pthread_setmask failed\n");
607       _exit (1);
608     }
609 }
610
611 /* Call pthread_mutex_lock with error checking.  */
612 __attribute__ ((unused))
613 static void
614 xpthread_mutex_lock (pthread_mutex_t *mutex)
615 {
616   int ret = pthread_mutex_lock (mutex);
617   if (ret != 0)
618     {
619       errno = ret;
620       printf ("error: pthread_mutex_lock: %m\n");
621       exit (1);
622     }
623 }
624
625 /* Call pthread_spin_lock with error checking.  */
626 __attribute__ ((unused))
627 static void
628 xpthread_spin_lock (pthread_spinlock_t *lock)
629 {
630   int ret = pthread_spin_lock (lock);
631   if (ret != 0)
632     {
633       errno = ret;
634       printf ("error: pthread_spin_lock: %m\n");
635       exit (1);
636     }
637 }
638
639 /* Call pthread_cond_wait with error checking.  */
640 __attribute__ ((unused))
641 static void
642 xpthread_cond_wait (pthread_cond_t * cond,
643                     pthread_mutex_t * mutex)
644 {
645   int ret = pthread_cond_wait (cond, mutex);
646   if (ret != 0)
647     {
648       errno = ret;
649       printf ("error: pthread_cond_wait: %m\n");
650       exit (1);
651     }
652 }
653
654 /* Call pthread_barrier_wait with error checking.  */
655 __attribute__ ((unused))
656 static int
657 xpthread_barrier_wait (pthread_barrier_t *barrier)
658 {
659   int ret = pthread_barrier_wait (barrier);
660   if (ret != 0 && ret != PTHREAD_BARRIER_SERIAL_THREAD)
661     {
662       errno = ret;
663       printf ("error: pthread_barrier_wait: %m\n");
664       exit (1);
665     }
666   return ret;
667 }
668
669 /* Call pthread_create with error checking.  */
670 static pthread_t
671 xpthread_create (pthread_attr_t *attr,
672                  void *(*thread_func) (void *), void *closure)
673 {
674   pthread_t thr;
675   int ret = pthread_create (&thr, attr, thread_func, closure);
676   if (ret != 0)
677     {
678       errno = ret;
679       printf ("error: pthread_create: %m\n");
680       exit (1);
681     }
682   return thr;
683 }
684
685 /* Call pthread_detach with error checking.  */
686 static void
687 xpthread_detach (pthread_t thr)
688 {
689   int ret = pthread_detach (thr);
690   if (ret != 0)
691     {
692       errno = ret;
693       printf ("error: pthread_detach: %m\n");
694       exit (1);
695     }
696 }
697
698 /* Call pthread_join with error checking.  */
699 __attribute__ ((unused))
700 static void *
701 xpthread_join (pthread_t thr)
702 {
703   void *result;
704   int ret = pthread_join (thr, &result);
705   if (ret != 0)
706     {
707       errno = ret;
708       printf ("error: pthread_join: %m\n");
709       exit (1);
710     }
711   return result;
712 }
713
714 /* Used to implement the delayed_exit function defined below.  */
715 static void *
716 delayed_exit_thread (void *seconds_as_ptr)
717 {
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)
722     {
723       printf ("error: nanosleep: %m\n");
724       _exit (1);
725     }
726   /* Exit the process sucessfully.  */
727   exit (0);
728   return NULL;
729 }
730
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))
735 static void
736 delayed_exit (int seconds)
737 {
738   /* Create the new thread with all signals blocked.  */
739   sigset_t all_blocked;
740   sigfillset (&all_blocked);
741   sigset_t old_set;
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);
749 }
750
751 #endif  /* _PTHREAD_H */