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