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