]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/cpio/test/main.c
Merge state reuse for tcp.
[FreeBSD/FreeBSD.git] / usr.bin / cpio / 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 "bsdcpio"    /* Name of program being tested. */
43 #define ENVBASE "BSDCPIO" /* 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 /* assertEqualFile() asserts that two files have the same contents. */
506 /* TODO: hexdump the first bytes that actually differ. */
507 int
508 test_assert_equal_file(const char *f1, const char *f2pattern, ...)
509 {
510         char f2[1024];
511         va_list ap;
512         char buff1[1024];
513         char buff2[1024];
514         int fd1, fd2;
515         int n1, n2;
516
517         va_start(ap, f2pattern);
518         vsprintf(f2, f2pattern, ap);
519         va_end(ap);
520
521         fd1 = open(f1, O_RDONLY);
522         fd2 = open(f2, O_RDONLY);
523         for (;;) {
524                 n1 = read(fd1, buff1, sizeof(buff1));
525                 n2 = read(fd2, buff2, sizeof(buff2));
526                 if (n1 != n2)
527                         break;
528                 if (n1 == 0 && n2 == 0)
529                         return (1);
530                 if (memcmp(buff1, buff2, n1) != 0)
531                         break;
532         }
533         failures ++;
534         if (!verbose && previous_failures(test_filename, test_line))
535                 return (0);
536         fprintf(stderr, "%s:%d: Files are not identical\n",
537             test_filename, test_line);
538         fprintf(stderr, "  file1=\"%s\"\n", f1);
539         fprintf(stderr, "  file2=\"%s\"\n", f2);
540         report_failure(test_extra);
541         return (0);
542 }
543
544 int
545 test_assert_file_exists(const char *fpattern, ...)
546 {
547         char f[1024];
548         va_list ap;
549
550         va_start(ap, fpattern);
551         vsprintf(f, fpattern, ap);
552         va_end(ap);
553
554         if (!access(f, F_OK))
555                 return (1);
556         if (!previous_failures(test_filename, test_line)) {
557                 fprintf(stderr, "%s:%d: File doesn't exist\n",
558                     test_filename, test_line);
559                 fprintf(stderr, "  file=\"%s\"\n", f);
560                 report_failure(test_extra);
561         }
562         return (0);
563 }
564
565 int
566 test_assert_file_not_exists(const char *fpattern, ...)
567 {
568         char f[1024];
569         va_list ap;
570
571         va_start(ap, fpattern);
572         vsprintf(f, fpattern, ap);
573         va_end(ap);
574
575         if (access(f, F_OK))
576                 return (1);
577         if (!previous_failures(test_filename, test_line)) {
578                 fprintf(stderr, "%s:%d: File exists and shouldn't\n",
579                     test_filename, test_line);
580                 fprintf(stderr, "  file=\"%s\"\n", f);
581                 report_failure(test_extra);
582         }
583         return (0);
584 }
585
586 /* assertFileContents() asserts the contents of a file. */
587 int
588 test_assert_file_contents(const void *buff, int s, const char *fpattern, ...)
589 {
590         char f[1024];
591         va_list ap;
592         char *contents;
593         int fd;
594         int n;
595
596         va_start(ap, fpattern);
597         vsprintf(f, fpattern, ap);
598         va_end(ap);
599
600         fd = open(f, O_RDONLY);
601         contents = malloc(s * 2);
602         n = read(fd, contents, s * 2);
603         if (n == s && memcmp(buff, contents, s) == 0) {
604                 free(contents);
605                 return (1);
606         }
607         failures ++;
608         if (!previous_failures(test_filename, test_line)) {
609                 fprintf(stderr, "%s:%d: File contents don't match\n",
610                     test_filename, test_line);
611                 fprintf(stderr, "  file=\"%s\"\n", f);
612                 if (n > 0)
613                         hexdump(contents, buff, n, 0);
614                 else {
615                         fprintf(stderr, "  File empty, contents should be:\n");
616                         hexdump(buff, NULL, s, 0);
617                 }
618                 report_failure(test_extra);
619         }
620         free(contents);
621         return (0);
622 }
623
624 /*
625  * Call standard system() call, but build up the command line using
626  * sprintf() conventions.
627  */
628 int
629 systemf(const char *fmt, ...)
630 {
631         char buff[8192];
632         va_list ap;
633         int r;
634
635         va_start(ap, fmt);
636         vsprintf(buff, fmt, ap);
637         r = system(buff);
638         va_end(ap);
639         return (r);
640 }
641
642 /*
643  * Slurp a file into memory for ease of comparison and testing.
644  * Returns size of file in 'sizep' if non-NULL, null-terminates
645  * data in memory for ease of use.
646  */
647 char *
648 slurpfile(size_t * sizep, const char *fmt, ...)
649 {
650         char filename[8192];
651         struct stat st;
652         va_list ap;
653         char *p;
654         ssize_t bytes_read;
655         int fd;
656         int r;
657
658         va_start(ap, fmt);
659         vsprintf(filename, fmt, ap);
660         va_end(ap);
661
662         fd = open(filename, O_RDONLY);
663         if (fd < 0) {
664                 /* Note: No error; non-existent file is okay here. */
665                 return (NULL);
666         }
667         r = fstat(fd, &st);
668         if (r != 0) {
669                 fprintf(stderr, "Can't stat file %s\n", filename);
670                 close(fd);
671                 return (NULL);
672         }
673         p = malloc(st.st_size + 1);
674         if (p == NULL) {
675                 fprintf(stderr, "Can't allocate %ld bytes of memory to read file %s\n", (long int)st.st_size, filename);
676                 close(fd);
677                 return (NULL);
678         }
679         bytes_read = read(fd, p, st.st_size);
680         if (bytes_read < st.st_size) {
681                 fprintf(stderr, "Can't read file %s\n", filename);
682                 close(fd);
683                 free(p);
684                 return (NULL);
685         }
686         p[st.st_size] = '\0';
687         if (sizep != NULL)
688                 *sizep = (size_t)st.st_size;
689         close(fd);
690         return (p);
691 }
692
693 /*
694  * "list.h" is automatically generated; it just has a lot of lines like:
695  *      DEFINE_TEST(function_name)
696  * It's used above to declare all of the test functions.
697  * We reuse it here to define a list of all tests (functions and names).
698  */
699 #undef DEFINE_TEST
700 #define DEFINE_TEST(n) { n, #n },
701 struct { void (*func)(void); const char *name; } tests[] = {
702         #include "list.h"
703 };
704
705 /*
706  * Each test is run in a private work dir.  Those work dirs
707  * do have consistent and predictable names, in case a group
708  * of tests need to collaborate.  However, there is no provision
709  * for requiring that tests run in a certain order.
710  */
711 static int test_run(int i, const char *tmpdir)
712 {
713         int failures_before = failures;
714
715         if (!quiet_flag) {
716                 printf("%d: %s\n", i, tests[i].name);
717                 fflush(stdout);
718         }
719
720         /*
721          * Always explicitly chdir() in case the last test moved us to
722          * a strange place.
723          */
724         if (chdir(tmpdir)) {
725                 fprintf(stderr,
726                     "ERROR: Couldn't chdir to temp dir %s\n",
727                     tmpdir);
728                 exit(1);
729         }
730         /* Create a temp directory for this specific test. */
731         if (mkdir(tests[i].name, 0755)) {
732                 fprintf(stderr,
733                     "ERROR: Couldn't create temp dir ``%s''\n",
734                     tests[i].name);
735                 exit(1);
736         }
737         /* Chdir() to that work directory. */
738         if (chdir(tests[i].name)) {
739                 fprintf(stderr,
740                     "ERROR: Couldn't chdir to temp dir ``%s''\n",
741                     tests[i].name);
742                 exit(1);
743         }
744         /* Explicitly reset the locale before each test. */
745         setlocale(LC_ALL, "C");
746         /* Run the actual test. */
747         (*tests[i].func)();
748         /* Summarize the results of this test. */
749         summarize();
750         /* If there were no failures, we can remove the work dir. */
751         if (failures == failures_before) {
752                 if (!keep_temp_files && chdir(tmpdir) == 0) {
753                         systemf("rm -rf %s", tests[i].name);
754                 }
755         }
756         /* Return appropriate status. */
757         return (failures == failures_before ? 0 : 1);
758 }
759
760 static void usage(const char *program)
761 {
762         static const int limit = sizeof(tests) / sizeof(tests[0]);
763         int i;
764
765         printf("Usage: %s [options] <test> <test> ...\n", program);
766         printf("Default is to run all tests.\n");
767         printf("Otherwise, specify the numbers of the tests you wish to run.\n");
768         printf("Options:\n");
769         printf("  -d  Dump core after any failure, for debugging.\n");
770         printf("  -k  Keep all temp files.\n");
771         printf("      Default: temp files for successful tests deleted.\n");
772 #ifdef PROGRAM
773         printf("  -p <path>  Path to executable to be tested.\n");
774         printf("      Default: path taken from " ENVBASE " environment variable.\n");
775 #endif
776         printf("  -q  Quiet.\n");
777         printf("  -r <dir>   Path to dir containing reference files.\n");
778         printf("      Default: Current directory.\n");
779         printf("  -v  Verbose.\n");
780         printf("Available tests:\n");
781         for (i = 0; i < limit; i++)
782                 printf("  %d: %s\n", i, tests[i].name);
783         exit(1);
784 }
785
786 #define UUDECODE(c) (((c) - 0x20) & 0x3f)
787
788 void
789 extract_reference_file(const char *name)
790 {
791         char buff[1024];
792         FILE *in, *out;
793
794         sprintf(buff, "%s/%s.uu", refdir, name);
795         in = fopen(buff, "r");
796         failure("Couldn't open reference file %s", buff);
797         assert(in != NULL);
798         if (in == NULL)
799                 return;
800         /* Read up to and including the 'begin' line. */
801         for (;;) {
802                 if (fgets(buff, sizeof(buff), in) == NULL) {
803                         /* TODO: This is a failure. */
804                         return;
805                 }
806                 if (memcmp(buff, "begin ", 6) == 0)
807                         break;
808         }
809         /* Now, decode the rest and write it. */
810         /* Not a lot of error checking here; the input better be right. */
811         out = fopen(name, "w");
812         while (fgets(buff, sizeof(buff), in) != NULL) {
813                 char *p = buff;
814                 int bytes;
815
816                 if (memcmp(buff, "end", 3) == 0)
817                         break;
818
819                 bytes = UUDECODE(*p++);
820                 while (bytes > 0) {
821                         int n = 0;
822                         /* Write out 1-3 bytes from that. */
823                         if (bytes > 0) {
824                                 n = UUDECODE(*p++) << 18;
825                                 n |= UUDECODE(*p++) << 12;
826                                 fputc(n >> 16, out);
827                                 --bytes;
828                         }
829                         if (bytes > 0) {
830                                 n |= UUDECODE(*p++) << 6;
831                                 fputc((n >> 8) & 0xFF, out);
832                                 --bytes;
833                         }
834                         if (bytes > 0) {
835                                 n |= UUDECODE(*p++);
836                                 fputc(n & 0xFF, out);
837                                 --bytes;
838                         }
839                 }
840         }
841         fclose(out);
842         fclose(in);
843 }
844
845
846 int main(int argc, char **argv)
847 {
848         static const int limit = sizeof(tests) / sizeof(tests[0]);
849         int i, tests_run = 0, tests_failed = 0, opt;
850         time_t now;
851         char *refdir_alloc = NULL;
852         char *progname, *p;
853         char tmpdir[256];
854         char tmpdir_timestamp[256];
855
856         /*
857          * Name of this program, used to build root of our temp directory
858          * tree.
859          */
860         progname = p = argv[0];
861         while (*p != '\0') {
862                 if (*p == '/')
863                         progname = p + 1;
864                 ++p;
865         }
866
867 #ifdef PROGRAM
868         /* Get the target program from environment, if available. */
869         testprog = getenv(ENVBASE);
870 #endif
871
872         /* Allow -d to be controlled through the environment. */
873         if (getenv(ENVBASE "_DEBUG") != NULL)
874                 dump_on_failure = 1;
875
876         /* Get the directory holding test files from environment. */
877         refdir = getenv(ENVBASE "_TEST_FILES");
878
879         /*
880          * Parse options.
881          */
882         while ((opt = getopt(argc, argv, "dkp:qr:v")) != -1) {
883                 switch (opt) {
884                 case 'd':
885                         dump_on_failure = 1;
886                         break;
887                 case 'k':
888                         keep_temp_files = 1;
889                         break;
890                 case 'p':
891 #ifdef PROGRAM
892                         testprog = optarg;
893 #else
894                         usage(progname);
895 #endif
896                         break;
897                 case 'q':
898                         quiet_flag++;
899                         break;
900                 case 'r':
901                         refdir = optarg;
902                         break;
903                 case 'v':
904                         verbose = 1;
905                         break;
906                 case '?':
907                 default:
908                         usage(progname);
909                 }
910         }
911         argc -= optind;
912         argv += optind;
913
914         /*
915          * Sanity-check that our options make sense.
916          */
917 #ifdef PROGRAM
918         if (testprog == NULL)
919                 usage(progname);
920 #endif
921
922         /*
923          * Create a temp directory for the following tests.
924          * Include the time the tests started as part of the name,
925          * to make it easier to track the results of multiple tests.
926          */
927         now = time(NULL);
928         for (i = 0; i < 1000; i++) {
929                 strftime(tmpdir_timestamp, sizeof(tmpdir_timestamp),
930                     "%Y-%m-%dT%H.%M.%S",
931                     localtime(&now));
932                 sprintf(tmpdir, "/tmp/%s.%s-%03d", progname, tmpdir_timestamp, i);
933                 if (mkdir(tmpdir,0755) == 0)
934                         break;
935                 if (errno == EEXIST)
936                         continue;
937                 fprintf(stderr, "ERROR: Unable to create temp directory %s\n",
938                     tmpdir);
939                 exit(1);
940         }
941
942         /*
943          * If the user didn't specify a directory for locating
944          * reference files, use the current directory for that.
945          */
946         if (refdir == NULL) {
947                 systemf("/bin/pwd > %s/refdir", tmpdir);
948                 refdir = refdir_alloc = slurpfile(NULL, "%s/refdir", tmpdir);
949                 p = refdir + strlen(refdir);
950                 while (p[-1] == '\n') {
951                         --p;
952                         *p = '\0';
953                 }
954                 systemf("rm %s/refdir", tmpdir);
955         }
956
957         /*
958          * Banner with basic information.
959          */
960         if (!quiet_flag) {
961                 printf("Running tests in: %s\n", tmpdir);
962                 printf("Reference files will be read from: %s\n", refdir);
963 #ifdef PROGRAM
964                 printf("Running tests on: %s\n", testprog);
965 #endif
966                 printf("Exercising: ");
967                 fflush(stdout);
968                 printf("%s\n", EXTRA_VERSION);
969         }
970
971         /*
972          * Run some or all of the individual tests.
973          */
974         if (argc == 0) {
975                 /* Default: Run all tests. */
976                 for (i = 0; i < limit; i++) {
977                         if (test_run(i, tmpdir))
978                                 tests_failed++;
979                         tests_run++;
980                 }
981         } else {
982                 while (*(argv) != NULL) {
983                         i = atoi(*argv);
984                         if (**argv < '0' || **argv > '9' || i < 0 || i >= limit) {
985                                 printf("*** INVALID Test %s\n", *argv);
986                                 usage(progname);
987                         } else {
988                                 if (test_run(i, tmpdir))
989                                         tests_failed++;
990                                 tests_run++;
991                         }
992                         argv++;
993                 }
994         }
995
996         /*
997          * Report summary statistics.
998          */
999         if (!quiet_flag) {
1000                 printf("\n");
1001                 printf("%d of %d tests reported failures\n",
1002                     tests_failed, tests_run);
1003                 printf(" Total of %d assertions checked.\n", assertions);
1004                 printf(" Total of %d assertions failed.\n", failures);
1005                 printf(" Total of %d assertions skipped.\n", skips);
1006         }
1007
1008         free(refdir_alloc);
1009
1010         /* If the final tmpdir is empty, we can remove it. */
1011         /* This should be the usual case when all tests succeed. */
1012         rmdir(tmpdir);
1013
1014         return (tests_failed);
1015 }