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