]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - contrib/libarchive/libarchive/test/main.c
Fix bspatch heap overflow vulnerability. [SA-16:29]
[FreeBSD/releng/10.2.git] / contrib / libarchive / libarchive / test / main.c
1 /*
2  * Copyright (c) 2003-2009 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 #include "test.h"
27 #include "test_utils.h"
28 #ifdef HAVE_SYS_IOCTL_H
29 #include <sys/ioctl.h>
30 #endif
31 #ifdef HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34 #include <errno.h>
35 #ifdef HAVE_ICONV_H
36 #include <iconv.h>
37 #endif
38 /*
39  * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
40  * As the include guards don't agree, the order of include is important.
41  */
42 #ifdef HAVE_LINUX_EXT2_FS_H
43 #include <linux/ext2_fs.h>      /* for Linux file flags */
44 #endif
45 #if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
46 #include <ext2fs/ext2_fs.h>     /* Linux file flags, broken on Cygwin */
47 #endif
48 #include <limits.h>
49 #include <locale.h>
50 #ifdef HAVE_SIGNAL_H
51 #include <signal.h>
52 #endif
53 #include <stdarg.h>
54 #include <time.h>
55
56 /*
57  * This same file is used pretty much verbatim for all test harnesses.
58  *
59  * The next few lines are the only differences.
60  * TODO: Move this into a separate configuration header, have all test
61  * suites share one copy of this file.
62  */
63 __FBSDID("$FreeBSD$");
64 #define KNOWNREF        "test_compat_gtar_1.tar.uu"
65 #define ENVBASE "LIBARCHIVE" /* Prefix for environment variables. */
66 #undef  PROGRAM              /* Testing a library, not a program. */
67 #define LIBRARY "libarchive"
68 #define EXTRA_DUMP(x)   archive_error_string((struct archive *)(x))
69 #define EXTRA_ERRNO(x)  archive_errno((struct archive *)(x))
70 #define EXTRA_VERSION   archive_version_string()
71
72 /*
73  *
74  * Windows support routines
75  *
76  * Note: Configuration is a tricky issue.  Using HAVE_* feature macros
77  * in the test harness is dangerous because they cover up
78  * configuration errors.  The classic example of this is omitting a
79  * configure check.  If libarchive and libarchive_test both look for
80  * the same feature macro, such errors are hard to detect.  Platform
81  * macros (e.g., _WIN32 or __GNUC__) are a little better, but can
82  * easily lead to very messy code.  It's best to limit yourself
83  * to only the most generic programming techniques in the test harness
84  * and thus avoid conditionals altogether.  Where that's not possible,
85  * try to minimize conditionals by grouping platform-specific tests in
86  * one place (e.g., test_acl_freebsd) or by adding new assert()
87  * functions (e.g., assertMakeHardlink()) to cover up platform
88  * differences.  Platform-specific coding in libarchive_test is often
89  * a symptom that some capability is missing from libarchive itself.
90  */
91 #if defined(_WIN32) && !defined(__CYGWIN__)
92 #include <io.h>
93 #include <direct.h>
94 #include <windows.h>
95 #ifndef F_OK
96 #define F_OK (0)
97 #endif
98 #ifndef S_ISDIR
99 #define S_ISDIR(m)  ((m) & _S_IFDIR)
100 #endif
101 #ifndef S_ISREG
102 #define S_ISREG(m)  ((m) & _S_IFREG)
103 #endif
104 #if !defined(__BORLANDC__)
105 #define access _access
106 #undef chdir
107 #define chdir _chdir
108 #endif
109 #ifndef fileno
110 #define fileno _fileno
111 #endif
112 /*#define fstat _fstat64*/
113 #if !defined(__BORLANDC__)
114 #define getcwd _getcwd
115 #endif
116 #define lstat stat
117 /*#define lstat _stat64*/
118 /*#define stat _stat64*/
119 #define rmdir _rmdir
120 #if !defined(__BORLANDC__)
121 #define strdup _strdup
122 #define umask _umask
123 #endif
124 #define int64_t __int64
125 #endif
126
127 #if defined(HAVE__CrtSetReportMode)
128 # include <crtdbg.h>
129 #endif
130
131 #if defined(_WIN32) && !defined(__CYGWIN__)
132 static void     *GetFunctionKernel32(const char *);
133 static int       my_CreateSymbolicLinkA(const char *, const char *, int);
134 static int       my_CreateHardLinkA(const char *, const char *);
135 static int       my_GetFileInformationByName(const char *,
136                      BY_HANDLE_FILE_INFORMATION *);
137
138 static void *
139 GetFunctionKernel32(const char *name)
140 {
141         static HINSTANCE lib;
142         static int set;
143         if (!set) {
144                 set = 1;
145                 lib = LoadLibrary("kernel32.dll");
146         }
147         if (lib == NULL) {
148                 fprintf(stderr, "Can't load kernel32.dll?!\n");
149                 exit(1);
150         }
151         return (void *)GetProcAddress(lib, name);
152 }
153
154 static int
155 my_CreateSymbolicLinkA(const char *linkname, const char *target, int flags)
156 {
157         static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, DWORD);
158         static int set;
159         if (!set) {
160                 set = 1;
161                 f = GetFunctionKernel32("CreateSymbolicLinkA");
162         }
163         return f == NULL ? 0 : (*f)(linkname, target, flags);
164 }
165
166 static int
167 my_CreateHardLinkA(const char *linkname, const char *target)
168 {
169         static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, LPSECURITY_ATTRIBUTES);
170         static int set;
171         if (!set) {
172                 set = 1;
173                 f = GetFunctionKernel32("CreateHardLinkA");
174         }
175         return f == NULL ? 0 : (*f)(linkname, target, NULL);
176 }
177
178 static int
179 my_GetFileInformationByName(const char *path, BY_HANDLE_FILE_INFORMATION *bhfi)
180 {
181         HANDLE h;
182         int r;
183
184         memset(bhfi, 0, sizeof(*bhfi));
185         h = CreateFile(path, FILE_READ_ATTRIBUTES, 0, NULL,
186                 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
187         if (h == INVALID_HANDLE_VALUE)
188                 return (0);
189         r = GetFileInformationByHandle(h, bhfi);
190         CloseHandle(h);
191         return (r);
192 }
193 #endif
194
195 #if defined(HAVE__CrtSetReportMode)
196 static void
197 invalid_parameter_handler(const wchar_t * expression,
198     const wchar_t * function, const wchar_t * file,
199     unsigned int line, uintptr_t pReserved)
200 {
201         /* nop */
202 }
203 #endif
204
205 /*
206  *
207  * OPTIONS FLAGS
208  *
209  */
210
211 /* Enable core dump on failure. */
212 static int dump_on_failure = 0;
213 /* Default is to remove temp dirs and log data for successful tests. */
214 static int keep_temp_files = 0;
215 /* Default is to run the specified tests once and report errors. */
216 static int until_failure = 0;
217 /* Default is to just report pass/fail for each test. */
218 static int verbosity = 0;
219 #define VERBOSITY_SUMMARY_ONLY -1 /* -q */
220 #define VERBOSITY_PASSFAIL 0   /* Default */
221 #define VERBOSITY_LIGHT_REPORT 1 /* -v */
222 #define VERBOSITY_FULL 2 /* -vv */
223 /* A few places generate even more output for verbosity > VERBOSITY_FULL,
224  * mostly for debugging the test harness itself. */
225 /* Cumulative count of assertion failures. */
226 static int failures = 0;
227 /* Cumulative count of reported skips. */
228 static int skips = 0;
229 /* Cumulative count of assertions checked. */
230 static int assertions = 0;
231
232 /* Directory where uuencoded reference files can be found. */
233 static const char *refdir;
234
235 /*
236  * Report log information selectively to console and/or disk log.
237  */
238 static int log_console = 0;
239 static FILE *logfile;
240 static void
241 vlogprintf(const char *fmt, va_list ap)
242 {
243 #ifdef va_copy
244         va_list lfap;
245         va_copy(lfap, ap);
246 #endif
247         if (log_console)
248                 vfprintf(stdout, fmt, ap);
249         if (logfile != NULL)
250 #ifdef va_copy
251                 vfprintf(logfile, fmt, lfap);
252         va_end(lfap);
253 #else
254                 vfprintf(logfile, fmt, ap);
255 #endif
256 }
257
258 static void
259 logprintf(const char *fmt, ...)
260 {
261         va_list ap;
262         va_start(ap, fmt);
263         vlogprintf(fmt, ap);
264         va_end(ap);
265 }
266
267 /* Set up a message to display only if next assertion fails. */
268 static char msgbuff[4096];
269 static const char *msg, *nextmsg;
270 void
271 failure(const char *fmt, ...)
272 {
273         va_list ap;
274         if (fmt == NULL) {
275                 nextmsg = NULL;
276         } else {
277                 va_start(ap, fmt);
278                 vsprintf(msgbuff, fmt, ap);
279                 va_end(ap);
280                 nextmsg = msgbuff;
281         }
282 }
283
284 /*
285  * Copy arguments into file-local variables.
286  * This was added to permit vararg assert() functions without needing
287  * variadic wrapper macros.  Turns out that the vararg capability is almost
288  * never used, so almost all of the vararg assertions can be simplified
289  * by removing the vararg capability and reworking the wrapper macro to
290  * pass __FILE__, __LINE__ directly into the function instead of using
291  * this hook.  I suspect this machinery is used so rarely that we
292  * would be better off just removing it entirely.  That would simplify
293  * the code here noticeably.
294  */
295 static const char *skipping_filename;
296 static int skipping_line;
297 void skipping_setup(const char *filename, int line)
298 {
299         skipping_filename = filename;
300         skipping_line = line;
301 }
302
303 /* Called at the beginning of each assert() function. */
304 static void
305 assertion_count(const char *file, int line)
306 {
307         (void)file; /* UNUSED */
308         (void)line; /* UNUSED */
309         ++assertions;
310         /* Proper handling of "failure()" message. */
311         msg = nextmsg;
312         nextmsg = NULL;
313         /* Uncomment to print file:line after every assertion.
314          * Verbose, but occasionally useful in tracking down crashes. */
315         /* printf("Checked %s:%d\n", file, line); */
316 }
317
318 /*
319  * For each test source file, we remember how many times each
320  * assertion was reported.  Cleared before each new test,
321  * used by test_summarize().
322  */
323 static struct line {
324         int count;
325         int skip;
326 }  failed_lines[10000];
327 const char *failed_filename;
328
329 /* Count this failure, setup up log destination and handle initial report. */
330 static void
331 failure_start(const char *filename, int line, const char *fmt, ...)
332 {
333         va_list ap;
334
335         /* Record another failure for this line. */
336         ++failures;
337         failed_filename = filename;
338         failed_lines[line].count++;
339
340         /* Determine whether to log header to console. */
341         switch (verbosity) {
342         case VERBOSITY_LIGHT_REPORT:
343                 log_console = (failed_lines[line].count < 2);
344                 break;
345         default:
346                 log_console = (verbosity >= VERBOSITY_FULL);
347         }
348
349         /* Log file:line header for this failure */
350         va_start(ap, fmt);
351 #if _MSC_VER
352         logprintf("%s(%d): ", filename, line);
353 #else
354         logprintf("%s:%d: ", filename, line);
355 #endif
356         vlogprintf(fmt, ap);
357         va_end(ap);
358         logprintf("\n");
359
360         if (msg != NULL && msg[0] != '\0') {
361                 logprintf("   Description: %s\n", msg);
362                 msg = NULL;
363         }
364
365         /* Determine whether to log details to console. */
366         if (verbosity == VERBOSITY_LIGHT_REPORT)
367                 log_console = 0;
368 }
369
370 /* Complete reporting of failed tests. */
371 /*
372  * The 'extra' hook here is used by libarchive to include libarchive
373  * error messages with assertion failures.  It could also be used
374  * to add strerror() output, for example.  Just define the EXTRA_DUMP()
375  * macro appropriately.
376  */
377 static void
378 failure_finish(void *extra)
379 {
380         (void)extra; /* UNUSED (maybe) */
381 #ifdef EXTRA_DUMP
382         if (extra != NULL) {
383                 logprintf("    errno: %d\n", EXTRA_ERRNO(extra));
384                 logprintf("   detail: %s\n", EXTRA_DUMP(extra));
385         }
386 #endif
387
388         if (dump_on_failure) {
389                 fprintf(stderr,
390                     " *** forcing core dump so failure can be debugged ***\n");
391                 abort();
392         }
393 }
394
395 /* Inform user that we're skipping some checks. */
396 void
397 test_skipping(const char *fmt, ...)
398 {
399         char buff[1024];
400         va_list ap;
401
402         va_start(ap, fmt);
403         vsprintf(buff, fmt, ap);
404         va_end(ap);
405         /* Use failure() message if set. */
406         msg = nextmsg;
407         nextmsg = NULL;
408         /* failure_start() isn't quite right, but is awfully convenient. */
409         failure_start(skipping_filename, skipping_line, "SKIPPING: %s", buff);
410         --failures; /* Undo failures++ in failure_start() */
411         /* Don't failure_finish() here. */
412         /* Mark as skip, so doesn't count as failed test. */
413         failed_lines[skipping_line].skip = 1;
414         ++skips;
415 }
416
417 /*
418  *
419  * ASSERTIONS
420  *
421  */
422
423 /* Generic assert() just displays the failed condition. */
424 int
425 assertion_assert(const char *file, int line, int value,
426     const char *condition, void *extra)
427 {
428         assertion_count(file, line);
429         if (!value) {
430                 failure_start(file, line, "Assertion failed: %s", condition);
431                 failure_finish(extra);
432         }
433         return (value);
434 }
435
436 /* chdir() and report any errors */
437 int
438 assertion_chdir(const char *file, int line, const char *pathname)
439 {
440         assertion_count(file, line);
441         if (chdir(pathname) == 0)
442                 return (1);
443         failure_start(file, line, "chdir(\"%s\")", pathname);
444         failure_finish(NULL);
445         return (0);
446
447 }
448
449 /* Verify two integers are equal. */
450 int
451 assertion_equal_int(const char *file, int line,
452     long long v1, const char *e1, long long v2, const char *e2, void *extra)
453 {
454         assertion_count(file, line);
455         if (v1 == v2)
456                 return (1);
457         failure_start(file, line, "%s != %s", e1, e2);
458         logprintf("      %s=%lld (0x%llx, 0%llo)\n", e1, v1, v1, v1);
459         logprintf("      %s=%lld (0x%llx, 0%llo)\n", e2, v2, v2, v2);
460         failure_finish(extra);
461         return (0);
462 }
463
464 /*
465  * Utility to convert a single UTF-8 sequence.
466  */
467 static int
468 _utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
469 {
470         static const char utf8_count[256] = {
471                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
472                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
473                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
474                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
475                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
476                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
477                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
478                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
479                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
480                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
481                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
482                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
483                  0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
484                  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
485                  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
486                  4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
487         };
488         int ch;
489         int cnt;
490         uint32_t wc;
491
492         *pwc = 0;
493
494         /* Sanity check. */
495         if (n == 0)
496                 return (0);
497         /*
498          * Decode 1-4 bytes depending on the value of the first byte.
499          */
500         ch = (unsigned char)*s;
501         if (ch == 0)
502                 return (0); /* Standard:  return 0 for end-of-string. */
503         cnt = utf8_count[ch];
504
505         /* Invalide sequence or there are not plenty bytes. */
506         if (n < (size_t)cnt)
507                 return (-1);
508
509         /* Make a Unicode code point from a single UTF-8 sequence. */
510         switch (cnt) {
511         case 1: /* 1 byte sequence. */
512                 *pwc = ch & 0x7f;
513                 return (cnt);
514         case 2: /* 2 bytes sequence. */
515                 if ((s[1] & 0xc0) != 0x80) return (-1);
516                 *pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
517                 return (cnt);
518         case 3: /* 3 bytes sequence. */
519                 if ((s[1] & 0xc0) != 0x80) return (-1);
520                 if ((s[2] & 0xc0) != 0x80) return (-1);
521                 wc = ((ch & 0x0f) << 12)
522                     | ((s[1] & 0x3f) << 6)
523                     | (s[2] & 0x3f);
524                 if (wc < 0x800)
525                         return (-1);/* Overlong sequence. */
526                 break;
527         case 4: /* 4 bytes sequence. */
528                 if (n < 4)
529                         return (-1);
530                 if ((s[1] & 0xc0) != 0x80) return (-1);
531                 if ((s[2] & 0xc0) != 0x80) return (-1);
532                 if ((s[3] & 0xc0) != 0x80) return (-1);
533                 wc = ((ch & 0x07) << 18)
534                     | ((s[1] & 0x3f) << 12)
535                     | ((s[2] & 0x3f) << 6)
536                     | (s[3] & 0x3f);
537                 if (wc < 0x10000)
538                         return (-1);/* Overlong sequence. */
539                 break;
540         default:
541                 return (-1);
542         }
543
544         /* The code point larger than 0x10FFFF is not leagal
545          * Unicode values. */
546         if (wc > 0x10FFFF)
547                 return (-1);
548         /* Correctly gets a Unicode, returns used bytes. */
549         *pwc = wc;
550         return (cnt);
551 }
552
553 static void strdump(const char *e, const char *p, int ewidth, int utf8)
554 {
555         const char *q = p;
556
557         logprintf("      %*s = ", ewidth, e);
558         if (p == NULL) {
559                 logprintf("NULL\n");
560                 return;
561         }
562         logprintf("\"");
563         while (*p != '\0') {
564                 unsigned int c = 0xff & *p++;
565                 switch (c) {
566                 case '\a': printf("\a"); break;
567                 case '\b': printf("\b"); break;
568                 case '\n': printf("\n"); break;
569                 case '\r': printf("\r"); break;
570                 default:
571                         if (c >= 32 && c < 127)
572                                 logprintf("%c", c);
573                         else
574                                 logprintf("\\x%02X", c);
575                 }
576         }
577         logprintf("\"");
578         logprintf(" (length %d)", q == NULL ? -1 : (int)strlen(q));
579
580         /*
581          * If the current string is UTF-8, dump its code points.
582          */
583         if (utf8) {
584                 size_t len;
585                 uint32_t uc;
586                 int n;
587                 int cnt = 0;
588
589                 p = q;
590                 len = strlen(p);
591                 logprintf(" [");
592                 while ((n = _utf8_to_unicode(&uc, p, len)) > 0) {
593                         if (p != q)
594                                 logprintf(" ");
595                         logprintf("%04X", uc);
596                         p += n;
597                         len -= n;
598                         cnt++;
599                 }
600                 logprintf("]");
601                 logprintf(" (count %d", cnt);
602                 if (n < 0) {
603                         logprintf(",unknown %d bytes", len);
604                 }
605                 logprintf(")");
606
607         }
608         logprintf("\n");
609 }
610
611 /* Verify two strings are equal, dump them if not. */
612 int
613 assertion_equal_string(const char *file, int line,
614     const char *v1, const char *e1,
615     const char *v2, const char *e2,
616     void *extra, int utf8)
617 {
618         int l1, l2;
619
620         assertion_count(file, line);
621         if (v1 == v2 || (v1 != NULL && v2 != NULL && strcmp(v1, v2) == 0))
622                 return (1);
623         failure_start(file, line, "%s != %s", e1, e2);
624         l1 = (int)strlen(e1);
625         l2 = (int)strlen(e2);
626         if (l1 < l2)
627                 l1 = l2;
628         strdump(e1, v1, l1, utf8);
629         strdump(e2, v2, l1, utf8);
630         failure_finish(extra);
631         return (0);
632 }
633
634 static void
635 wcsdump(const char *e, const wchar_t *w)
636 {
637         logprintf("      %s = ", e);
638         if (w == NULL) {
639                 logprintf("(null)");
640                 return;
641         }
642         logprintf("\"");
643         while (*w != L'\0') {
644                 unsigned int c = *w++;
645                 if (c >= 32 && c < 127)
646                         logprintf("%c", c);
647                 else if (c < 256)
648                         logprintf("\\x%02X", c);
649                 else if (c < 0x10000)
650                         logprintf("\\u%04X", c);
651                 else
652                         logprintf("\\U%08X", c);
653         }
654         logprintf("\"\n");
655 }
656
657 #ifndef HAVE_WCSCMP
658 static int
659 wcscmp(const wchar_t *s1, const wchar_t *s2)
660 {
661
662         while (*s1 == *s2++) {
663                 if (*s1++ == L'\0')
664                         return 0;
665         }
666         if (*s1 > *--s2)
667                 return 1;
668         else
669                 return -1;
670 }
671 #endif
672
673 /* Verify that two wide strings are equal, dump them if not. */
674 int
675 assertion_equal_wstring(const char *file, int line,
676     const wchar_t *v1, const char *e1,
677     const wchar_t *v2, const char *e2,
678     void *extra)
679 {
680         assertion_count(file, line);
681         if (v1 == v2)
682                 return (1);
683         if (v1 != NULL && v2 != NULL && wcscmp(v1, v2) == 0)
684                 return (1);
685         failure_start(file, line, "%s != %s", e1, e2);
686         wcsdump(e1, v1);
687         wcsdump(e2, v2);
688         failure_finish(extra);
689         return (0);
690 }
691
692 /*
693  * Pretty standard hexdump routine.  As a bonus, if ref != NULL, then
694  * any bytes in p that differ from ref will be highlighted with '_'
695  * before and after the hex value.
696  */
697 static void
698 hexdump(const char *p, const char *ref, size_t l, size_t offset)
699 {
700         size_t i, j;
701         char sep;
702
703         if (p == NULL) {
704                 logprintf("(null)\n");
705                 return;
706         }
707         for(i=0; i < l; i+=16) {
708                 logprintf("%04x", (unsigned)(i + offset));
709                 sep = ' ';
710                 for (j = 0; j < 16 && i + j < l; j++) {
711                         if (ref != NULL && p[i + j] != ref[i + j])
712                                 sep = '_';
713                         logprintf("%c%02x", sep, 0xff & (int)p[i+j]);
714                         if (ref != NULL && p[i + j] == ref[i + j])
715                                 sep = ' ';
716                 }
717                 for (; j < 16; j++) {
718                         logprintf("%c  ", sep);
719                         sep = ' ';
720                 }
721                 logprintf("%c", sep);
722                 for (j=0; j < 16 && i + j < l; j++) {
723                         int c = p[i + j];
724                         if (c >= ' ' && c <= 126)
725                                 logprintf("%c", c);
726                         else
727                                 logprintf(".");
728                 }
729                 logprintf("\n");
730         }
731 }
732
733 /* Verify that two blocks of memory are the same, display the first
734  * block of differences if they're not. */
735 int
736 assertion_equal_mem(const char *file, int line,
737     const void *_v1, const char *e1,
738     const void *_v2, const char *e2,
739     size_t l, const char *ld, void *extra)
740 {
741         const char *v1 = (const char *)_v1;
742         const char *v2 = (const char *)_v2;
743         size_t offset;
744
745         assertion_count(file, line);
746         if (v1 == v2 || (v1 != NULL && v2 != NULL && memcmp(v1, v2, l) == 0))
747                 return (1);
748         if (v1 == NULL || v2 == NULL)
749                 return (0);
750
751         failure_start(file, line, "%s != %s", e1, e2);
752         logprintf("      size %s = %d\n", ld, (int)l);
753         /* Dump 48 bytes (3 lines) so that the first difference is
754          * in the second line. */
755         offset = 0;
756         while (l > 64 && memcmp(v1, v2, 32) == 0) {
757                 /* Two lines agree, so step forward one line. */
758                 v1 += 16;
759                 v2 += 16;
760                 l -= 16;
761                 offset += 16;
762         }
763         logprintf("      Dump of %s\n", e1);
764         hexdump(v1, v2, l < 128 ? l : 128, offset);
765         logprintf("      Dump of %s\n", e2);
766         hexdump(v2, v1, l < 128 ? l : 128, offset);
767         logprintf("\n");
768         failure_finish(extra);
769         return (0);
770 }
771
772 /* Verify that the named file exists and is empty. */
773 int
774 assertion_empty_file(const char *filename, int line, const char *f1)
775 {
776         char buff[1024];
777         struct stat st;
778         ssize_t s;
779         FILE *f;
780
781         assertion_count(filename, line);
782
783         if (stat(f1, &st) != 0) {
784                 failure_start(filename, line, "Stat failed: %s", f1);
785                 failure_finish(NULL);
786                 return (0);
787         }
788         if (st.st_size == 0)
789                 return (1);
790
791         failure_start(filename, line, "File should be empty: %s", f1);
792         logprintf("    File size: %d\n", (int)st.st_size);
793         logprintf("    Contents:\n");
794         f = fopen(f1, "rb");
795         if (f == NULL) {
796                 logprintf("    Unable to open %s\n", f1);
797         } else {
798                 s = ((off_t)sizeof(buff) < st.st_size) ?
799                     (ssize_t)sizeof(buff) : (ssize_t)st.st_size;
800                 s = fread(buff, 1, s, f);
801                 hexdump(buff, NULL, s, 0);
802                 fclose(f);
803         }
804         failure_finish(NULL);
805         return (0);
806 }
807
808 /* Verify that the named file exists and is not empty. */
809 int
810 assertion_non_empty_file(const char *filename, int line, const char *f1)
811 {
812         struct stat st;
813
814         assertion_count(filename, line);
815
816         if (stat(f1, &st) != 0) {
817                 failure_start(filename, line, "Stat failed: %s", f1);
818                 failure_finish(NULL);
819                 return (0);
820         }
821         if (st.st_size == 0) {
822                 failure_start(filename, line, "File empty: %s", f1);
823                 failure_finish(NULL);
824                 return (0);
825         }
826         return (1);
827 }
828
829 /* Verify that two files have the same contents. */
830 /* TODO: hexdump the first bytes that actually differ. */
831 int
832 assertion_equal_file(const char *filename, int line, const char *fn1, const char *fn2)
833 {
834         char buff1[1024];
835         char buff2[1024];
836         FILE *f1, *f2;
837         int n1, n2;
838
839         assertion_count(filename, line);
840
841         f1 = fopen(fn1, "rb");
842         f2 = fopen(fn2, "rb");
843         if (f1 == NULL || f2 == NULL) {
844                 if (f1) fclose(f1);
845                 if (f2) fclose(f2);
846                 return (0);
847         }
848         for (;;) {
849                 n1 = (int)fread(buff1, 1, sizeof(buff1), f1);
850                 n2 = (int)fread(buff2, 1, sizeof(buff2), f2);
851                 if (n1 != n2)
852                         break;
853                 if (n1 == 0 && n2 == 0) {
854                         fclose(f1);
855                         fclose(f2);
856                         return (1);
857                 }
858                 if (memcmp(buff1, buff2, n1) != 0)
859                         break;
860         }
861         fclose(f1);
862         fclose(f2);
863         failure_start(filename, line, "Files not identical");
864         logprintf("  file1=\"%s\"\n", fn1);
865         logprintf("  file2=\"%s\"\n", fn2);
866         failure_finish(NULL);
867         return (0);
868 }
869
870 /* Verify that the named file does exist. */
871 int
872 assertion_file_exists(const char *filename, int line, const char *f)
873 {
874         assertion_count(filename, line);
875
876 #if defined(_WIN32) && !defined(__CYGWIN__)
877         if (!_access(f, 0))
878                 return (1);
879 #else
880         if (!access(f, F_OK))
881                 return (1);
882 #endif
883         failure_start(filename, line, "File should exist: %s", f);
884         failure_finish(NULL);
885         return (0);
886 }
887
888 /* Verify that the named file doesn't exist. */
889 int
890 assertion_file_not_exists(const char *filename, int line, const char *f)
891 {
892         assertion_count(filename, line);
893
894 #if defined(_WIN32) && !defined(__CYGWIN__)
895         if (_access(f, 0))
896                 return (1);
897 #else
898         if (access(f, F_OK))
899                 return (1);
900 #endif
901         failure_start(filename, line, "File should not exist: %s", f);
902         failure_finish(NULL);
903         return (0);
904 }
905
906 /* Compare the contents of a file to a block of memory. */
907 int
908 assertion_file_contents(const char *filename, int line, const void *buff, int s, const char *fn)
909 {
910         char *contents;
911         FILE *f;
912         int n;
913
914         assertion_count(filename, line);
915
916         f = fopen(fn, "rb");
917         if (f == NULL) {
918                 failure_start(filename, line,
919                     "File should exist: %s", fn);
920                 failure_finish(NULL);
921                 return (0);
922         }
923         contents = malloc(s * 2);
924         n = (int)fread(contents, 1, s * 2, f);
925         fclose(f);
926         if (n == s && memcmp(buff, contents, s) == 0) {
927                 free(contents);
928                 return (1);
929         }
930         failure_start(filename, line, "File contents don't match");
931         logprintf("  file=\"%s\"\n", fn);
932         if (n > 0)
933                 hexdump(contents, buff, n > 512 ? 512 : n, 0);
934         else {
935                 logprintf("  File empty, contents should be:\n");
936                 hexdump(buff, NULL, s > 512 ? 512 : s, 0);
937         }
938         failure_finish(NULL);
939         free(contents);
940         return (0);
941 }
942
943 /* Check the contents of a text file, being tolerant of line endings. */
944 int
945 assertion_text_file_contents(const char *filename, int line, const char *buff, const char *fn)
946 {
947         char *contents;
948         const char *btxt, *ftxt;
949         FILE *f;
950         int n, s;
951
952         assertion_count(filename, line);
953         f = fopen(fn, "r");
954         if (f == NULL) {
955                 failure_start(filename, line,
956                     "File doesn't exist: %s", fn);
957                 failure_finish(NULL);
958                 return (0);
959         }
960         s = (int)strlen(buff);
961         contents = malloc(s * 2 + 128);
962         n = (int)fread(contents, 1, s * 2 + 128 - 1, f);
963         if (n >= 0)
964                 contents[n] = '\0';
965         fclose(f);
966         /* Compare texts. */
967         btxt = buff;
968         ftxt = (const char *)contents;
969         while (*btxt != '\0' && *ftxt != '\0') {
970                 if (*btxt == *ftxt) {
971                         ++btxt;
972                         ++ftxt;
973                         continue;
974                 }
975                 if (btxt[0] == '\n' && ftxt[0] == '\r' && ftxt[1] == '\n') {
976                         /* Pass over different new line characters. */
977                         ++btxt;
978                         ftxt += 2;
979                         continue;
980                 }
981                 break;
982         }
983         if (*btxt == '\0' && *ftxt == '\0') {
984                 free(contents);
985                 return (1);
986         }
987         failure_start(filename, line, "Contents don't match");
988         logprintf("  file=\"%s\"\n", fn);
989         if (n > 0) {
990                 hexdump(contents, buff, n, 0);
991                 logprintf("  expected\n", fn);
992                 hexdump(buff, contents, s, 0);
993         } else {
994                 logprintf("  File empty, contents should be:\n");
995                 hexdump(buff, NULL, s, 0);
996         }
997         failure_finish(NULL);
998         free(contents);
999         return (0);
1000 }
1001
1002 /* Verify that a text file contains the specified lines, regardless of order */
1003 /* This could be more efficient if we sorted both sets of lines, etc, but
1004  * since this is used only for testing and only ever deals with a dozen or so
1005  * lines at a time, this relatively crude approach is just fine. */
1006 int
1007 assertion_file_contains_lines_any_order(const char *file, int line,
1008     const char *pathname, const char *lines[])
1009 {
1010         char *buff;
1011         size_t buff_size;
1012         size_t expected_count, actual_count, i, j;
1013         char **expected = NULL;
1014         char *p, **actual = NULL;
1015         char c;
1016         int expected_failure = 0, actual_failure = 0;
1017
1018         assertion_count(file, line);
1019
1020         buff = slurpfile(&buff_size, "%s", pathname);
1021         if (buff == NULL) {
1022                 failure_start(pathname, line, "Can't read file: %s", pathname);
1023                 failure_finish(NULL);
1024                 return (0);
1025         }
1026
1027         /* Make a copy of the provided lines and count up the expected
1028          * file size. */
1029         for (i = 0; lines[i] != NULL; ++i) {
1030         }
1031         expected_count = i;
1032         if (expected_count) {
1033                 expected = malloc(sizeof(char *) * expected_count);
1034                 if (expected == NULL) {
1035                         failure_start(pathname, line, "Can't allocate memory");
1036                         failure_finish(NULL);
1037                         return (0);
1038                 }
1039                 for (i = 0; lines[i] != NULL; ++i) {
1040                         expected[i] = strdup(lines[i]);
1041                 }
1042         }
1043
1044         /* Break the file into lines */
1045         actual_count = 0;
1046         for (c = '\0', p = buff; p < buff + buff_size; ++p) {
1047                 if (*p == '\x0d' || *p == '\x0a')
1048                         *p = '\0';
1049                 if (c == '\0' && *p != '\0')
1050                         ++actual_count;
1051                 c = *p;
1052         }
1053         if (actual_count) {
1054                 actual = calloc(sizeof(char *), actual_count);
1055                 if (actual == NULL) {
1056                         failure_start(pathname, line, "Can't allocate memory");
1057                         failure_finish(NULL);
1058                         free(expected);
1059                         return (0);
1060                 }
1061                 for (j = 0, p = buff; p < buff + buff_size;
1062                     p += 1 + strlen(p)) {
1063                         if (*p != '\0') {
1064                                 actual[j] = p;
1065                                 ++j;
1066                         }
1067                 }
1068         }
1069
1070         /* Erase matching lines from both lists */
1071         for (i = 0; i < expected_count; ++i) {
1072                 if (expected[i] == NULL)
1073                         continue;
1074                 for (j = 0; j < actual_count; ++j) {
1075                         if (actual[j] == NULL)
1076                                 continue;
1077                         if (strcmp(expected[i], actual[j]) == 0) {
1078                                 free(expected[i]);
1079                                 expected[i] = NULL;
1080                                 actual[j] = NULL;
1081                                 break;
1082                         }
1083                 }
1084         }
1085
1086         /* If there's anything left, it's a failure */
1087         for (i = 0; i < expected_count; ++i) {
1088                 if (expected[i] != NULL)
1089                         ++expected_failure;
1090         }
1091         for (j = 0; j < actual_count; ++j) {
1092                 if (actual[j] != NULL)
1093                         ++actual_failure;
1094         }
1095         if (expected_failure == 0 && actual_failure == 0) {
1096                 free(buff);
1097                 free(expected);
1098                 free(actual);
1099                 return (1);
1100         }
1101         failure_start(file, line, "File doesn't match: %s", pathname);
1102         for (i = 0; i < expected_count; ++i) {
1103                 if (expected[i] != NULL) {
1104                         logprintf("  Expected but not present: %s\n", expected[i]);
1105                         free(expected[i]);
1106                 }
1107         }
1108         for (j = 0; j < actual_count; ++j) {
1109                 if (actual[j] != NULL)
1110                         logprintf("  Present but not expected: %s\n", actual[j]);
1111         }
1112         failure_finish(NULL);
1113         free(buff);
1114         free(expected);
1115         free(actual);
1116         return (0);
1117 }
1118
1119 /* Test that two paths point to the same file. */
1120 /* As a side-effect, asserts that both files exist. */
1121 static int
1122 is_hardlink(const char *file, int line,
1123     const char *path1, const char *path2)
1124 {
1125 #if defined(_WIN32) && !defined(__CYGWIN__)
1126         BY_HANDLE_FILE_INFORMATION bhfi1, bhfi2;
1127         int r;
1128
1129         assertion_count(file, line);
1130         r = my_GetFileInformationByName(path1, &bhfi1);
1131         if (r == 0) {
1132                 failure_start(file, line, "File %s can't be inspected?", path1);
1133                 failure_finish(NULL);
1134                 return (0);
1135         }
1136         r = my_GetFileInformationByName(path2, &bhfi2);
1137         if (r == 0) {
1138                 failure_start(file, line, "File %s can't be inspected?", path2);
1139                 failure_finish(NULL);
1140                 return (0);
1141         }
1142         return (bhfi1.dwVolumeSerialNumber == bhfi2.dwVolumeSerialNumber
1143                 && bhfi1.nFileIndexHigh == bhfi2.nFileIndexHigh
1144                 && bhfi1.nFileIndexLow == bhfi2.nFileIndexLow);
1145 #else
1146         struct stat st1, st2;
1147         int r;
1148
1149         assertion_count(file, line);
1150         r = lstat(path1, &st1);
1151         if (r != 0) {
1152                 failure_start(file, line, "File should exist: %s", path1);
1153                 failure_finish(NULL);
1154                 return (0);
1155         }
1156         r = lstat(path2, &st2);
1157         if (r != 0) {
1158                 failure_start(file, line, "File should exist: %s", path2);
1159                 failure_finish(NULL);
1160                 return (0);
1161         }
1162         return (st1.st_ino == st2.st_ino && st1.st_dev == st2.st_dev);
1163 #endif
1164 }
1165
1166 int
1167 assertion_is_hardlink(const char *file, int line,
1168     const char *path1, const char *path2)
1169 {
1170         if (is_hardlink(file, line, path1, path2))
1171                 return (1);
1172         failure_start(file, line,
1173             "Files %s and %s are not hardlinked", path1, path2);
1174         failure_finish(NULL);
1175         return (0);
1176 }
1177
1178 int
1179 assertion_is_not_hardlink(const char *file, int line,
1180     const char *path1, const char *path2)
1181 {
1182         if (!is_hardlink(file, line, path1, path2))
1183                 return (1);
1184         failure_start(file, line,
1185             "Files %s and %s should not be hardlinked", path1, path2);
1186         failure_finish(NULL);
1187         return (0);
1188 }
1189
1190 /* Verify a/b/mtime of 'pathname'. */
1191 /* If 'recent', verify that it's within last 10 seconds. */
1192 static int
1193 assertion_file_time(const char *file, int line,
1194     const char *pathname, long t, long nsec, char type, int recent)
1195 {
1196         long long filet, filet_nsec;
1197         int r;
1198
1199 #if defined(_WIN32) && !defined(__CYGWIN__)
1200 #define EPOC_TIME       (116444736000000000ULL)
1201         FILETIME fxtime, fbirthtime, fatime, fmtime;
1202         ULARGE_INTEGER wintm;
1203         HANDLE h;
1204         fxtime.dwLowDateTime = 0;
1205         fxtime.dwHighDateTime = 0;
1206
1207         assertion_count(file, line);
1208         /* Note: FILE_FLAG_BACKUP_SEMANTICS applies to open
1209          * a directory file. If not, CreateFile() will fail when
1210          * the pathname is a directory. */
1211         h = CreateFile(pathname, FILE_READ_ATTRIBUTES, 0, NULL,
1212             OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1213         if (h == INVALID_HANDLE_VALUE) {
1214                 failure_start(file, line, "Can't access %s\n", pathname);
1215                 failure_finish(NULL);
1216                 return (0);
1217         }
1218         r = GetFileTime(h, &fbirthtime, &fatime, &fmtime);
1219         switch (type) {
1220         case 'a': fxtime = fatime; break;
1221         case 'b': fxtime = fbirthtime; break;
1222         case 'm': fxtime = fmtime; break;
1223         }
1224         CloseHandle(h);
1225         if (r == 0) {
1226                 failure_start(file, line, "Can't GetFileTime %s\n", pathname);
1227                 failure_finish(NULL);
1228                 return (0);
1229         }
1230         wintm.LowPart = fxtime.dwLowDateTime;
1231         wintm.HighPart = fxtime.dwHighDateTime;
1232         filet = (wintm.QuadPart - EPOC_TIME) / 10000000;
1233         filet_nsec = ((wintm.QuadPart - EPOC_TIME) % 10000000) * 100;
1234         nsec = (nsec / 100) * 100; /* Round the request */
1235 #else
1236         struct stat st;
1237
1238         assertion_count(file, line);
1239         r = lstat(pathname, &st);
1240         if (r != 0) {
1241                 failure_start(file, line, "Can't stat %s\n", pathname);
1242                 failure_finish(NULL);
1243                 return (0);
1244         }
1245         switch (type) {
1246         case 'a': filet = st.st_atime; break;
1247         case 'm': filet = st.st_mtime; break;
1248         case 'b': filet = 0; break;
1249         default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);
1250                 exit(1);
1251         }
1252 #if defined(__FreeBSD__)
1253         switch (type) {
1254         case 'a': filet_nsec = st.st_atimespec.tv_nsec; break;
1255         case 'b': filet = st.st_birthtime;
1256                 filet_nsec = st.st_birthtimespec.tv_nsec; break;
1257         case 'm': filet_nsec = st.st_mtimespec.tv_nsec; break;
1258         default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);
1259                 exit(1);
1260         }
1261         /* FreeBSD generally only stores to microsecond res, so round. */
1262         filet_nsec = (filet_nsec / 1000) * 1000;
1263         nsec = (nsec / 1000) * 1000;
1264 #else
1265         filet_nsec = nsec = 0;  /* Generic POSIX only has whole seconds. */
1266         if (type == 'b') return (1); /* Generic POSIX doesn't have birthtime */
1267 #if defined(__HAIKU__)
1268         if (type == 'a') return (1); /* Haiku doesn't have atime. */
1269 #endif
1270 #endif
1271 #endif
1272         if (recent) {
1273                 /* Check that requested time is up-to-date. */
1274                 time_t now = time(NULL);
1275                 if (filet < now - 10 || filet > now + 1) {
1276                         failure_start(file, line,
1277                             "File %s has %ctime %lld, %lld seconds ago\n",
1278                             pathname, type, filet, now - filet);
1279                         failure_finish(NULL);
1280                         return (0);
1281                 }
1282         } else if (filet != t || filet_nsec != nsec) {
1283                 failure_start(file, line,
1284                     "File %s has %ctime %lld.%09lld, expected %lld.%09lld",
1285                     pathname, type, filet, filet_nsec, t, nsec);
1286                 failure_finish(NULL);
1287                 return (0);
1288         }
1289         return (1);
1290 }
1291
1292 /* Verify atime of 'pathname'. */
1293 int
1294 assertion_file_atime(const char *file, int line,
1295     const char *pathname, long t, long nsec)
1296 {
1297         return assertion_file_time(file, line, pathname, t, nsec, 'a', 0);
1298 }
1299
1300 /* Verify atime of 'pathname' is up-to-date. */
1301 int
1302 assertion_file_atime_recent(const char *file, int line, const char *pathname)
1303 {
1304         return assertion_file_time(file, line, pathname, 0, 0, 'a', 1);
1305 }
1306
1307 /* Verify birthtime of 'pathname'. */
1308 int
1309 assertion_file_birthtime(const char *file, int line,
1310     const char *pathname, long t, long nsec)
1311 {
1312         return assertion_file_time(file, line, pathname, t, nsec, 'b', 0);
1313 }
1314
1315 /* Verify birthtime of 'pathname' is up-to-date. */
1316 int
1317 assertion_file_birthtime_recent(const char *file, int line,
1318     const char *pathname)
1319 {
1320         return assertion_file_time(file, line, pathname, 0, 0, 'b', 1);
1321 }
1322
1323 /* Verify mtime of 'pathname'. */
1324 int
1325 assertion_file_mtime(const char *file, int line,
1326     const char *pathname, long t, long nsec)
1327 {
1328         return assertion_file_time(file, line, pathname, t, nsec, 'm', 0);
1329 }
1330
1331 /* Verify mtime of 'pathname' is up-to-date. */
1332 int
1333 assertion_file_mtime_recent(const char *file, int line, const char *pathname)
1334 {
1335         return assertion_file_time(file, line, pathname, 0, 0, 'm', 1);
1336 }
1337
1338 /* Verify number of links to 'pathname'. */
1339 int
1340 assertion_file_nlinks(const char *file, int line,
1341     const char *pathname, int nlinks)
1342 {
1343 #if defined(_WIN32) && !defined(__CYGWIN__)
1344         BY_HANDLE_FILE_INFORMATION bhfi;
1345         int r;
1346
1347         assertion_count(file, line);
1348         r = my_GetFileInformationByName(pathname, &bhfi);
1349         if (r != 0 && bhfi.nNumberOfLinks == (DWORD)nlinks)
1350                 return (1);
1351         failure_start(file, line, "File %s has %d links, expected %d",
1352             pathname, bhfi.nNumberOfLinks, nlinks);
1353         failure_finish(NULL);
1354         return (0);
1355 #else
1356         struct stat st;
1357         int r;
1358
1359         assertion_count(file, line);
1360         r = lstat(pathname, &st);
1361         if (r == 0 && (int)st.st_nlink == nlinks)
1362                         return (1);
1363         failure_start(file, line, "File %s has %d links, expected %d",
1364             pathname, st.st_nlink, nlinks);
1365         failure_finish(NULL);
1366         return (0);
1367 #endif
1368 }
1369
1370 /* Verify size of 'pathname'. */
1371 int
1372 assertion_file_size(const char *file, int line, const char *pathname, long size)
1373 {
1374         int64_t filesize;
1375         int r;
1376
1377         assertion_count(file, line);
1378 #if defined(_WIN32) && !defined(__CYGWIN__)
1379         {
1380                 BY_HANDLE_FILE_INFORMATION bhfi;
1381                 r = !my_GetFileInformationByName(pathname, &bhfi);
1382                 filesize = ((int64_t)bhfi.nFileSizeHigh << 32) + bhfi.nFileSizeLow;
1383         }
1384 #else
1385         {
1386                 struct stat st;
1387                 r = lstat(pathname, &st);
1388                 filesize = st.st_size;
1389         }
1390 #endif
1391         if (r == 0 && filesize == size)
1392                         return (1);
1393         failure_start(file, line, "File %s has size %ld, expected %ld",
1394             pathname, (long)filesize, (long)size);
1395         failure_finish(NULL);
1396         return (0);
1397 }
1398
1399 /* Verify mode of 'pathname'. */
1400 int
1401 assertion_file_mode(const char *file, int line, const char *pathname, int expected_mode)
1402 {
1403         int mode;
1404         int r;
1405
1406         assertion_count(file, line);
1407 #if defined(_WIN32) && !defined(__CYGWIN__)
1408         failure_start(file, line, "assertFileMode not yet implemented for Windows");
1409 #else
1410         {
1411                 struct stat st;
1412                 r = lstat(pathname, &st);
1413                 mode = (int)(st.st_mode & 0777);
1414         }
1415         if (r == 0 && mode == expected_mode)
1416                 return (1);
1417         failure_start(file, line, "File %s has mode %o, expected %o",
1418             pathname, mode, expected_mode);
1419 #endif
1420         failure_finish(NULL);
1421         return (0);
1422 }
1423
1424 /* Assert that 'pathname' is a dir.  If mode >= 0, verify that too. */
1425 int
1426 assertion_is_dir(const char *file, int line, const char *pathname, int mode)
1427 {
1428         struct stat st;
1429         int r;
1430
1431 #if defined(_WIN32) && !defined(__CYGWIN__)
1432         (void)mode; /* UNUSED */
1433 #endif
1434         assertion_count(file, line);
1435         r = lstat(pathname, &st);
1436         if (r != 0) {
1437                 failure_start(file, line, "Dir should exist: %s", pathname);
1438                 failure_finish(NULL);
1439                 return (0);
1440         }
1441         if (!S_ISDIR(st.st_mode)) {
1442                 failure_start(file, line, "%s is not a dir", pathname);
1443                 failure_finish(NULL);
1444                 return (0);
1445         }
1446 #if !defined(_WIN32) || defined(__CYGWIN__)
1447         /* Windows doesn't handle permissions the same way as POSIX,
1448          * so just ignore the mode tests. */
1449         /* TODO: Can we do better here? */
1450         if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {
1451                 failure_start(file, line, "Dir %s has wrong mode", pathname);
1452                 logprintf("  Expected: 0%3o\n", mode);
1453                 logprintf("  Found: 0%3o\n", st.st_mode & 07777);
1454                 failure_finish(NULL);
1455                 return (0);
1456         }
1457 #endif
1458         return (1);
1459 }
1460
1461 /* Verify that 'pathname' is a regular file.  If 'mode' is >= 0,
1462  * verify that too. */
1463 int
1464 assertion_is_reg(const char *file, int line, const char *pathname, int mode)
1465 {
1466         struct stat st;
1467         int r;
1468
1469 #if defined(_WIN32) && !defined(__CYGWIN__)
1470         (void)mode; /* UNUSED */
1471 #endif
1472         assertion_count(file, line);
1473         r = lstat(pathname, &st);
1474         if (r != 0 || !S_ISREG(st.st_mode)) {
1475                 failure_start(file, line, "File should exist: %s", pathname);
1476                 failure_finish(NULL);
1477                 return (0);
1478         }
1479 #if !defined(_WIN32) || defined(__CYGWIN__)
1480         /* Windows doesn't handle permissions the same way as POSIX,
1481          * so just ignore the mode tests. */
1482         /* TODO: Can we do better here? */
1483         if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {
1484                 failure_start(file, line, "File %s has wrong mode", pathname);
1485                 logprintf("  Expected: 0%3o\n", mode);
1486                 logprintf("  Found: 0%3o\n", st.st_mode & 07777);
1487                 failure_finish(NULL);
1488                 return (0);
1489         }
1490 #endif
1491         return (1);
1492 }
1493
1494 /* Check whether 'pathname' is a symbolic link.  If 'contents' is
1495  * non-NULL, verify that the symlink has those contents. */
1496 static int
1497 is_symlink(const char *file, int line,
1498     const char *pathname, const char *contents)
1499 {
1500 #if defined(_WIN32) && !defined(__CYGWIN__)
1501         (void)pathname; /* UNUSED */
1502         (void)contents; /* UNUSED */
1503         assertion_count(file, line);
1504         /* Windows sort-of has real symlinks, but they're only usable
1505          * by privileged users and are crippled even then, so there's
1506          * really not much point in bothering with this. */
1507         return (0);
1508 #else
1509         char buff[300];
1510         struct stat st;
1511         ssize_t linklen;
1512         int r;
1513
1514         assertion_count(file, line);
1515         r = lstat(pathname, &st);
1516         if (r != 0) {
1517                 failure_start(file, line,
1518                     "Symlink should exist: %s", pathname);
1519                 failure_finish(NULL);
1520                 return (0);
1521         }
1522         if (!S_ISLNK(st.st_mode))
1523                 return (0);
1524         if (contents == NULL)
1525                 return (1);
1526         linklen = readlink(pathname, buff, sizeof(buff));
1527         if (linklen < 0) {
1528                 failure_start(file, line, "Can't read symlink %s", pathname);
1529                 failure_finish(NULL);
1530                 return (0);
1531         }
1532         buff[linklen] = '\0';
1533         if (strcmp(buff, contents) != 0)
1534                 return (0);
1535         return (1);
1536 #endif
1537 }
1538
1539 /* Assert that path is a symlink that (optionally) contains contents. */
1540 int
1541 assertion_is_symlink(const char *file, int line,
1542     const char *path, const char *contents)
1543 {
1544         if (is_symlink(file, line, path, contents))
1545                 return (1);
1546         if (contents)
1547                 failure_start(file, line, "File %s is not a symlink to %s",
1548                     path, contents);
1549         else
1550                 failure_start(file, line, "File %s is not a symlink", path);
1551         failure_finish(NULL);
1552         return (0);
1553 }
1554
1555
1556 /* Create a directory and report any errors. */
1557 int
1558 assertion_make_dir(const char *file, int line, const char *dirname, int mode)
1559 {
1560         assertion_count(file, line);
1561 #if defined(_WIN32) && !defined(__CYGWIN__)
1562         (void)mode; /* UNUSED */
1563         if (0 == _mkdir(dirname))
1564                 return (1);
1565 #else
1566         if (0 == mkdir(dirname, mode))
1567                 return (1);
1568 #endif
1569         failure_start(file, line, "Could not create directory %s", dirname);
1570         failure_finish(NULL);
1571         return(0);
1572 }
1573
1574 /* Create a file with the specified contents and report any failures. */
1575 int
1576 assertion_make_file(const char *file, int line,
1577     const char *path, int mode, int csize, const void *contents)
1578 {
1579 #if defined(_WIN32) && !defined(__CYGWIN__)
1580         /* TODO: Rework this to set file mode as well. */
1581         FILE *f;
1582         (void)mode; /* UNUSED */
1583         assertion_count(file, line);
1584         f = fopen(path, "wb");
1585         if (f == NULL) {
1586                 failure_start(file, line, "Could not create file %s", path);
1587                 failure_finish(NULL);
1588                 return (0);
1589         }
1590         if (contents != NULL) {
1591                 size_t wsize;
1592
1593                 if (csize < 0)
1594                         wsize = strlen(contents);
1595                 else
1596                         wsize = (size_t)csize;
1597                 if (wsize != fwrite(contents, 1, wsize, f)) {
1598                         fclose(f);
1599                         failure_start(file, line,
1600                             "Could not write file %s", path);
1601                         failure_finish(NULL);
1602                         return (0);
1603                 }
1604         }
1605         fclose(f);
1606         return (1);
1607 #else
1608         int fd;
1609         assertion_count(file, line);
1610         fd = open(path, O_CREAT | O_WRONLY, mode >= 0 ? mode : 0644);
1611         if (fd < 0) {
1612                 failure_start(file, line, "Could not create %s", path);
1613                 failure_finish(NULL);
1614                 return (0);
1615         }
1616         if (contents != NULL) {
1617                 ssize_t wsize;
1618
1619                 if (csize < 0)
1620                         wsize = (ssize_t)strlen(contents);
1621                 else
1622                         wsize = (ssize_t)csize;
1623                 if (wsize != write(fd, contents, wsize)) {
1624                         close(fd);
1625                         failure_start(file, line,
1626                             "Could not write to %s", path);
1627                         failure_finish(NULL);
1628                         return (0);
1629                 }
1630         }
1631         close(fd);
1632         return (1);
1633 #endif
1634 }
1635
1636 /* Create a hardlink and report any failures. */
1637 int
1638 assertion_make_hardlink(const char *file, int line,
1639     const char *newpath, const char *linkto)
1640 {
1641         int succeeded;
1642
1643         assertion_count(file, line);
1644 #if defined(_WIN32) && !defined(__CYGWIN__)
1645         succeeded = my_CreateHardLinkA(newpath, linkto);
1646 #elif HAVE_LINK
1647         succeeded = !link(linkto, newpath);
1648 #else
1649         succeeded = 0;
1650 #endif
1651         if (succeeded)
1652                 return (1);
1653         failure_start(file, line, "Could not create hardlink");
1654         logprintf("   New link: %s\n", newpath);
1655         logprintf("   Old name: %s\n", linkto);
1656         failure_finish(NULL);
1657         return(0);
1658 }
1659
1660 /* Create a symlink and report any failures. */
1661 int
1662 assertion_make_symlink(const char *file, int line,
1663     const char *newpath, const char *linkto)
1664 {
1665 #if defined(_WIN32) && !defined(__CYGWIN__)
1666         int targetIsDir = 0;  /* TODO: Fix this */
1667         assertion_count(file, line);
1668         if (my_CreateSymbolicLinkA(newpath, linkto, targetIsDir))
1669                 return (1);
1670 #elif HAVE_SYMLINK
1671         assertion_count(file, line);
1672         if (0 == symlink(linkto, newpath))
1673                 return (1);
1674 #endif
1675         failure_start(file, line, "Could not create symlink");
1676         logprintf("   New link: %s\n", newpath);
1677         logprintf("   Old name: %s\n", linkto);
1678         failure_finish(NULL);
1679         return(0);
1680 }
1681
1682 /* Set umask, report failures. */
1683 int
1684 assertion_umask(const char *file, int line, int mask)
1685 {
1686         assertion_count(file, line);
1687         (void)file; /* UNUSED */
1688         (void)line; /* UNUSED */
1689         umask(mask);
1690         return (1);
1691 }
1692
1693 /* Set times, report failures. */
1694 int
1695 assertion_utimes(const char *file, int line,
1696     const char *pathname, long at, long at_nsec, long mt, long mt_nsec)
1697 {
1698         int r;
1699
1700 #if defined(_WIN32) && !defined(__CYGWIN__)
1701 #define WINTIME(sec, nsec) ((Int32x32To64(sec, 10000000) + EPOC_TIME)\
1702          + (((nsec)/1000)*10))
1703         HANDLE h;
1704         ULARGE_INTEGER wintm;
1705         FILETIME fatime, fmtime;
1706         FILETIME *pat, *pmt;
1707
1708         assertion_count(file, line);
1709         h = CreateFileA(pathname,GENERIC_READ | GENERIC_WRITE,
1710                     FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1711                     FILE_FLAG_BACKUP_SEMANTICS, NULL);
1712         if (h == INVALID_HANDLE_VALUE) {
1713                 failure_start(file, line, "Can't access %s\n", pathname);
1714                 failure_finish(NULL);
1715                 return (0);
1716         }
1717
1718         if (at > 0 || at_nsec > 0) {
1719                 wintm.QuadPart = WINTIME(at, at_nsec);
1720                 fatime.dwLowDateTime = wintm.LowPart;
1721                 fatime.dwHighDateTime = wintm.HighPart;
1722                 pat = &fatime;
1723         } else
1724                 pat = NULL;
1725         if (mt > 0 || mt_nsec > 0) {
1726                 wintm.QuadPart = WINTIME(mt, mt_nsec);
1727                 fmtime.dwLowDateTime = wintm.LowPart;
1728                 fmtime.dwHighDateTime = wintm.HighPart;
1729                 pmt = &fmtime;
1730         } else
1731                 pmt = NULL;
1732         if (pat != NULL || pmt != NULL)
1733                 r = SetFileTime(h, NULL, pat, pmt);
1734         else
1735                 r = 1;
1736         CloseHandle(h);
1737         if (r == 0) {
1738                 failure_start(file, line, "Can't SetFileTime %s\n", pathname);
1739                 failure_finish(NULL);
1740                 return (0);
1741         }
1742         return (1);
1743 #else /* defined(_WIN32) && !defined(__CYGWIN__) */
1744         struct stat st;
1745         struct timeval times[2];
1746
1747 #if !defined(__FreeBSD__)
1748         mt_nsec = at_nsec = 0;  /* Generic POSIX only has whole seconds. */
1749 #endif
1750         if (mt == 0 && mt_nsec == 0 && at == 0 && at_nsec == 0)
1751                 return (1);
1752
1753         r = lstat(pathname, &st);
1754         if (r < 0) {
1755                 failure_start(file, line, "Can't stat %s\n", pathname);
1756                 failure_finish(NULL);
1757                 return (0);
1758         }
1759
1760         if (mt == 0 && mt_nsec == 0) {
1761                 mt = st.st_mtime;
1762 #if defined(__FreeBSD__)
1763                 mt_nsec = st.st_mtimespec.tv_nsec;
1764                 /* FreeBSD generally only stores to microsecond res, so round. */
1765                 mt_nsec = (mt_nsec / 1000) * 1000;
1766 #endif
1767         }
1768         if (at == 0 && at_nsec == 0) {
1769                 at = st.st_atime;
1770 #if defined(__FreeBSD__)
1771                 at_nsec = st.st_atimespec.tv_nsec;
1772                 /* FreeBSD generally only stores to microsecond res, so round. */
1773                 at_nsec = (at_nsec / 1000) * 1000;
1774 #endif
1775         }
1776
1777         times[1].tv_sec = mt;
1778         times[1].tv_usec = mt_nsec / 1000;
1779
1780         times[0].tv_sec = at;
1781         times[0].tv_usec = at_nsec / 1000;
1782
1783 #ifdef HAVE_LUTIMES
1784         r = lutimes(pathname, times);
1785 #else
1786         r = utimes(pathname, times);
1787 #endif
1788         if (r < 0) {
1789                 failure_start(file, line, "Can't utimes %s\n", pathname);
1790                 failure_finish(NULL);
1791                 return (0);
1792         }
1793         return (1);
1794 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
1795 }
1796
1797 /* Set nodump, report failures. */
1798 int
1799 assertion_nodump(const char *file, int line, const char *pathname)
1800 {
1801 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
1802         int r;
1803
1804         assertion_count(file, line);
1805         r = chflags(pathname, UF_NODUMP);
1806         if (r < 0) {
1807                 failure_start(file, line, "Can't set nodump %s\n", pathname);
1808                 failure_finish(NULL);
1809                 return (0);
1810         }
1811 #elif defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)\
1812          && defined(EXT2_NODUMP_FL)
1813         int fd, r, flags;
1814
1815         assertion_count(file, line);
1816         fd = open(pathname, O_RDONLY | O_NONBLOCK);
1817         if (fd < 0) {
1818                 failure_start(file, line, "Can't open %s\n", pathname);
1819                 failure_finish(NULL);
1820                 return (0);
1821         }
1822         r = ioctl(fd, EXT2_IOC_GETFLAGS, &flags);
1823         if (r < 0) {
1824                 failure_start(file, line, "Can't get flags %s\n", pathname);
1825                 failure_finish(NULL);
1826                 return (0);
1827         }
1828         flags |= EXT2_NODUMP_FL;
1829         r = ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
1830         if (r < 0) {
1831                 failure_start(file, line, "Can't set nodump %s\n", pathname);
1832                 failure_finish(NULL);
1833                 return (0);
1834         }
1835         close(fd);
1836 #else
1837         (void)pathname; /* UNUSED */
1838         assertion_count(file, line);
1839 #endif
1840         return (1);
1841 }
1842
1843 /*
1844  *
1845  *  UTILITIES for use by tests.
1846  *
1847  */
1848
1849 /*
1850  * Check whether platform supports symlinks.  This is intended
1851  * for tests to use in deciding whether to bother testing symlink
1852  * support; if the platform doesn't support symlinks, there's no point
1853  * in checking whether the program being tested can create them.
1854  *
1855  * Note that the first time this test is called, we actually go out to
1856  * disk to create and verify a symlink.  This is necessary because
1857  * symlink support is actually a property of a particular filesystem
1858  * and can thus vary between directories on a single system.  After
1859  * the first call, this returns the cached result from memory, so it's
1860  * safe to call it as often as you wish.
1861  */
1862 int
1863 canSymlink(void)
1864 {
1865         /* Remember the test result */
1866         static int value = 0, tested = 0;
1867         if (tested)
1868                 return (value);
1869
1870         ++tested;
1871         assertion_make_file(__FILE__, __LINE__, "canSymlink.0", 0644, 1, "a");
1872         /* Note: Cygwin has its own symlink() emulation that does not
1873          * use the Win32 CreateSymbolicLink() function. */
1874 #if defined(_WIN32) && !defined(__CYGWIN__)
1875         value = my_CreateSymbolicLinkA("canSymlink.1", "canSymlink.0", 0)
1876             && is_symlink(__FILE__, __LINE__, "canSymlink.1", "canSymlink.0");
1877 #elif HAVE_SYMLINK
1878         value = (0 == symlink("canSymlink.0", "canSymlink.1"))
1879             && is_symlink(__FILE__, __LINE__, "canSymlink.1","canSymlink.0");
1880 #endif
1881         return (value);
1882 }
1883
1884 /* Platform-dependent options for hiding the output of a subcommand. */
1885 #if defined(_WIN32) && !defined(__CYGWIN__)
1886 static const char *redirectArgs = ">NUL 2>NUL"; /* Win32 cmd.exe */
1887 #else
1888 static const char *redirectArgs = ">/dev/null 2>/dev/null"; /* POSIX 'sh' */
1889 #endif
1890 /*
1891  * Can this platform run the bzip2 program?
1892  */
1893 int
1894 canBzip2(void)
1895 {
1896         static int tested = 0, value = 0;
1897         if (!tested) {
1898                 tested = 1;
1899                 if (systemf("bzip2 -d -V %s", redirectArgs) == 0)
1900                         value = 1;
1901         }
1902         return (value);
1903 }
1904
1905 /*
1906  * Can this platform run the grzip program?
1907  */
1908 int
1909 canGrzip(void)
1910 {
1911         static int tested = 0, value = 0;
1912         if (!tested) {
1913                 tested = 1;
1914                 if (systemf("grzip -V %s", redirectArgs) == 0)
1915                         value = 1;
1916         }
1917         return (value);
1918 }
1919
1920 /*
1921  * Can this platform run the gzip program?
1922  */
1923 int
1924 canGzip(void)
1925 {
1926         static int tested = 0, value = 0;
1927         if (!tested) {
1928                 tested = 1;
1929                 if (systemf("gzip -V %s", redirectArgs) == 0)
1930                         value = 1;
1931         }
1932         return (value);
1933 }
1934
1935 /*
1936  * Can this platform run the lrzip program?
1937  */
1938 int
1939 canRunCommand(const char *cmd)
1940 {
1941   static int tested = 0, value = 0;
1942   if (!tested) {
1943     tested = 1;
1944     if (systemf("%s %s", cmd, redirectArgs) == 0)
1945       value = 1;
1946   }
1947   return (value);
1948 }
1949
1950 int
1951 canLrzip(void)
1952 {
1953         static int tested = 0, value = 0;
1954         if (!tested) {
1955                 tested = 1;
1956                 if (systemf("lrzip -V %s", redirectArgs) == 0)
1957                         value = 1;
1958         }
1959         return (value);
1960 }
1961
1962 /*
1963  * Can this platform run the lzip program?
1964  */
1965 int
1966 canLzip(void)
1967 {
1968         static int tested = 0, value = 0;
1969         if (!tested) {
1970                 tested = 1;
1971                 if (systemf("lzip -V %s", redirectArgs) == 0)
1972                         value = 1;
1973         }
1974         return (value);
1975 }
1976
1977 /*
1978  * Can this platform run the lzma program?
1979  */
1980 int
1981 canLzma(void)
1982 {
1983         static int tested = 0, value = 0;
1984         if (!tested) {
1985                 tested = 1;
1986                 if (systemf("lzma -V %s", redirectArgs) == 0)
1987                         value = 1;
1988         }
1989         return (value);
1990 }
1991
1992 /*
1993  * Can this platform run the lzop program?
1994  */
1995 int
1996 canLzop(void)
1997 {
1998         static int tested = 0, value = 0;
1999         if (!tested) {
2000                 tested = 1;
2001                 if (systemf("lzop -V %s", redirectArgs) == 0)
2002                         value = 1;
2003         }
2004         return (value);
2005 }
2006
2007 /*
2008  * Can this platform run the xz program?
2009  */
2010 int
2011 canXz(void)
2012 {
2013         static int tested = 0, value = 0;
2014         if (!tested) {
2015                 tested = 1;
2016                 if (systemf("xz -V %s", redirectArgs) == 0)
2017                         value = 1;
2018         }
2019         return (value);
2020 }
2021
2022 /*
2023  * Can this filesystem handle nodump flags.
2024  */
2025 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2026
2027 int
2028 canNodump(void)
2029 {
2030         const char *path = "cannodumptest";
2031         struct stat sb;
2032
2033         assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);
2034         if (chflags(path, UF_NODUMP) < 0)
2035                 return (0);
2036         if (stat(path, &sb) < 0)
2037                 return (0);
2038         if (sb.st_flags & UF_NODUMP)
2039                 return (1);
2040         return (0);
2041 }
2042
2043 #elif defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)\
2044          && defined(EXT2_NODUMP_FL)
2045
2046 int
2047 canNodump(void)
2048 {
2049         const char *path = "cannodumptest";
2050         int fd, r, flags;
2051
2052         assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);
2053         fd = open(path, O_RDONLY | O_NONBLOCK);
2054         if (fd < 0)
2055                 return (0);
2056         r = ioctl(fd, EXT2_IOC_GETFLAGS, &flags);
2057         if (r < 0)
2058                 return (0);
2059         flags |= EXT2_NODUMP_FL;
2060         r = ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
2061         if (r < 0)
2062                 return (0);
2063         close(fd);
2064         fd = open(path, O_RDONLY | O_NONBLOCK);
2065         if (fd < 0)
2066                 return (0);
2067         r = ioctl(fd, EXT2_IOC_GETFLAGS, &flags);
2068         if (r < 0)
2069                 return (0);
2070         close(fd);
2071         if (flags & EXT2_NODUMP_FL)
2072                 return (1);
2073         return (0);
2074 }
2075
2076 #else
2077
2078 int
2079 canNodump()
2080 {
2081         return (0);
2082 }
2083
2084 #endif
2085
2086 /*
2087  * Sleep as needed; useful for verifying disk timestamp changes by
2088  * ensuring that the wall-clock time has actually changed before we
2089  * go back to re-read something from disk.
2090  */
2091 void
2092 sleepUntilAfter(time_t t)
2093 {
2094         while (t >= time(NULL))
2095 #if defined(_WIN32) && !defined(__CYGWIN__)
2096                 Sleep(500);
2097 #else
2098                 sleep(1);
2099 #endif
2100 }
2101
2102 /*
2103  * Call standard system() call, but build up the command line using
2104  * sprintf() conventions.
2105  */
2106 int
2107 systemf(const char *fmt, ...)
2108 {
2109         char buff[8192];
2110         va_list ap;
2111         int r;
2112
2113         va_start(ap, fmt);
2114         vsprintf(buff, fmt, ap);
2115         if (verbosity > VERBOSITY_FULL)
2116                 logprintf("Cmd: %s\n", buff);
2117         r = system(buff);
2118         va_end(ap);
2119         return (r);
2120 }
2121
2122 /*
2123  * Slurp a file into memory for ease of comparison and testing.
2124  * Returns size of file in 'sizep' if non-NULL, null-terminates
2125  * data in memory for ease of use.
2126  */
2127 char *
2128 slurpfile(size_t * sizep, const char *fmt, ...)
2129 {
2130         char filename[8192];
2131         struct stat st;
2132         va_list ap;
2133         char *p;
2134         ssize_t bytes_read;
2135         FILE *f;
2136         int r;
2137
2138         va_start(ap, fmt);
2139         vsprintf(filename, fmt, ap);
2140         va_end(ap);
2141
2142         f = fopen(filename, "rb");
2143         if (f == NULL) {
2144                 /* Note: No error; non-existent file is okay here. */
2145                 return (NULL);
2146         }
2147         r = fstat(fileno(f), &st);
2148         if (r != 0) {
2149                 logprintf("Can't stat file %s\n", filename);
2150                 fclose(f);
2151                 return (NULL);
2152         }
2153         p = malloc((size_t)st.st_size + 1);
2154         if (p == NULL) {
2155                 logprintf("Can't allocate %ld bytes of memory to read file %s\n",
2156                     (long int)st.st_size, filename);
2157                 fclose(f);
2158                 return (NULL);
2159         }
2160         bytes_read = fread(p, 1, (size_t)st.st_size, f);
2161         if (bytes_read < st.st_size) {
2162                 logprintf("Can't read file %s\n", filename);
2163                 fclose(f);
2164                 free(p);
2165                 return (NULL);
2166         }
2167         p[st.st_size] = '\0';
2168         if (sizep != NULL)
2169                 *sizep = (size_t)st.st_size;
2170         fclose(f);
2171         return (p);
2172 }
2173
2174 /* Read a uuencoded file from the reference directory, decode, and
2175  * write the result into the current directory. */
2176 #define UUDECODE(c) (((c) - 0x20) & 0x3f)
2177 void
2178 extract_reference_file(const char *name)
2179 {
2180         char buff[1024];
2181         FILE *in, *out;
2182
2183         sprintf(buff, "%s/%s.uu", refdir, name);
2184         in = fopen(buff, "r");
2185         failure("Couldn't open reference file %s", buff);
2186         assert(in != NULL);
2187         if (in == NULL)
2188                 return;
2189         /* Read up to and including the 'begin' line. */
2190         for (;;) {
2191                 if (fgets(buff, sizeof(buff), in) == NULL) {
2192                         /* TODO: This is a failure. */
2193                         return;
2194                 }
2195                 if (memcmp(buff, "begin ", 6) == 0)
2196                         break;
2197         }
2198         /* Now, decode the rest and write it. */
2199         /* Not a lot of error checking here; the input better be right. */
2200         out = fopen(name, "wb");
2201         while (fgets(buff, sizeof(buff), in) != NULL) {
2202                 char *p = buff;
2203                 int bytes;
2204
2205                 if (memcmp(buff, "end", 3) == 0)
2206                         break;
2207
2208                 bytes = UUDECODE(*p++);
2209                 while (bytes > 0) {
2210                         int n = 0;
2211                         /* Write out 1-3 bytes from that. */
2212                         if (bytes > 0) {
2213                                 n = UUDECODE(*p++) << 18;
2214                                 n |= UUDECODE(*p++) << 12;
2215                                 fputc(n >> 16, out);
2216                                 --bytes;
2217                         }
2218                         if (bytes > 0) {
2219                                 n |= UUDECODE(*p++) << 6;
2220                                 fputc((n >> 8) & 0xFF, out);
2221                                 --bytes;
2222                         }
2223                         if (bytes > 0) {
2224                                 n |= UUDECODE(*p++);
2225                                 fputc(n & 0xFF, out);
2226                                 --bytes;
2227                         }
2228                 }
2229         }
2230         fclose(out);
2231         fclose(in);
2232 }
2233
2234 int
2235 is_LargeInode(const char *file)
2236 {
2237 #if defined(_WIN32) && !defined(__CYGWIN__)
2238         BY_HANDLE_FILE_INFORMATION bhfi;
2239         int r;
2240
2241         r = my_GetFileInformationByName(file, &bhfi);
2242         if (r != 0)
2243                 return (0);
2244         return (bhfi.nFileIndexHigh & 0x0000FFFFUL);
2245 #else
2246         struct stat st;
2247         int64_t ino;
2248
2249         if (stat(file, &st) < 0)
2250                 return (0);
2251         ino = (int64_t)st.st_ino;
2252         return (ino > 0xffffffff);
2253 #endif
2254 }
2255
2256 void
2257 extract_reference_files(const char **names)
2258 {
2259         while (names && *names)
2260                 extract_reference_file(*names++);
2261 }
2262
2263 /*
2264  *
2265  * TEST management
2266  *
2267  */
2268
2269 /*
2270  * "list.h" is simply created by "grep DEFINE_TEST test_*.c"; it has
2271  * a line like
2272  *      DEFINE_TEST(test_function)
2273  * for each test.
2274  */
2275
2276 /* Use "list.h" to declare all of the test functions. */
2277 #undef DEFINE_TEST
2278 #define DEFINE_TEST(name) void name(void);
2279 #include "list.h"
2280
2281 /* Use "list.h" to create a list of all tests (functions and names). */
2282 #undef DEFINE_TEST
2283 #define DEFINE_TEST(n) { n, #n, 0 },
2284 struct test_list_t tests[] = {
2285         #include "list.h"
2286 };
2287
2288 /*
2289  * Summarize repeated failures in the just-completed test.
2290  */
2291 static void
2292 test_summarize(int failed)
2293 {
2294         unsigned int i;
2295
2296         switch (verbosity) {
2297         case VERBOSITY_SUMMARY_ONLY:
2298                 printf(failed ? "E" : ".");
2299                 fflush(stdout);
2300                 break;
2301         case VERBOSITY_PASSFAIL:
2302                 printf(failed ? "FAIL\n" : "ok\n");
2303                 break;
2304         }
2305
2306         log_console = (verbosity == VERBOSITY_LIGHT_REPORT);
2307
2308         for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {
2309                 if (failed_lines[i].count > 1 && !failed_lines[i].skip)
2310                         logprintf("%s:%d: Summary: Failed %d times\n",
2311                             failed_filename, i, failed_lines[i].count);
2312         }
2313         /* Clear the failure history for the next file. */
2314         failed_filename = NULL;
2315         memset(failed_lines, 0, sizeof(failed_lines));
2316 }
2317
2318 /*
2319  * Actually run a single test, with appropriate setup and cleanup.
2320  */
2321 static int
2322 test_run(int i, const char *tmpdir)
2323 {
2324         char workdir[1024];
2325         char logfilename[64];
2326         int failures_before = failures;
2327         int oldumask;
2328
2329         switch (verbosity) {
2330         case VERBOSITY_SUMMARY_ONLY: /* No per-test reports at all */
2331                 break;
2332         case VERBOSITY_PASSFAIL: /* rest of line will include ok/FAIL marker */
2333                 printf("%3d: %-50s", i, tests[i].name);
2334                 fflush(stdout);
2335                 break;
2336         default: /* Title of test, details will follow */
2337                 printf("%3d: %s\n", i, tests[i].name);
2338         }
2339
2340         /* Chdir to the top-level work directory. */
2341         if (!assertChdir(tmpdir)) {
2342                 fprintf(stderr,
2343                     "ERROR: Can't chdir to top work dir %s\n", tmpdir);
2344                 exit(1);
2345         }
2346         /* Create a log file for this test. */
2347         sprintf(logfilename, "%s.log", tests[i].name);
2348         logfile = fopen(logfilename, "w");
2349         fprintf(logfile, "%s\n\n", tests[i].name);
2350         /* Chdir() to a work dir for this specific test. */
2351         snprintf(workdir, sizeof(workdir), "%s/%s", tmpdir, tests[i].name);
2352         testworkdir = workdir;
2353         if (!assertMakeDir(testworkdir, 0755)
2354             || !assertChdir(testworkdir)) {
2355                 fprintf(stderr,
2356                     "ERROR: Can't chdir to work dir %s\n", testworkdir);
2357                 exit(1);
2358         }
2359         /* Explicitly reset the locale before each test. */
2360         setlocale(LC_ALL, "C");
2361         /* Record the umask before we run the test. */
2362         umask(oldumask = umask(0));
2363         /*
2364          * Run the actual test.
2365          */
2366         (*tests[i].func)();
2367         /*
2368          * Clean up and report afterwards.
2369          */
2370         testworkdir = NULL;
2371         /* Restore umask */
2372         umask(oldumask);
2373         /* Reset locale. */
2374         setlocale(LC_ALL, "C");
2375         /* Reset directory. */
2376         if (!assertChdir(tmpdir)) {
2377                 fprintf(stderr, "ERROR: Couldn't chdir to temp dir %s\n",
2378                     tmpdir);
2379                 exit(1);
2380         }
2381         /* Report per-test summaries. */
2382         tests[i].failures = failures - failures_before;
2383         test_summarize(tests[i].failures);
2384         /* Close the per-test log file. */
2385         fclose(logfile);
2386         logfile = NULL;
2387         /* If there were no failures, we can remove the work dir and logfile. */
2388         if (tests[i].failures == 0) {
2389                 if (!keep_temp_files && assertChdir(tmpdir)) {
2390 #if defined(_WIN32) && !defined(__CYGWIN__)
2391                         /* Make sure not to leave empty directories.
2392                          * Sometimes a processing of closing files used by tests
2393                          * is not done, then rmdir will be failed and it will
2394                          * leave a empty test directory. So we should wait a few
2395                          * seconds and retry rmdir. */
2396                         int r, t;
2397                         for (t = 0; t < 10; t++) {
2398                                 if (t > 0)
2399                                         Sleep(1000);
2400                                 r = systemf("rmdir /S /Q %s", tests[i].name);
2401                                 if (r == 0)
2402                                         break;
2403                         }
2404                         systemf("del %s", logfilename);
2405 #else
2406                         systemf("rm -rf %s", tests[i].name);
2407                         systemf("rm %s", logfilename);
2408 #endif
2409                 }
2410         }
2411         /* Return appropriate status. */
2412         return (tests[i].failures);
2413 }
2414
2415 /*
2416  *
2417  *
2418  * MAIN and support routines.
2419  *
2420  *
2421  */
2422
2423 static void
2424 usage(const char *program)
2425 {
2426         static const int limit = sizeof(tests) / sizeof(tests[0]);
2427         int i;
2428
2429         printf("Usage: %s [options] <test> <test> ...\n", program);
2430         printf("Default is to run all tests.\n");
2431         printf("Otherwise, specify the numbers of the tests you wish to run.\n");
2432         printf("Options:\n");
2433         printf("  -d  Dump core after any failure, for debugging.\n");
2434         printf("  -k  Keep all temp files.\n");
2435         printf("      Default: temp files for successful tests deleted.\n");
2436 #ifdef PROGRAM
2437         printf("  -p <path>  Path to executable to be tested.\n");
2438         printf("      Default: path taken from " ENVBASE " environment variable.\n");
2439 #endif
2440         printf("  -q  Quiet.\n");
2441         printf("  -r <dir>   Path to dir containing reference files.\n");
2442         printf("      Default: Current directory.\n");
2443         printf("  -u  Keep running specifies tests until one fails.\n");
2444         printf("  -v  Verbose.\n");
2445         printf("Available tests:\n");
2446         for (i = 0; i < limit; i++)
2447                 printf("  %d: %s\n", i, tests[i].name);
2448         exit(1);
2449 }
2450
2451 static char *
2452 get_refdir(const char *d)
2453 {
2454         char tried[512] = { '\0' };
2455         char buff[128];
2456         char *pwd, *p;
2457
2458         /* If a dir was specified, try that */
2459         if (d != NULL) {
2460                 pwd = NULL;
2461                 snprintf(buff, sizeof(buff), "%s", d);
2462                 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2463                 if (p != NULL) goto success;
2464                 strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2465                 strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2466                 goto failure;
2467         }
2468
2469         /* Get the current dir. */
2470 #ifdef PATH_MAX
2471         pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */
2472 #else
2473         pwd = getcwd(NULL, 0);
2474 #endif
2475         while (pwd[strlen(pwd) - 1] == '\n')
2476                 pwd[strlen(pwd) - 1] = '\0';
2477
2478         /* Look for a known file. */
2479         snprintf(buff, sizeof(buff), "%s", pwd);
2480         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2481         if (p != NULL) goto success;
2482         strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2483         strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2484
2485         snprintf(buff, sizeof(buff), "%s/test", pwd);
2486         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2487         if (p != NULL) goto success;
2488         strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2489         strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2490
2491 #if defined(LIBRARY)
2492         snprintf(buff, sizeof(buff), "%s/%s/test", pwd, LIBRARY);
2493 #else
2494         snprintf(buff, sizeof(buff), "%s/%s/test", pwd, PROGRAM);
2495 #endif
2496         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2497         if (p != NULL) goto success;
2498         strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2499         strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2500
2501 #if defined(PROGRAM_ALIAS)
2502         snprintf(buff, sizeof(buff), "%s/%s/test", pwd, PROGRAM_ALIAS);
2503         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2504         if (p != NULL) goto success;
2505         strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2506         strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2507 #endif
2508
2509         if (memcmp(pwd, "/usr/obj", 8) == 0) {
2510                 snprintf(buff, sizeof(buff), "%s", pwd + 8);
2511                 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2512                 if (p != NULL) goto success;
2513                 strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2514                 strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2515
2516                 snprintf(buff, sizeof(buff), "%s/test", pwd + 8);
2517                 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2518                 if (p != NULL) goto success;
2519                 strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2520                 strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2521         }
2522
2523 failure:
2524         printf("Unable to locate known reference file %s\n", KNOWNREF);
2525         printf("  Checked following directories:\n%s\n", tried);
2526 #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
2527         DebugBreak();
2528 #endif
2529         exit(1);
2530
2531 success:
2532         free(p);
2533         free(pwd);
2534         return strdup(buff);
2535 }
2536
2537 int
2538 main(int argc, char **argv)
2539 {
2540         static const int limit = sizeof(tests) / sizeof(tests[0]);
2541         int test_set[sizeof(tests) / sizeof(tests[0])];
2542         int i = 0, j = 0, tests_run = 0, tests_failed = 0, option;
2543         time_t now;
2544         char *refdir_alloc = NULL;
2545         const char *progname;
2546         char **saved_argv;
2547         const char *tmp, *option_arg, *p;
2548         char tmpdir[256], *pwd, *testprogdir, *tmp2 = NULL, *vlevel = NULL;
2549         char tmpdir_timestamp[256];
2550
2551         (void)argc; /* UNUSED */
2552
2553         /* Get the current dir. */
2554 #ifdef PATH_MAX
2555         pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */
2556 #else
2557         pwd = getcwd(NULL, 0);
2558 #endif
2559         while (pwd[strlen(pwd) - 1] == '\n')
2560                 pwd[strlen(pwd) - 1] = '\0';
2561
2562 #if defined(HAVE__CrtSetReportMode)
2563         /* To stop to run the default invalid parameter handler. */
2564         _set_invalid_parameter_handler(invalid_parameter_handler);
2565         /* Disable annoying assertion message box. */
2566         _CrtSetReportMode(_CRT_ASSERT, 0);
2567 #endif
2568
2569         /*
2570          * Name of this program, used to build root of our temp directory
2571          * tree.
2572          */
2573         progname = p = argv[0];
2574         if ((testprogdir = (char *)malloc(strlen(progname) + 1)) == NULL)
2575         {
2576                 fprintf(stderr, "ERROR: Out of memory.");
2577                 exit(1);
2578         }
2579         strcpy(testprogdir, progname);
2580         while (*p != '\0') {
2581                 /* Support \ or / dir separators for Windows compat. */
2582                 if (*p == '/' || *p == '\\')
2583                 {
2584                         progname = p + 1;
2585                         i = j;
2586                 }
2587                 ++p;
2588                 j++;
2589         }
2590         testprogdir[i] = '\0';
2591 #if defined(_WIN32) && !defined(__CYGWIN__)
2592         if (testprogdir[0] != '/' && testprogdir[0] != '\\' &&
2593             !(((testprogdir[0] >= 'a' && testprogdir[0] <= 'z') ||
2594                (testprogdir[0] >= 'A' && testprogdir[0] <= 'Z')) &&
2595                 testprogdir[1] == ':' &&
2596                 (testprogdir[2] == '/' || testprogdir[2] == '\\')))
2597 #else
2598         if (testprogdir[0] != '/')
2599 #endif
2600         {
2601                 /* Fixup path for relative directories. */
2602                 if ((testprogdir = (char *)realloc(testprogdir,
2603                         strlen(pwd) + 1 + strlen(testprogdir) + 1)) == NULL)
2604                 {
2605                         fprintf(stderr, "ERROR: Out of memory.");
2606                         exit(1);
2607                 }
2608                 memmove(testprogdir + strlen(pwd) + 1, testprogdir,
2609                     strlen(testprogdir));
2610                 memcpy(testprogdir, pwd, strlen(pwd));
2611                 testprogdir[strlen(pwd)] = '/';
2612         }
2613
2614 #ifdef PROGRAM
2615         /* Get the target program from environment, if available. */
2616         testprogfile = getenv(ENVBASE);
2617 #endif
2618
2619         if (getenv("TMPDIR") != NULL)
2620                 tmp = getenv("TMPDIR");
2621         else if (getenv("TMP") != NULL)
2622                 tmp = getenv("TMP");
2623         else if (getenv("TEMP") != NULL)
2624                 tmp = getenv("TEMP");
2625         else if (getenv("TEMPDIR") != NULL)
2626                 tmp = getenv("TEMPDIR");
2627         else
2628                 tmp = "/tmp";
2629
2630         /* Allow -d to be controlled through the environment. */
2631         if (getenv(ENVBASE "_DEBUG") != NULL)
2632                 dump_on_failure = 1;
2633
2634         /* Allow -v to be controlled through the environment. */
2635         if (getenv("_VERBOSITY_LEVEL") != NULL)
2636         {
2637                 vlevel = getenv("_VERBOSITY_LEVEL");
2638                 verbosity = atoi(vlevel);
2639                 if (verbosity < VERBOSITY_SUMMARY_ONLY || verbosity > VERBOSITY_FULL)
2640                 {
2641                         /* Unsupported verbosity levels are silently ignored */
2642                         vlevel = NULL;
2643                         verbosity = VERBOSITY_PASSFAIL;
2644                 }
2645         }
2646
2647         /* Get the directory holding test files from environment. */
2648         refdir = getenv(ENVBASE "_TEST_FILES");
2649
2650         /*
2651          * Parse options, without using getopt(), which isn't available
2652          * on all platforms.
2653          */
2654         ++argv; /* Skip program name */
2655         while (*argv != NULL) {
2656                 if (**argv != '-')
2657                         break;
2658                 p = *argv++;
2659                 ++p; /* Skip '-' */
2660                 while (*p != '\0') {
2661                         option = *p++;
2662                         option_arg = NULL;
2663                         /* If 'opt' takes an argument, parse that. */
2664                         if (option == 'p' || option == 'r') {
2665                                 if (*p != '\0')
2666                                         option_arg = p;
2667                                 else if (*argv == NULL) {
2668                                         fprintf(stderr,
2669                                             "Option -%c requires argument.\n",
2670                                             option);
2671                                         usage(progname);
2672                                 } else
2673                                         option_arg = *argv++;
2674                                 p = ""; /* End of this option word. */
2675                         }
2676
2677                         /* Now, handle the option. */
2678                         switch (option) {
2679                         case 'd':
2680                                 dump_on_failure = 1;
2681                                 break;
2682                         case 'k':
2683                                 keep_temp_files = 1;
2684                                 break;
2685                         case 'p':
2686 #ifdef PROGRAM
2687                                 testprogfile = option_arg;
2688 #else
2689                                 fprintf(stderr, "-p option not permitted\n");
2690                                 usage(progname);
2691 #endif
2692                                 break;
2693                         case 'q':
2694                                 if (!vlevel)
2695                                         verbosity--;
2696                                 break;
2697                         case 'r':
2698                                 refdir = option_arg;
2699                                 break;
2700                         case 'u':
2701                                 until_failure++;
2702                                 break;
2703                         case 'v':
2704                                 if (!vlevel)
2705                                         verbosity++;
2706                                 break;
2707                         default:
2708                                 fprintf(stderr, "Unrecognized option '%c'\n",
2709                                     option);
2710                                 usage(progname);
2711                         }
2712                 }
2713         }
2714
2715         /*
2716          * Sanity-check that our options make sense.
2717          */
2718 #ifdef PROGRAM
2719         if (testprogfile == NULL)
2720         {
2721                 if ((tmp2 = (char *)malloc(strlen(testprogdir) + 1 +
2722                         strlen(PROGRAM) + 1)) == NULL)
2723                 {
2724                         fprintf(stderr, "ERROR: Out of memory.");
2725                         exit(1);
2726                 }
2727                 strcpy(tmp2, testprogdir);
2728                 strcat(tmp2, "/");
2729                 strcat(tmp2, PROGRAM);
2730                 testprogfile = tmp2;
2731         }
2732
2733         {
2734                 char *testprg;
2735 #if defined(_WIN32) && !defined(__CYGWIN__)
2736                 /* Command.com sometimes rejects '/' separators. */
2737                 testprg = strdup(testprogfile);
2738                 for (i = 0; testprg[i] != '\0'; i++) {
2739                         if (testprg[i] == '/')
2740                                 testprg[i] = '\\';
2741                 }
2742                 testprogfile = testprg;
2743 #endif
2744                 /* Quote the name that gets put into shell command lines. */
2745                 testprg = malloc(strlen(testprogfile) + 3);
2746                 strcpy(testprg, "\"");
2747                 strcat(testprg, testprogfile);
2748                 strcat(testprg, "\"");
2749                 testprog = testprg;
2750         }
2751 #endif
2752
2753 #if !defined(_WIN32) && defined(SIGPIPE)
2754         {   /* Ignore SIGPIPE signals */
2755                 struct sigaction sa;
2756                 sa.sa_handler = SIG_IGN;
2757                 sigemptyset(&sa.sa_mask);
2758                 sa.sa_flags = 0;
2759                 sigaction(SIGPIPE, &sa, NULL);
2760         }
2761 #endif
2762
2763         /*
2764          * Create a temp directory for the following tests.
2765          * Include the time the tests started as part of the name,
2766          * to make it easier to track the results of multiple tests.
2767          */
2768         now = time(NULL);
2769         for (i = 0; ; i++) {
2770                 strftime(tmpdir_timestamp, sizeof(tmpdir_timestamp),
2771                     "%Y-%m-%dT%H.%M.%S",
2772                     localtime(&now));
2773                 sprintf(tmpdir, "%s/%s.%s-%03d", tmp, progname,
2774                     tmpdir_timestamp, i);
2775                 if (assertMakeDir(tmpdir,0755))
2776                         break;
2777                 if (i >= 999) {
2778                         fprintf(stderr,
2779                             "ERROR: Unable to create temp directory %s\n",
2780                             tmpdir);
2781                         exit(1);
2782                 }
2783         }
2784
2785         /*
2786          * If the user didn't specify a directory for locating
2787          * reference files, try to find the reference files in
2788          * the "usual places."
2789          */
2790         refdir = refdir_alloc = get_refdir(refdir);
2791
2792         /*
2793          * Banner with basic information.
2794          */
2795         printf("\n");
2796         printf("If tests fail or crash, details will be in:\n");
2797         printf("   %s\n", tmpdir);
2798         printf("\n");
2799         if (verbosity > VERBOSITY_SUMMARY_ONLY) {
2800                 printf("Reference files will be read from: %s\n", refdir);
2801 #ifdef PROGRAM
2802                 printf("Running tests on: %s\n", testprog);
2803 #endif
2804                 printf("Exercising: ");
2805                 fflush(stdout);
2806                 printf("%s\n", EXTRA_VERSION);
2807         } else {
2808                 printf("Running ");
2809                 fflush(stdout);
2810         }
2811
2812         /*
2813          * Run some or all of the individual tests.
2814          */
2815         saved_argv = argv;
2816         do {
2817                 argv = saved_argv;
2818                 do {
2819                         int test_num;
2820
2821                         test_num = get_test_set(test_set, limit, *argv, tests);
2822                         if (test_num < 0) {
2823                                 printf("*** INVALID Test %s\n", *argv);
2824                                 free(refdir_alloc);
2825                                 free(testprogdir);
2826                                 usage(progname);
2827                                 return (1);
2828                         }
2829                         for (i = 0; i < test_num; i++) {
2830                                 tests_run++;
2831                                 if (test_run(test_set[i], tmpdir)) {
2832                                         tests_failed++;
2833                                         if (until_failure)
2834                                                 goto finish;
2835                                 }
2836                         }
2837                         if (*argv != NULL)
2838                                 argv++;
2839                 } while (*argv != NULL);
2840         } while (until_failure);
2841
2842 finish:
2843         /* Must be freed after all tests run */
2844         free(tmp2);
2845         free(testprogdir);
2846         free(pwd);
2847
2848         /*
2849          * Report summary statistics.
2850          */
2851         if (verbosity > VERBOSITY_SUMMARY_ONLY) {
2852                 printf("\n");
2853                 printf("Totals:\n");
2854                 printf("  Tests run:         %8d\n", tests_run);
2855                 printf("  Tests failed:      %8d\n", tests_failed);
2856                 printf("  Assertions checked:%8d\n", assertions);
2857                 printf("  Assertions failed: %8d\n", failures);
2858                 printf("  Skips reported:    %8d\n", skips);
2859         }
2860         if (failures) {
2861                 printf("\n");
2862                 printf("Failing tests:\n");
2863                 for (i = 0; i < limit; ++i) {
2864                         if (tests[i].failures)
2865                                 printf("  %d: %s (%d failures)\n", i,
2866                                     tests[i].name, tests[i].failures);
2867                 }
2868                 printf("\n");
2869                 printf("Details for failing tests: %s\n", tmpdir);
2870                 printf("\n");
2871         } else {
2872                 if (verbosity == VERBOSITY_SUMMARY_ONLY)
2873                         printf("\n");
2874                 printf("%d tests passed, no failures\n", tests_run);
2875         }
2876
2877         free(refdir_alloc);
2878
2879         /* If the final tmpdir is empty, we can remove it. */
2880         /* This should be the usual case when all tests succeed. */
2881         assertChdir("..");
2882         rmdir(tmpdir);
2883
2884         return (tests_failed ? 1 : 0);
2885 }