]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - usr.bin/tar/test/main.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / usr.bin / tar / test / main.c
1 /*
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 /*
27  * Various utility routines useful for test programs.
28  * Each test program is linked against this file.
29  */
30 #include "test.h"
31
32 #include <errno.h>
33 #include <locale.h>
34 #include <stdarg.h>
35 #include <time.h>
36
37 /*
38  * This same file is used pretty much verbatim for all test harnesses.
39  *
40  * The next few lines are the only differences.
41  */
42 #define PROGRAM "bsdtar" /* Name of program being tested. */
43 #define ENVBASE "BSDTAR" /* Prefix for environment variables. */
44 #undef  EXTRA_DUMP           /* How to dump extra data */
45 /* How to generate extra version info. */
46 #define EXTRA_VERSION    (systemf("%s --version", testprog) ? "" : "")
47 __FBSDID("$FreeBSD$");
48
49 /*
50  * "list.h" is simply created by "grep DEFINE_TEST"; it has
51  * a line like
52  *      DEFINE_TEST(test_function)
53  * for each test.
54  * Include it here with a suitable DEFINE_TEST to declare all of the
55  * test functions.
56  */
57 #undef DEFINE_TEST
58 #define DEFINE_TEST(name) void name(void);
59 #include "list.h"
60
61 /* Interix doesn't define these in a standard header. */
62 #if __INTERIX__
63 extern char *optarg;
64 extern int optind;
65 #endif
66
67 /* Enable core dump on failure. */
68 static int dump_on_failure = 0;
69 /* Default is to remove temp dirs for successful tests. */
70 static int keep_temp_files = 0;
71 /* Default is to print some basic information about each test. */
72 static int quiet_flag = 0;
73 /* Default is to summarize repeated failures. */
74 static int verbose = 0;
75 /* Cumulative count of component failures. */
76 static int failures = 0;
77 /* Cumulative count of skipped component tests. */
78 static int skips = 0;
79 /* Cumulative count of assertions. */
80 static int assertions = 0;
81
82 /* Directory where uuencoded reference files can be found. */
83 static char *refdir;
84
85 /*
86  * My own implementation of the standard assert() macro emits the
87  * message in the same format as GCC (file:line: message).
88  * It also includes some additional useful information.
89  * This makes it a lot easier to skim through test failures in
90  * Emacs.  ;-)
91  *
92  * It also supports a few special features specifically to simplify
93  * test harnesses:
94  *    failure(fmt, args) -- Stores a text string that gets
95  *          printed if the following assertion fails, good for
96  *          explaining subtle tests.
97  */
98 static char msg[4096];
99
100 /*
101  * For each test source file, we remember how many times each
102  * failure was reported.
103  */
104 static const char *failed_filename = NULL;
105 static struct line {
106         int line;
107         int count;
108 }  failed_lines[1000];
109
110 /*
111  * Count this failure; return the number of previous failures.
112  */
113 static int
114 previous_failures(const char *filename, int line)
115 {
116         unsigned int i;
117         int count;
118
119         if (failed_filename == NULL || strcmp(failed_filename, filename) != 0)
120                 memset(failed_lines, 0, sizeof(failed_lines));
121         failed_filename = filename;
122
123         for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {
124                 if (failed_lines[i].line == line) {
125                         count = failed_lines[i].count;
126                         failed_lines[i].count++;
127                         return (count);
128                 }
129                 if (failed_lines[i].line == 0) {
130                         failed_lines[i].line = line;
131                         failed_lines[i].count = 1;
132                         return (0);
133                 }
134         }
135         return (0);
136 }
137
138 /*
139  * Copy arguments into file-local variables.
140  */
141 static const char *test_filename;
142 static int test_line;
143 static void *test_extra;
144 void test_setup(const char *filename, int line)
145 {
146         test_filename = filename;
147         test_line = line;
148 }
149
150 /*
151  * Inform user that we're skipping a test.
152  */
153 void
154 test_skipping(const char *fmt, ...)
155 {
156         va_list ap;
157
158         if (previous_failures(test_filename, test_line))
159                 return;
160
161         va_start(ap, fmt);
162         fprintf(stderr, " *** SKIPPING: ");
163         vfprintf(stderr, fmt, ap);
164         fprintf(stderr, "\n");
165         va_end(ap);
166         ++skips;
167 }
168
169 /* Common handling of failed tests. */
170 static void
171 report_failure(void *extra)
172 {
173         if (msg[0] != '\0') {
174                 fprintf(stderr, "   Description: %s\n", msg);
175                 msg[0] = '\0';
176         }
177
178 #ifdef EXTRA_DUMP
179         if (extra != NULL)
180                 fprintf(stderr, "   detail: %s\n", EXTRA_DUMP(extra));
181 #else
182         (void)extra; /* UNUSED */
183 #endif
184
185         if (dump_on_failure) {
186                 fprintf(stderr,
187                     " *** forcing core dump so failure can be debugged ***\n");
188                 *(char *)(NULL) = 0;
189                 exit(1);
190         }
191 }
192
193 /*
194  * Summarize repeated failures in the just-completed test file.
195  * The reports above suppress multiple failures from the same source
196  * line; this reports on any tests that did fail multiple times.
197  */
198 static int
199 summarize_comparator(const void *a0, const void *b0)
200 {
201         const struct line *a = a0, *b = b0;
202         if (a->line == 0 && b->line == 0)
203                 return (0);
204         if (a->line == 0)
205                 return (1);
206         if (b->line == 0)
207                 return (-1);
208         return (a->line - b->line);
209 }
210
211 static void
212 summarize(void)
213 {
214         unsigned int i;
215
216         qsort(failed_lines, sizeof(failed_lines)/sizeof(failed_lines[0]),
217             sizeof(failed_lines[0]), summarize_comparator);
218         for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {
219                 if (failed_lines[i].line == 0)
220                         break;
221                 if (failed_lines[i].count > 1)
222                         fprintf(stderr, "%s:%d: Failed %d times\n",
223                             failed_filename, failed_lines[i].line,
224                             failed_lines[i].count);
225         }
226         /* Clear the failure history for the next file. */
227         memset(failed_lines, 0, sizeof(failed_lines));
228 }
229
230 /* Set up a message to display only after a test fails. */
231 void
232 failure(const char *fmt, ...)
233 {
234         va_list ap;
235         va_start(ap, fmt);
236         vsprintf(msg, fmt, ap);
237         va_end(ap);
238 }
239
240 /* Generic assert() just displays the failed condition. */
241 int
242 test_assert(const char *file, int line, int value, const char *condition, void *extra)
243 {
244         ++assertions;
245         if (value) {
246                 msg[0] = '\0';
247                 return (value);
248         }
249         failures ++;
250         if (!verbose && previous_failures(file, line))
251                 return (value);
252         fprintf(stderr, "%s:%d: Assertion failed\n", file, line);
253         fprintf(stderr, "   Condition: %s\n", condition);
254         report_failure(extra);
255         return (value);
256 }
257
258 /* assertEqualInt() displays the values of the two integers. */
259 int
260 test_assert_equal_int(const char *file, int line,
261     int v1, const char *e1, int v2, const char *e2, void *extra)
262 {
263         ++assertions;
264         if (v1 == v2) {
265                 msg[0] = '\0';
266                 return (1);
267         }
268         failures ++;
269         if (!verbose && previous_failures(file, line))
270                 return (0);
271         fprintf(stderr, "%s:%d: Assertion failed: Ints not equal\n",
272             file, line);
273         fprintf(stderr, "      %s=%d\n", e1, v1);
274         fprintf(stderr, "      %s=%d\n", e2, v2);
275         report_failure(extra);
276         return (0);
277 }
278
279 static void strdump(const char *p)
280 {
281         if (p == NULL) {
282                 fprintf(stderr, "(null)");
283                 return;
284         }
285         fprintf(stderr, "\"");
286         while (*p != '\0') {
287                 unsigned int c = 0xff & *p++;
288                 switch (c) {
289                 case '\a': fprintf(stderr, "\a"); break;
290                 case '\b': fprintf(stderr, "\b"); break;
291                 case '\n': fprintf(stderr, "\n"); break;
292                 case '\r': fprintf(stderr, "\r"); break;
293                 default:
294                         if (c >= 32 && c < 127)
295                                 fprintf(stderr, "%c", c);
296                         else
297                                 fprintf(stderr, "\\x%02X", c);
298                 }
299         }
300         fprintf(stderr, "\"");
301 }
302
303 /* assertEqualString() displays the values of the two strings. */
304 int
305 test_assert_equal_string(const char *file, int line,
306     const char *v1, const char *e1,
307     const char *v2, const char *e2,
308     void *extra)
309 {
310         ++assertions;
311         if (v1 == NULL || v2 == NULL) {
312                 if (v1 == v2) {
313                         msg[0] = '\0';
314                         return (1);
315                 }
316         } else if (strcmp(v1, v2) == 0) {
317                 msg[0] = '\0';
318                 return (1);
319         }
320         failures ++;
321         if (!verbose && previous_failures(file, line))
322                 return (0);
323         fprintf(stderr, "%s:%d: Assertion failed: Strings not equal\n",
324             file, line);
325         fprintf(stderr, "      %s = ", e1);
326         strdump(v1);
327         fprintf(stderr, " (length %d)\n", v1 == NULL ? 0 : strlen(v1));
328         fprintf(stderr, "      %s = ", e2);
329         strdump(v2);
330         fprintf(stderr, " (length %d)\n", v2 == NULL ? 0 : strlen(v2));
331         report_failure(extra);
332         return (0);
333 }
334
335 static void wcsdump(const wchar_t *w)
336 {
337         if (w == NULL) {
338                 fprintf(stderr, "(null)");
339                 return;
340         }
341         fprintf(stderr, "\"");
342         while (*w != L'\0') {
343                 unsigned int c = *w++;
344                 if (c >= 32 && c < 127)
345                         fprintf(stderr, "%c", c);
346                 else if (c < 256)
347                         fprintf(stderr, "\\x%02X", c);
348                 else if (c < 0x10000)
349                         fprintf(stderr, "\\u%04X", c);
350                 else
351                         fprintf(stderr, "\\U%08X", c);
352         }
353         fprintf(stderr, "\"");
354 }
355
356 /* assertEqualWString() displays the values of the two strings. */
357 int
358 test_assert_equal_wstring(const char *file, int line,
359     const wchar_t *v1, const char *e1,
360     const wchar_t *v2, const char *e2,
361     void *extra)
362 {
363         ++assertions;
364         if (v1 == NULL) {
365                 if (v2 == NULL) {
366                         msg[0] = '\0';
367                         return (1);
368                 }
369         } else if (v2 == NULL) {
370                 if (v1 == NULL) {
371                         msg[0] = '\0';
372                         return (1);
373                 }
374         } else if (wcscmp(v1, v2) == 0) {
375                 msg[0] = '\0';
376                 return (1);
377         }
378         failures ++;
379         if (!verbose && previous_failures(file, line))
380                 return (0);
381         fprintf(stderr, "%s:%d: Assertion failed: Unicode strings not equal\n",
382             file, line);
383         fprintf(stderr, "      %s = ", e1);
384         wcsdump(v1);
385         fprintf(stderr, "\n");
386         fprintf(stderr, "      %s = ", e2);
387         wcsdump(v2);
388         fprintf(stderr, "\n");
389         report_failure(extra);
390         return (0);
391 }
392
393 /*
394  * Pretty standard hexdump routine.  As a bonus, if ref != NULL, then
395  * any bytes in p that differ from ref will be highlighted with '_'
396  * before and after the hex value.
397  */
398 static void
399 hexdump(const char *p, const char *ref, size_t l, size_t offset)
400 {
401         size_t i, j;
402         char sep;
403
404         for(i=0; i < l; i+=16) {
405                 fprintf(stderr, "%04x", i + offset);
406                 sep = ' ';
407                 for (j = 0; j < 16 && i + j < l; j++) {
408                         if (ref != NULL && p[i + j] != ref[i + j])
409                                 sep = '_';
410                         fprintf(stderr, "%c%02x", sep, 0xff & (int)p[i+j]);
411                         if (ref != NULL && p[i + j] == ref[i + j])
412                                 sep = ' ';
413                 }
414                 for (; j < 16; j++) {
415                         fprintf(stderr, "%c  ", sep);
416                         sep = ' ';
417                 }
418                 fprintf(stderr, "%c", sep);
419                 for (j=0; j < 16 && i + j < l; j++) {
420                         int c = p[i + j];
421                         if (c >= ' ' && c <= 126)
422                                 fprintf(stderr, "%c", c);
423                         else
424                                 fprintf(stderr, ".");
425                 }
426                 fprintf(stderr, "\n");
427         }
428 }
429
430 /* assertEqualMem() displays the values of the two memory blocks. */
431 /* TODO: For long blocks, hexdump the first bytes that actually differ. */
432 int
433 test_assert_equal_mem(const char *file, int line,
434     const char *v1, const char *e1,
435     const char *v2, const char *e2,
436     size_t l, const char *ld, void *extra)
437 {
438         ++assertions;
439         if (v1 == NULL || v2 == NULL) {
440                 if (v1 == v2) {
441                         msg[0] = '\0';
442                         return (1);
443                 }
444         } else if (memcmp(v1, v2, l) == 0) {
445                 msg[0] = '\0';
446                 return (1);
447         }
448         failures ++;
449         if (!verbose && previous_failures(file, line))
450                 return (0);
451         fprintf(stderr, "%s:%d: Assertion failed: memory not equal\n",
452             file, line);
453         fprintf(stderr, "      size %s = %d\n", ld, (int)l);
454         fprintf(stderr, "      Dump of %s\n", e1);
455         hexdump(v1, v2, l < 32 ? l : 32, 0);
456         fprintf(stderr, "      Dump of %s\n", e2);
457         hexdump(v2, v1, l < 32 ? l : 32, 0);
458         fprintf(stderr, "\n");
459         report_failure(extra);
460         return (0);
461 }
462
463 int
464 test_assert_empty_file(const char *f1fmt, ...)
465 {
466         char buff[1024];
467         char f1[1024];
468         struct stat st;
469         va_list ap;
470         ssize_t s;
471         int fd;
472
473
474         va_start(ap, f1fmt);
475         vsprintf(f1, f1fmt, ap);
476         va_end(ap);
477
478         if (stat(f1, &st) != 0) {
479                 fprintf(stderr, "%s:%d: Could not stat: %s\n", test_filename, test_line, f1);
480                 report_failure(NULL);
481                 return (0);
482         }
483         if (st.st_size == 0)
484                 return (1);
485
486         failures ++;
487         if (!verbose && previous_failures(test_filename, test_line))
488                 return (0);
489
490         fprintf(stderr, "%s:%d: File not empty: %s\n", test_filename, test_line, f1);
491         fprintf(stderr, "    File size: %d\n", (int)st.st_size);
492         fprintf(stderr, "    Contents:\n");
493         fd = open(f1, O_RDONLY);
494         if (fd < 0) {
495                 fprintf(stderr, "    Unable to open %s\n", f1);
496         } else {
497                 s = sizeof(buff) < st.st_size ? sizeof(buff) : st.st_size;
498                 s = read(fd, buff, s);
499                 hexdump(buff, NULL, s, 0);
500         }
501         report_failure(NULL);
502         return (0);
503 }
504
505 int
506 test_assert_non_empty_file(const char *f1fmt, ...)
507 {
508         char f1[1024];
509         struct stat st;
510         va_list ap;
511
512
513         va_start(ap, f1fmt);
514         vsprintf(f1, f1fmt, ap);
515         va_end(ap);
516
517         if (stat(f1, &st) != 0) {
518                 fprintf(stderr, "%s:%d: Could not stat: %s\n",
519                     test_filename, test_line, f1);
520                 report_failure(NULL);
521                 return (0);
522         }
523         if (st.st_size != 0)
524                 return (1);
525
526         failures ++;
527         if (!verbose && previous_failures(test_filename, test_line))
528                 return (0);
529
530         fprintf(stderr, "%s:%d: File empty: %s\n",
531             test_filename, test_line, f1);
532         report_failure(NULL);
533         return (0);
534 }
535
536 /* assertEqualFile() asserts that two files have the same contents. */
537 /* TODO: hexdump the first bytes that actually differ. */
538 int
539 test_assert_equal_file(const char *f1, const char *f2pattern, ...)
540 {
541         char f2[1024];
542         va_list ap;
543         char buff1[1024];
544         char buff2[1024];
545         int fd1, fd2;
546         int n1, n2;
547
548         va_start(ap, f2pattern);
549         vsprintf(f2, f2pattern, ap);
550         va_end(ap);
551
552         fd1 = open(f1, O_RDONLY);
553         fd2 = open(f2, O_RDONLY);
554         for (;;) {
555                 n1 = read(fd1, buff1, sizeof(buff1));
556                 n2 = read(fd2, buff2, sizeof(buff2));
557                 if (n1 != n2)
558                         break;
559                 if (n1 == 0 && n2 == 0)
560                         return (1);
561                 if (memcmp(buff1, buff2, n1) != 0)
562                         break;
563         }
564         failures ++;
565         if (!verbose && previous_failures(test_filename, test_line))
566                 return (0);
567         fprintf(stderr, "%s:%d: Files are not identical\n",
568             test_filename, test_line);
569         fprintf(stderr, "  file1=\"%s\"\n", f1);
570         fprintf(stderr, "  file2=\"%s\"\n", f2);
571         report_failure(test_extra);
572         return (0);
573 }
574
575 int
576 test_assert_file_exists(const char *fpattern, ...)
577 {
578         char f[1024];
579         va_list ap;
580
581         va_start(ap, fpattern);
582         vsprintf(f, fpattern, ap);
583         va_end(ap);
584
585         if (!access(f, F_OK))
586                 return (1);
587         if (!previous_failures(test_filename, test_line)) {
588                 fprintf(stderr, "%s:%d: File doesn't exist\n",
589                     test_filename, test_line);
590                 fprintf(stderr, "  file=\"%s\"\n", f);
591                 report_failure(test_extra);
592         }
593         return (0);
594 }
595
596 int
597 test_assert_file_not_exists(const char *fpattern, ...)
598 {
599         char f[1024];
600         va_list ap;
601
602         va_start(ap, fpattern);
603         vsprintf(f, fpattern, ap);
604         va_end(ap);
605
606         if (access(f, F_OK))
607                 return (1);
608         if (!previous_failures(test_filename, test_line)) {
609                 fprintf(stderr, "%s:%d: File exists and shouldn't\n",
610                     test_filename, test_line);
611                 fprintf(stderr, "  file=\"%s\"\n", f);
612                 report_failure(test_extra);
613         }
614         return (0);
615 }
616
617 /* assertFileContents() asserts the contents of a file. */
618 int
619 test_assert_file_contents(const void *buff, int s, const char *fpattern, ...)
620 {
621         char f[1024];
622         va_list ap;
623         char *contents;
624         int fd;
625         int n;
626
627         va_start(ap, fpattern);
628         vsprintf(f, fpattern, ap);
629         va_end(ap);
630
631         fd = open(f, O_RDONLY);
632         contents = malloc(s * 2);
633         n = read(fd, contents, s * 2);
634         if (n == s && memcmp(buff, contents, s) == 0) {
635                 free(contents);
636                 return (1);
637         }
638         failures ++;
639         if (!previous_failures(test_filename, test_line)) {
640                 fprintf(stderr, "%s:%d: File contents don't match\n",
641                     test_filename, test_line);
642                 fprintf(stderr, "  file=\"%s\"\n", f);
643                 if (n > 0)
644                         hexdump(contents, buff, n, 0);
645                 else {
646                         fprintf(stderr, "  File empty, contents should be:\n");
647                         hexdump(buff, NULL, s, 0);
648                 }
649                 report_failure(test_extra);
650         }
651         free(contents);
652         return (0);
653 }
654
655 /*
656  * Call standard system() call, but build up the command line using
657  * sprintf() conventions.
658  */
659 int
660 systemf(const char *fmt, ...)
661 {
662         char buff[8192];
663         va_list ap;
664         int r;
665
666         va_start(ap, fmt);
667         vsprintf(buff, fmt, ap);
668         r = system(buff);
669         va_end(ap);
670         return (r);
671 }
672
673 /*
674  * Slurp a file into memory for ease of comparison and testing.
675  * Returns size of file in 'sizep' if non-NULL, null-terminates
676  * data in memory for ease of use.
677  */
678 char *
679 slurpfile(size_t * sizep, const char *fmt, ...)
680 {
681         char filename[8192];
682         struct stat st;
683         va_list ap;
684         char *p;
685         ssize_t bytes_read;
686         int fd;
687         int r;
688
689         va_start(ap, fmt);
690         vsprintf(filename, fmt, ap);
691         va_end(ap);
692
693         fd = open(filename, O_RDONLY);
694         if (fd < 0) {
695                 /* Note: No error; non-existent file is okay here. */
696                 return (NULL);
697         }
698         r = fstat(fd, &st);
699         if (r != 0) {
700                 fprintf(stderr, "Can't stat file %s\n", filename);
701                 close(fd);
702                 return (NULL);
703         }
704         p = malloc(st.st_size + 1);
705         if (p == NULL) {
706                 fprintf(stderr, "Can't allocate %ld bytes of memory to read file %s\n", (long int)st.st_size, filename);
707                 close(fd);
708                 return (NULL);
709         }
710         bytes_read = read(fd, p, st.st_size);
711         if (bytes_read < st.st_size) {
712                 fprintf(stderr, "Can't read file %s\n", filename);
713                 close(fd);
714                 free(p);
715                 return (NULL);
716         }
717         p[st.st_size] = '\0';
718         if (sizep != NULL)
719                 *sizep = (size_t)st.st_size;
720         close(fd);
721         return (p);
722 }
723
724 /*
725  * "list.h" is automatically generated; it just has a lot of lines like:
726  *      DEFINE_TEST(function_name)
727  * It's used above to declare all of the test functions.
728  * We reuse it here to define a list of all tests (functions and names).
729  */
730 #undef DEFINE_TEST
731 #define DEFINE_TEST(n) { n, #n },
732 struct { void (*func)(void); const char *name; } tests[] = {
733         #include "list.h"
734 };
735
736 /*
737  * Each test is run in a private work dir.  Those work dirs
738  * do have consistent and predictable names, in case a group
739  * of tests need to collaborate.  However, there is no provision
740  * for requiring that tests run in a certain order.
741  */
742 static int test_run(int i, const char *tmpdir)
743 {
744         int failures_before = failures;
745
746         if (!quiet_flag) {
747                 printf("%d: %s\n", i, tests[i].name);
748                 fflush(stdout);
749         }
750
751         /*
752          * Always explicitly chdir() in case the last test moved us to
753          * a strange place.
754          */
755         if (chdir(tmpdir)) {
756                 fprintf(stderr,
757                     "ERROR: Couldn't chdir to temp dir %s\n",
758                     tmpdir);
759                 exit(1);
760         }
761         /* Create a temp directory for this specific test. */
762         if (mkdir(tests[i].name, 0755)) {
763                 fprintf(stderr,
764                     "ERROR: Couldn't create temp dir ``%s''\n",
765                     tests[i].name);
766                 exit(1);
767         }
768         /* Chdir() to that work directory. */
769         if (chdir(tests[i].name)) {
770                 fprintf(stderr,
771                     "ERROR: Couldn't chdir to temp dir ``%s''\n",
772                     tests[i].name);
773                 exit(1);
774         }
775         /* Explicitly reset the locale before each test. */
776         setlocale(LC_ALL, "C");
777         /* Run the actual test. */
778         (*tests[i].func)();
779         /* Summarize the results of this test. */
780         summarize();
781         /* If there were no failures, we can remove the work dir. */
782         if (failures == failures_before) {
783                 if (!keep_temp_files && chdir(tmpdir) == 0) {
784                         systemf("rm -rf %s", tests[i].name);
785                 }
786         }
787         /* Return appropriate status. */
788         return (failures == failures_before ? 0 : 1);
789 }
790
791 static void usage(const char *program)
792 {
793         static const int limit = sizeof(tests) / sizeof(tests[0]);
794         int i;
795
796         printf("Usage: %s [options] <test> <test> ...\n", program);
797         printf("Default is to run all tests.\n");
798         printf("Otherwise, specify the numbers of the tests you wish to run.\n");
799         printf("Options:\n");
800         printf("  -d  Dump core after any failure, for debugging.\n");
801         printf("  -k  Keep all temp files.\n");
802         printf("      Default: temp files for successful tests deleted.\n");
803 #ifdef PROGRAM
804         printf("  -p <path>  Path to executable to be tested.\n");
805         printf("      Default: path taken from " ENVBASE " environment variable.\n");
806 #endif
807         printf("  -q  Quiet.\n");
808         printf("  -r <dir>   Path to dir containing reference files.\n");
809         printf("      Default: Current directory.\n");
810         printf("  -v  Verbose.\n");
811         printf("Available tests:\n");
812         for (i = 0; i < limit; i++)
813                 printf("  %d: %s\n", i, tests[i].name);
814         exit(1);
815 }
816
817 #define UUDECODE(c) (((c) - 0x20) & 0x3f)
818
819 void
820 extract_reference_file(const char *name)
821 {
822         char buff[1024];
823         FILE *in, *out;
824
825         sprintf(buff, "%s/%s.uu", refdir, name);
826         in = fopen(buff, "r");
827         failure("Couldn't open reference file %s", buff);
828         assert(in != NULL);
829         if (in == NULL)
830                 return;
831         /* Read up to and including the 'begin' line. */
832         for (;;) {
833                 if (fgets(buff, sizeof(buff), in) == NULL) {
834                         /* TODO: This is a failure. */
835                         return;
836                 }
837                 if (memcmp(buff, "begin ", 6) == 0)
838                         break;
839         }
840         /* Now, decode the rest and write it. */
841         /* Not a lot of error checking here; the input better be right. */
842         out = fopen(name, "w");
843         while (fgets(buff, sizeof(buff), in) != NULL) {
844                 char *p = buff;
845                 int bytes;
846
847                 if (memcmp(buff, "end", 3) == 0)
848                         break;
849
850                 bytes = UUDECODE(*p++);
851                 while (bytes > 0) {
852                         int n = 0;
853                         /* Write out 1-3 bytes from that. */
854                         if (bytes > 0) {
855                                 n = UUDECODE(*p++) << 18;
856                                 n |= UUDECODE(*p++) << 12;
857                                 fputc(n >> 16, out);
858                                 --bytes;
859                         }
860                         if (bytes > 0) {
861                                 n |= UUDECODE(*p++) << 6;
862                                 fputc((n >> 8) & 0xFF, out);
863                                 --bytes;
864                         }
865                         if (bytes > 0) {
866                                 n |= UUDECODE(*p++);
867                                 fputc(n & 0xFF, out);
868                                 --bytes;
869                         }
870                 }
871         }
872         fclose(out);
873         fclose(in);
874 }
875
876
877 int main(int argc, char **argv)
878 {
879         static const int limit = sizeof(tests) / sizeof(tests[0]);
880         int i, tests_run = 0, tests_failed = 0, opt;
881         time_t now;
882         char *refdir_alloc = NULL;
883         char *progname, *p;
884         char tmpdir[256];
885         char tmpdir_timestamp[256];
886
887         /*
888          * Name of this program, used to build root of our temp directory
889          * tree.
890          */
891         progname = p = argv[0];
892         while (*p != '\0') {
893                 if (*p == '/')
894                         progname = p + 1;
895                 ++p;
896         }
897
898 #ifdef PROGRAM
899         /* Get the target program from environment, if available. */
900         testprog = getenv(ENVBASE);
901 #endif
902
903         /* Allow -d to be controlled through the environment. */
904         if (getenv(ENVBASE "_DEBUG") != NULL)
905                 dump_on_failure = 1;
906
907         /* Get the directory holding test files from environment. */
908         refdir = getenv(ENVBASE "_TEST_FILES");
909
910         /*
911          * Parse options.
912          */
913         while ((opt = getopt(argc, argv, "dkp:qr:v")) != -1) {
914                 switch (opt) {
915                 case 'd':
916                         dump_on_failure = 1;
917                         break;
918                 case 'k':
919                         keep_temp_files = 1;
920                         break;
921                 case 'p':
922 #ifdef PROGRAM
923                         testprog = optarg;
924 #else
925                         usage(progname);
926 #endif
927                         break;
928                 case 'q':
929                         quiet_flag++;
930                         break;
931                 case 'r':
932                         refdir = optarg;
933                         break;
934                 case 'v':
935                         verbose = 1;
936                         break;
937                 case '?':
938                 default:
939                         usage(progname);
940                 }
941         }
942         argc -= optind;
943         argv += optind;
944
945         /*
946          * Sanity-check that our options make sense.
947          */
948 #ifdef PROGRAM
949         if (testprog == NULL)
950                 usage(progname);
951 #endif
952
953         /*
954          * Create a temp directory for the following tests.
955          * Include the time the tests started as part of the name,
956          * to make it easier to track the results of multiple tests.
957          */
958         now = time(NULL);
959         for (i = 0; i < 1000; i++) {
960                 strftime(tmpdir_timestamp, sizeof(tmpdir_timestamp),
961                     "%Y-%m-%dT%H.%M.%S",
962                     localtime(&now));
963                 sprintf(tmpdir, "/tmp/%s.%s-%03d", progname, tmpdir_timestamp, i);
964                 if (mkdir(tmpdir,0755) == 0)
965                         break;
966                 if (errno == EEXIST)
967                         continue;
968                 fprintf(stderr, "ERROR: Unable to create temp directory %s\n",
969                     tmpdir);
970                 exit(1);
971         }
972
973         /*
974          * If the user didn't specify a directory for locating
975          * reference files, use the current directory for that.
976          */
977         if (refdir == NULL) {
978                 systemf("/bin/pwd > %s/refdir", tmpdir);
979                 refdir = refdir_alloc = slurpfile(NULL, "%s/refdir", tmpdir);
980                 p = refdir + strlen(refdir);
981                 while (p[-1] == '\n') {
982                         --p;
983                         *p = '\0';
984                 }
985                 systemf("rm %s/refdir", tmpdir);
986         }
987
988         /*
989          * Banner with basic information.
990          */
991         if (!quiet_flag) {
992                 printf("Running tests in: %s\n", tmpdir);
993                 printf("Reference files will be read from: %s\n", refdir);
994 #ifdef PROGRAM
995                 printf("Running tests on: %s\n", testprog);
996 #endif
997                 printf("Exercising: ");
998                 fflush(stdout);
999                 printf("%s\n", EXTRA_VERSION);
1000         }
1001
1002         /*
1003          * Run some or all of the individual tests.
1004          */
1005         if (argc == 0) {
1006                 /* Default: Run all tests. */
1007                 for (i = 0; i < limit; i++) {
1008                         if (test_run(i, tmpdir))
1009                                 tests_failed++;
1010                         tests_run++;
1011                 }
1012         } else {
1013                 while (*(argv) != NULL) {
1014                         i = atoi(*argv);
1015                         if (**argv < '0' || **argv > '9' || i < 0 || i >= limit) {
1016                                 printf("*** INVALID Test %s\n", *argv);
1017                                 usage(progname);
1018                         } else {
1019                                 if (test_run(i, tmpdir))
1020                                         tests_failed++;
1021                                 tests_run++;
1022                         }
1023                         argv++;
1024                 }
1025         }
1026
1027         /*
1028          * Report summary statistics.
1029          */
1030         if (!quiet_flag) {
1031                 printf("\n");
1032                 printf("%d of %d tests reported failures\n",
1033                     tests_failed, tests_run);
1034                 printf(" Total of %d assertions checked.\n", assertions);
1035                 printf(" Total of %d assertions failed.\n", failures);
1036                 printf(" Total of %d assertions skipped.\n", skips);
1037         }
1038
1039         free(refdir_alloc);
1040
1041         /* If the final tmpdir is empty, we can remove it. */
1042         /* This should be the usual case when all tests succeed. */
1043         rmdir(tmpdir);
1044
1045         return (tests_failed);
1046 }