]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/libarchive/libarchive/test/main.c
Copy head (r256279) to stable/10 as part of the 10.0-RELEASE cycle.
[FreeBSD/stable/10.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 /* Assert that 'pathname' is a dir.  If mode >= 0, verify that too. */
1400 int
1401 assertion_is_dir(const char *file, int line, const char *pathname, int mode)
1402 {
1403         struct stat st;
1404         int r;
1405
1406 #if defined(_WIN32) && !defined(__CYGWIN__)
1407         (void)mode; /* UNUSED */
1408 #endif
1409         assertion_count(file, line);
1410         r = lstat(pathname, &st);
1411         if (r != 0) {
1412                 failure_start(file, line, "Dir should exist: %s", pathname);
1413                 failure_finish(NULL);
1414                 return (0);
1415         }
1416         if (!S_ISDIR(st.st_mode)) {
1417                 failure_start(file, line, "%s is not a dir", pathname);
1418                 failure_finish(NULL);
1419                 return (0);
1420         }
1421 #if !defined(_WIN32) || defined(__CYGWIN__)
1422         /* Windows doesn't handle permissions the same way as POSIX,
1423          * so just ignore the mode tests. */
1424         /* TODO: Can we do better here? */
1425         if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {
1426                 failure_start(file, line, "Dir %s has wrong mode", pathname);
1427                 logprintf("  Expected: 0%3o\n", mode);
1428                 logprintf("  Found: 0%3o\n", st.st_mode & 07777);
1429                 failure_finish(NULL);
1430                 return (0);
1431         }
1432 #endif
1433         return (1);
1434 }
1435
1436 /* Verify that 'pathname' is a regular file.  If 'mode' is >= 0,
1437  * verify that too. */
1438 int
1439 assertion_is_reg(const char *file, int line, const char *pathname, int mode)
1440 {
1441         struct stat st;
1442         int r;
1443
1444 #if defined(_WIN32) && !defined(__CYGWIN__)
1445         (void)mode; /* UNUSED */
1446 #endif
1447         assertion_count(file, line);
1448         r = lstat(pathname, &st);
1449         if (r != 0 || !S_ISREG(st.st_mode)) {
1450                 failure_start(file, line, "File should exist: %s", pathname);
1451                 failure_finish(NULL);
1452                 return (0);
1453         }
1454 #if !defined(_WIN32) || defined(__CYGWIN__)
1455         /* Windows doesn't handle permissions the same way as POSIX,
1456          * so just ignore the mode tests. */
1457         /* TODO: Can we do better here? */
1458         if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {
1459                 failure_start(file, line, "File %s has wrong mode", pathname);
1460                 logprintf("  Expected: 0%3o\n", mode);
1461                 logprintf("  Found: 0%3o\n", st.st_mode & 07777);
1462                 failure_finish(NULL);
1463                 return (0);
1464         }
1465 #endif
1466         return (1);
1467 }
1468
1469 /* Check whether 'pathname' is a symbolic link.  If 'contents' is
1470  * non-NULL, verify that the symlink has those contents. */
1471 static int
1472 is_symlink(const char *file, int line,
1473     const char *pathname, const char *contents)
1474 {
1475 #if defined(_WIN32) && !defined(__CYGWIN__)
1476         (void)pathname; /* UNUSED */
1477         (void)contents; /* UNUSED */
1478         assertion_count(file, line);
1479         /* Windows sort-of has real symlinks, but they're only usable
1480          * by privileged users and are crippled even then, so there's
1481          * really not much point in bothering with this. */
1482         return (0);
1483 #else
1484         char buff[300];
1485         struct stat st;
1486         ssize_t linklen;
1487         int r;
1488
1489         assertion_count(file, line);
1490         r = lstat(pathname, &st);
1491         if (r != 0) {
1492                 failure_start(file, line,
1493                     "Symlink should exist: %s", pathname);
1494                 failure_finish(NULL);
1495                 return (0);
1496         }
1497         if (!S_ISLNK(st.st_mode))
1498                 return (0);
1499         if (contents == NULL)
1500                 return (1);
1501         linklen = readlink(pathname, buff, sizeof(buff));
1502         if (linklen < 0) {
1503                 failure_start(file, line, "Can't read symlink %s", pathname);
1504                 failure_finish(NULL);
1505                 return (0);
1506         }
1507         buff[linklen] = '\0';
1508         if (strcmp(buff, contents) != 0)
1509                 return (0);
1510         return (1);
1511 #endif
1512 }
1513
1514 /* Assert that path is a symlink that (optionally) contains contents. */
1515 int
1516 assertion_is_symlink(const char *file, int line,
1517     const char *path, const char *contents)
1518 {
1519         if (is_symlink(file, line, path, contents))
1520                 return (1);
1521         if (contents)
1522                 failure_start(file, line, "File %s is not a symlink to %s",
1523                     path, contents);
1524         else
1525                 failure_start(file, line, "File %s is not a symlink", path);
1526         failure_finish(NULL);
1527         return (0);
1528 }
1529
1530
1531 /* Create a directory and report any errors. */
1532 int
1533 assertion_make_dir(const char *file, int line, const char *dirname, int mode)
1534 {
1535         assertion_count(file, line);
1536 #if defined(_WIN32) && !defined(__CYGWIN__)
1537         (void)mode; /* UNUSED */
1538         if (0 == _mkdir(dirname))
1539                 return (1);
1540 #else
1541         if (0 == mkdir(dirname, mode))
1542                 return (1);
1543 #endif
1544         failure_start(file, line, "Could not create directory %s", dirname);
1545         failure_finish(NULL);
1546         return(0);
1547 }
1548
1549 /* Create a file with the specified contents and report any failures. */
1550 int
1551 assertion_make_file(const char *file, int line,
1552     const char *path, int mode, int csize, const void *contents)
1553 {
1554 #if defined(_WIN32) && !defined(__CYGWIN__)
1555         /* TODO: Rework this to set file mode as well. */
1556         FILE *f;
1557         (void)mode; /* UNUSED */
1558         assertion_count(file, line);
1559         f = fopen(path, "wb");
1560         if (f == NULL) {
1561                 failure_start(file, line, "Could not create file %s", path);
1562                 failure_finish(NULL);
1563                 return (0);
1564         }
1565         if (contents != NULL) {
1566                 size_t wsize;
1567
1568                 if (csize < 0)
1569                         wsize = strlen(contents);
1570                 else
1571                         wsize = (size_t)csize;
1572                 if (wsize != fwrite(contents, 1, wsize, f)) {
1573                         fclose(f);
1574                         failure_start(file, line,
1575                             "Could not write file %s", path);
1576                         failure_finish(NULL);
1577                         return (0);
1578                 }
1579         }
1580         fclose(f);
1581         return (1);
1582 #else
1583         int fd;
1584         assertion_count(file, line);
1585         fd = open(path, O_CREAT | O_WRONLY, mode >= 0 ? mode : 0644);
1586         if (fd < 0) {
1587                 failure_start(file, line, "Could not create %s", path);
1588                 failure_finish(NULL);
1589                 return (0);
1590         }
1591         if (contents != NULL) {
1592                 ssize_t wsize;
1593
1594                 if (csize < 0)
1595                         wsize = (ssize_t)strlen(contents);
1596                 else
1597                         wsize = (ssize_t)csize;
1598                 if (wsize != write(fd, contents, wsize)) {
1599                         close(fd);
1600                         failure_start(file, line,
1601                             "Could not write to %s", path);
1602                         failure_finish(NULL);
1603                         return (0);
1604                 }
1605         }
1606         close(fd);
1607         return (1);
1608 #endif
1609 }
1610
1611 /* Create a hardlink and report any failures. */
1612 int
1613 assertion_make_hardlink(const char *file, int line,
1614     const char *newpath, const char *linkto)
1615 {
1616         int succeeded;
1617
1618         assertion_count(file, line);
1619 #if defined(_WIN32) && !defined(__CYGWIN__)
1620         succeeded = my_CreateHardLinkA(newpath, linkto);
1621 #elif HAVE_LINK
1622         succeeded = !link(linkto, newpath);
1623 #else
1624         succeeded = 0;
1625 #endif
1626         if (succeeded)
1627                 return (1);
1628         failure_start(file, line, "Could not create hardlink");
1629         logprintf("   New link: %s\n", newpath);
1630         logprintf("   Old name: %s\n", linkto);
1631         failure_finish(NULL);
1632         return(0);
1633 }
1634
1635 /* Create a symlink and report any failures. */
1636 int
1637 assertion_make_symlink(const char *file, int line,
1638     const char *newpath, const char *linkto)
1639 {
1640 #if defined(_WIN32) && !defined(__CYGWIN__)
1641         int targetIsDir = 0;  /* TODO: Fix this */
1642         assertion_count(file, line);
1643         if (my_CreateSymbolicLinkA(newpath, linkto, targetIsDir))
1644                 return (1);
1645 #elif HAVE_SYMLINK
1646         assertion_count(file, line);
1647         if (0 == symlink(linkto, newpath))
1648                 return (1);
1649 #endif
1650         failure_start(file, line, "Could not create symlink");
1651         logprintf("   New link: %s\n", newpath);
1652         logprintf("   Old name: %s\n", linkto);
1653         failure_finish(NULL);
1654         return(0);
1655 }
1656
1657 /* Set umask, report failures. */
1658 int
1659 assertion_umask(const char *file, int line, int mask)
1660 {
1661         assertion_count(file, line);
1662         (void)file; /* UNUSED */
1663         (void)line; /* UNUSED */
1664         umask(mask);
1665         return (1);
1666 }
1667
1668 /* Set times, report failures. */
1669 int
1670 assertion_utimes(const char *file, int line,
1671     const char *pathname, long at, long at_nsec, long mt, long mt_nsec)
1672 {
1673         int r;
1674
1675 #if defined(_WIN32) && !defined(__CYGWIN__)
1676 #define WINTIME(sec, nsec) ((Int32x32To64(sec, 10000000) + EPOC_TIME)\
1677          + (((nsec)/1000)*10))
1678         HANDLE h;
1679         ULARGE_INTEGER wintm;
1680         FILETIME fatime, fmtime;
1681         FILETIME *pat, *pmt;
1682
1683         assertion_count(file, line);
1684         h = CreateFileA(pathname,GENERIC_READ | GENERIC_WRITE,
1685                     FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1686                     FILE_FLAG_BACKUP_SEMANTICS, NULL);
1687         if (h == INVALID_HANDLE_VALUE) {
1688                 failure_start(file, line, "Can't access %s\n", pathname);
1689                 failure_finish(NULL);
1690                 return (0);
1691         }
1692
1693         if (at > 0 || at_nsec > 0) {
1694                 wintm.QuadPart = WINTIME(at, at_nsec);
1695                 fatime.dwLowDateTime = wintm.LowPart;
1696                 fatime.dwHighDateTime = wintm.HighPart;
1697                 pat = &fatime;
1698         } else
1699                 pat = NULL;
1700         if (mt > 0 || mt_nsec > 0) {
1701                 wintm.QuadPart = WINTIME(mt, mt_nsec);
1702                 fmtime.dwLowDateTime = wintm.LowPart;
1703                 fmtime.dwHighDateTime = wintm.HighPart;
1704                 pmt = &fmtime;
1705         } else
1706                 pmt = NULL;
1707         if (pat != NULL || pmt != NULL)
1708                 r = SetFileTime(h, NULL, pat, pmt);
1709         else
1710                 r = 1;
1711         CloseHandle(h);
1712         if (r == 0) {
1713                 failure_start(file, line, "Can't SetFileTime %s\n", pathname);
1714                 failure_finish(NULL);
1715                 return (0);
1716         }
1717         return (1);
1718 #else /* defined(_WIN32) && !defined(__CYGWIN__) */
1719         struct stat st;
1720         struct timeval times[2];
1721
1722 #if !defined(__FreeBSD__)
1723         mt_nsec = at_nsec = 0;  /* Generic POSIX only has whole seconds. */
1724 #endif
1725         if (mt == 0 && mt_nsec == 0 && at == 0 && at_nsec == 0)
1726                 return (1);
1727
1728         r = lstat(pathname, &st);
1729         if (r < 0) {
1730                 failure_start(file, line, "Can't stat %s\n", pathname);
1731                 failure_finish(NULL);
1732                 return (0);
1733         }
1734
1735         if (mt == 0 && mt_nsec == 0) {
1736                 mt = st.st_mtime;
1737 #if defined(__FreeBSD__)
1738                 mt_nsec = st.st_mtimespec.tv_nsec;
1739                 /* FreeBSD generally only stores to microsecond res, so round. */
1740                 mt_nsec = (mt_nsec / 1000) * 1000;
1741 #endif
1742         }
1743         if (at == 0 && at_nsec == 0) {
1744                 at = st.st_atime;
1745 #if defined(__FreeBSD__)
1746                 at_nsec = st.st_atimespec.tv_nsec;
1747                 /* FreeBSD generally only stores to microsecond res, so round. */
1748                 at_nsec = (at_nsec / 1000) * 1000;
1749 #endif
1750         }
1751
1752         times[1].tv_sec = mt;
1753         times[1].tv_usec = mt_nsec / 1000;
1754
1755         times[0].tv_sec = at;
1756         times[0].tv_usec = at_nsec / 1000;
1757
1758 #ifdef HAVE_LUTIMES
1759         r = lutimes(pathname, times);
1760 #else
1761         r = utimes(pathname, times);
1762 #endif
1763         if (r < 0) {
1764                 failure_start(file, line, "Can't utimes %s\n", pathname);
1765                 failure_finish(NULL);
1766                 return (0);
1767         }
1768         return (1);
1769 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
1770 }
1771
1772 /* Set nodump, report failures. */
1773 int
1774 assertion_nodump(const char *file, int line, const char *pathname)
1775 {
1776 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
1777         int r;
1778
1779         assertion_count(file, line);
1780         r = chflags(pathname, UF_NODUMP);
1781         if (r < 0) {
1782                 failure_start(file, line, "Can't set nodump %s\n", pathname);
1783                 failure_finish(NULL);
1784                 return (0);
1785         }
1786 #elif defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)\
1787          && defined(EXT2_NODUMP_FL)
1788         int fd, r, flags;
1789
1790         assertion_count(file, line);
1791         fd = open(pathname, O_RDONLY | O_NONBLOCK);
1792         if (fd < 0) {
1793                 failure_start(file, line, "Can't open %s\n", pathname);
1794                 failure_finish(NULL);
1795                 return (0);
1796         }
1797         r = ioctl(fd, EXT2_IOC_GETFLAGS, &flags);
1798         if (r < 0) {
1799                 failure_start(file, line, "Can't get flags %s\n", pathname);
1800                 failure_finish(NULL);
1801                 return (0);
1802         }
1803         flags |= EXT2_NODUMP_FL;
1804         r = ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
1805         if (r < 0) {
1806                 failure_start(file, line, "Can't set nodump %s\n", pathname);
1807                 failure_finish(NULL);
1808                 return (0);
1809         }
1810         close(fd);
1811 #else
1812         (void)pathname; /* UNUSED */
1813         assertion_count(file, line);
1814 #endif
1815         return (1);
1816 }
1817
1818 /*
1819  *
1820  *  UTILITIES for use by tests.
1821  *
1822  */
1823
1824 /*
1825  * Check whether platform supports symlinks.  This is intended
1826  * for tests to use in deciding whether to bother testing symlink
1827  * support; if the platform doesn't support symlinks, there's no point
1828  * in checking whether the program being tested can create them.
1829  *
1830  * Note that the first time this test is called, we actually go out to
1831  * disk to create and verify a symlink.  This is necessary because
1832  * symlink support is actually a property of a particular filesystem
1833  * and can thus vary between directories on a single system.  After
1834  * the first call, this returns the cached result from memory, so it's
1835  * safe to call it as often as you wish.
1836  */
1837 int
1838 canSymlink(void)
1839 {
1840         /* Remember the test result */
1841         static int value = 0, tested = 0;
1842         if (tested)
1843                 return (value);
1844
1845         ++tested;
1846         assertion_make_file(__FILE__, __LINE__, "canSymlink.0", 0644, 1, "a");
1847         /* Note: Cygwin has its own symlink() emulation that does not
1848          * use the Win32 CreateSymbolicLink() function. */
1849 #if defined(_WIN32) && !defined(__CYGWIN__)
1850         value = my_CreateSymbolicLinkA("canSymlink.1", "canSymlink.0", 0)
1851             && is_symlink(__FILE__, __LINE__, "canSymlink.1", "canSymlink.0");
1852 #elif HAVE_SYMLINK
1853         value = (0 == symlink("canSymlink.0", "canSymlink.1"))
1854             && is_symlink(__FILE__, __LINE__, "canSymlink.1","canSymlink.0");
1855 #endif
1856         return (value);
1857 }
1858
1859 /* Platform-dependent options for hiding the output of a subcommand. */
1860 #if defined(_WIN32) && !defined(__CYGWIN__)
1861 static const char *redirectArgs = ">NUL 2>NUL"; /* Win32 cmd.exe */
1862 #else
1863 static const char *redirectArgs = ">/dev/null 2>/dev/null"; /* POSIX 'sh' */
1864 #endif
1865 /*
1866  * Can this platform run the bzip2 program?
1867  */
1868 int
1869 canBzip2(void)
1870 {
1871         static int tested = 0, value = 0;
1872         if (!tested) {
1873                 tested = 1;
1874                 if (systemf("bzip2 -d -V %s", redirectArgs) == 0)
1875                         value = 1;
1876         }
1877         return (value);
1878 }
1879
1880 /*
1881  * Can this platform run the grzip program?
1882  */
1883 int
1884 canGrzip(void)
1885 {
1886         static int tested = 0, value = 0;
1887         if (!tested) {
1888                 tested = 1;
1889                 if (systemf("grzip -V %s", redirectArgs) == 0)
1890                         value = 1;
1891         }
1892         return (value);
1893 }
1894
1895 /*
1896  * Can this platform run the gzip program?
1897  */
1898 int
1899 canGzip(void)
1900 {
1901         static int tested = 0, value = 0;
1902         if (!tested) {
1903                 tested = 1;
1904                 if (systemf("gzip -V %s", redirectArgs) == 0)
1905                         value = 1;
1906         }
1907         return (value);
1908 }
1909
1910 /*
1911  * Can this platform run the lrzip program?
1912  */
1913 int
1914 canRunCommand(const char *cmd)
1915 {
1916   static int tested = 0, value = 0;
1917   if (!tested) {
1918     tested = 1;
1919     if (systemf("%s %s", cmd, redirectArgs) == 0)
1920       value = 1;
1921   }
1922   return (value);
1923 }
1924
1925 int
1926 canLrzip(void)
1927 {
1928         static int tested = 0, value = 0;
1929         if (!tested) {
1930                 tested = 1;
1931                 if (systemf("lrzip -V %s", redirectArgs) == 0)
1932                         value = 1;
1933         }
1934         return (value);
1935 }
1936
1937 /*
1938  * Can this platform run the lzip program?
1939  */
1940 int
1941 canLzip(void)
1942 {
1943         static int tested = 0, value = 0;
1944         if (!tested) {
1945                 tested = 1;
1946                 if (systemf("lzip -V %s", redirectArgs) == 0)
1947                         value = 1;
1948         }
1949         return (value);
1950 }
1951
1952 /*
1953  * Can this platform run the lzma program?
1954  */
1955 int
1956 canLzma(void)
1957 {
1958         static int tested = 0, value = 0;
1959         if (!tested) {
1960                 tested = 1;
1961                 if (systemf("lzma -V %s", redirectArgs) == 0)
1962                         value = 1;
1963         }
1964         return (value);
1965 }
1966
1967 /*
1968  * Can this platform run the lzop program?
1969  */
1970 int
1971 canLzop(void)
1972 {
1973         static int tested = 0, value = 0;
1974         if (!tested) {
1975                 tested = 1;
1976                 if (systemf("lzop -V %s", redirectArgs) == 0)
1977                         value = 1;
1978         }
1979         return (value);
1980 }
1981
1982 /*
1983  * Can this platform run the xz program?
1984  */
1985 int
1986 canXz(void)
1987 {
1988         static int tested = 0, value = 0;
1989         if (!tested) {
1990                 tested = 1;
1991                 if (systemf("xz -V %s", redirectArgs) == 0)
1992                         value = 1;
1993         }
1994         return (value);
1995 }
1996
1997 /*
1998  * Can this filesystem handle nodump flags.
1999  */
2000 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2001
2002 int
2003 canNodump(void)
2004 {
2005         const char *path = "cannodumptest";
2006         struct stat sb;
2007
2008         assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);
2009         if (chflags(path, UF_NODUMP) < 0)
2010                 return (0);
2011         if (stat(path, &sb) < 0)
2012                 return (0);
2013         if (sb.st_flags & UF_NODUMP)
2014                 return (1);
2015         return (0);
2016 }
2017
2018 #elif defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)\
2019          && defined(EXT2_NODUMP_FL)
2020
2021 int
2022 canNodump(void)
2023 {
2024         const char *path = "cannodumptest";
2025         int fd, r, flags;
2026
2027         assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);
2028         fd = open(path, O_RDONLY | O_NONBLOCK);
2029         if (fd < 0)
2030                 return (0);
2031         r = ioctl(fd, EXT2_IOC_GETFLAGS, &flags);
2032         if (r < 0)
2033                 return (0);
2034         flags |= EXT2_NODUMP_FL;
2035         r = ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
2036         if (r < 0)
2037                 return (0);
2038         close(fd);
2039         fd = open(path, O_RDONLY | O_NONBLOCK);
2040         if (fd < 0)
2041                 return (0);
2042         r = ioctl(fd, EXT2_IOC_GETFLAGS, &flags);
2043         if (r < 0)
2044                 return (0);
2045         close(fd);
2046         if (flags & EXT2_NODUMP_FL)
2047                 return (1);
2048         return (0);
2049 }
2050
2051 #else
2052
2053 int
2054 canNodump()
2055 {
2056         return (0);
2057 }
2058
2059 #endif
2060
2061 /*
2062  * Sleep as needed; useful for verifying disk timestamp changes by
2063  * ensuring that the wall-clock time has actually changed before we
2064  * go back to re-read something from disk.
2065  */
2066 void
2067 sleepUntilAfter(time_t t)
2068 {
2069         while (t >= time(NULL))
2070 #if defined(_WIN32) && !defined(__CYGWIN__)
2071                 Sleep(500);
2072 #else
2073                 sleep(1);
2074 #endif
2075 }
2076
2077 /*
2078  * Call standard system() call, but build up the command line using
2079  * sprintf() conventions.
2080  */
2081 int
2082 systemf(const char *fmt, ...)
2083 {
2084         char buff[8192];
2085         va_list ap;
2086         int r;
2087
2088         va_start(ap, fmt);
2089         vsprintf(buff, fmt, ap);
2090         if (verbosity > VERBOSITY_FULL)
2091                 logprintf("Cmd: %s\n", buff);
2092         r = system(buff);
2093         va_end(ap);
2094         return (r);
2095 }
2096
2097 /*
2098  * Slurp a file into memory for ease of comparison and testing.
2099  * Returns size of file in 'sizep' if non-NULL, null-terminates
2100  * data in memory for ease of use.
2101  */
2102 char *
2103 slurpfile(size_t * sizep, const char *fmt, ...)
2104 {
2105         char filename[8192];
2106         struct stat st;
2107         va_list ap;
2108         char *p;
2109         ssize_t bytes_read;
2110         FILE *f;
2111         int r;
2112
2113         va_start(ap, fmt);
2114         vsprintf(filename, fmt, ap);
2115         va_end(ap);
2116
2117         f = fopen(filename, "rb");
2118         if (f == NULL) {
2119                 /* Note: No error; non-existent file is okay here. */
2120                 return (NULL);
2121         }
2122         r = fstat(fileno(f), &st);
2123         if (r != 0) {
2124                 logprintf("Can't stat file %s\n", filename);
2125                 fclose(f);
2126                 return (NULL);
2127         }
2128         p = malloc((size_t)st.st_size + 1);
2129         if (p == NULL) {
2130                 logprintf("Can't allocate %ld bytes of memory to read file %s\n",
2131                     (long int)st.st_size, filename);
2132                 fclose(f);
2133                 return (NULL);
2134         }
2135         bytes_read = fread(p, 1, (size_t)st.st_size, f);
2136         if (bytes_read < st.st_size) {
2137                 logprintf("Can't read file %s\n", filename);
2138                 fclose(f);
2139                 free(p);
2140                 return (NULL);
2141         }
2142         p[st.st_size] = '\0';
2143         if (sizep != NULL)
2144                 *sizep = (size_t)st.st_size;
2145         fclose(f);
2146         return (p);
2147 }
2148
2149 /* Read a uuencoded file from the reference directory, decode, and
2150  * write the result into the current directory. */
2151 #define UUDECODE(c) (((c) - 0x20) & 0x3f)
2152 void
2153 extract_reference_file(const char *name)
2154 {
2155         char buff[1024];
2156         FILE *in, *out;
2157
2158         sprintf(buff, "%s/%s.uu", refdir, name);
2159         in = fopen(buff, "r");
2160         failure("Couldn't open reference file %s", buff);
2161         assert(in != NULL);
2162         if (in == NULL)
2163                 return;
2164         /* Read up to and including the 'begin' line. */
2165         for (;;) {
2166                 if (fgets(buff, sizeof(buff), in) == NULL) {
2167                         /* TODO: This is a failure. */
2168                         return;
2169                 }
2170                 if (memcmp(buff, "begin ", 6) == 0)
2171                         break;
2172         }
2173         /* Now, decode the rest and write it. */
2174         /* Not a lot of error checking here; the input better be right. */
2175         out = fopen(name, "wb");
2176         while (fgets(buff, sizeof(buff), in) != NULL) {
2177                 char *p = buff;
2178                 int bytes;
2179
2180                 if (memcmp(buff, "end", 3) == 0)
2181                         break;
2182
2183                 bytes = UUDECODE(*p++);
2184                 while (bytes > 0) {
2185                         int n = 0;
2186                         /* Write out 1-3 bytes from that. */
2187                         if (bytes > 0) {
2188                                 n = UUDECODE(*p++) << 18;
2189                                 n |= UUDECODE(*p++) << 12;
2190                                 fputc(n >> 16, out);
2191                                 --bytes;
2192                         }
2193                         if (bytes > 0) {
2194                                 n |= UUDECODE(*p++) << 6;
2195                                 fputc((n >> 8) & 0xFF, out);
2196                                 --bytes;
2197                         }
2198                         if (bytes > 0) {
2199                                 n |= UUDECODE(*p++);
2200                                 fputc(n & 0xFF, out);
2201                                 --bytes;
2202                         }
2203                 }
2204         }
2205         fclose(out);
2206         fclose(in);
2207 }
2208
2209 int
2210 is_LargeInode(const char *file)
2211 {
2212 #if defined(_WIN32) && !defined(__CYGWIN__)
2213         BY_HANDLE_FILE_INFORMATION bhfi;
2214         int r;
2215
2216         r = my_GetFileInformationByName(file, &bhfi);
2217         if (r != 0)
2218                 return (0);
2219         return (bhfi.nFileIndexHigh & 0x0000FFFFUL);
2220 #else
2221         struct stat st;
2222         int64_t ino;
2223
2224         if (stat(file, &st) < 0)
2225                 return (0);
2226         ino = (int64_t)st.st_ino;
2227         return (ino > 0xffffffff);
2228 #endif
2229 }
2230
2231 void
2232 extract_reference_files(const char **names)
2233 {
2234         while (names && *names)
2235                 extract_reference_file(*names++);
2236 }
2237
2238 /*
2239  *
2240  * TEST management
2241  *
2242  */
2243
2244 /*
2245  * "list.h" is simply created by "grep DEFINE_TEST test_*.c"; it has
2246  * a line like
2247  *      DEFINE_TEST(test_function)
2248  * for each test.
2249  */
2250
2251 /* Use "list.h" to declare all of the test functions. */
2252 #undef DEFINE_TEST
2253 #define DEFINE_TEST(name) void name(void);
2254 #include "list.h"
2255
2256 /* Use "list.h" to create a list of all tests (functions and names). */
2257 #undef DEFINE_TEST
2258 #define DEFINE_TEST(n) { n, #n, 0 },
2259 struct test_list_t tests[] = {
2260         #include "list.h"
2261 };
2262
2263 /*
2264  * Summarize repeated failures in the just-completed test.
2265  */
2266 static void
2267 test_summarize(int failed)
2268 {
2269         unsigned int i;
2270
2271         switch (verbosity) {
2272         case VERBOSITY_SUMMARY_ONLY:
2273                 printf(failed ? "E" : ".");
2274                 fflush(stdout);
2275                 break;
2276         case VERBOSITY_PASSFAIL:
2277                 printf(failed ? "FAIL\n" : "ok\n");
2278                 break;
2279         }
2280
2281         log_console = (verbosity == VERBOSITY_LIGHT_REPORT);
2282
2283         for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {
2284                 if (failed_lines[i].count > 1 && !failed_lines[i].skip)
2285                         logprintf("%s:%d: Summary: Failed %d times\n",
2286                             failed_filename, i, failed_lines[i].count);
2287         }
2288         /* Clear the failure history for the next file. */
2289         failed_filename = NULL;
2290         memset(failed_lines, 0, sizeof(failed_lines));
2291 }
2292
2293 /*
2294  * Actually run a single test, with appropriate setup and cleanup.
2295  */
2296 static int
2297 test_run(int i, const char *tmpdir)
2298 {
2299         char workdir[1024];
2300         char logfilename[64];
2301         int failures_before = failures;
2302         int oldumask;
2303
2304         switch (verbosity) {
2305         case VERBOSITY_SUMMARY_ONLY: /* No per-test reports at all */
2306                 break;
2307         case VERBOSITY_PASSFAIL: /* rest of line will include ok/FAIL marker */
2308                 printf("%3d: %-50s", i, tests[i].name);
2309                 fflush(stdout);
2310                 break;
2311         default: /* Title of test, details will follow */
2312                 printf("%3d: %s\n", i, tests[i].name);
2313         }
2314
2315         /* Chdir to the top-level work directory. */
2316         if (!assertChdir(tmpdir)) {
2317                 fprintf(stderr,
2318                     "ERROR: Can't chdir to top work dir %s\n", tmpdir);
2319                 exit(1);
2320         }
2321         /* Create a log file for this test. */
2322         sprintf(logfilename, "%s.log", tests[i].name);
2323         logfile = fopen(logfilename, "w");
2324         fprintf(logfile, "%s\n\n", tests[i].name);
2325         /* Chdir() to a work dir for this specific test. */
2326         snprintf(workdir, sizeof(workdir), "%s/%s", tmpdir, tests[i].name);
2327         testworkdir = workdir;
2328         if (!assertMakeDir(testworkdir, 0755)
2329             || !assertChdir(testworkdir)) {
2330                 fprintf(stderr,
2331                     "ERROR: Can't chdir to work dir %s\n", testworkdir);
2332                 exit(1);
2333         }
2334         /* Explicitly reset the locale before each test. */
2335         setlocale(LC_ALL, "C");
2336         /* Record the umask before we run the test. */
2337         umask(oldumask = umask(0));
2338         /*
2339          * Run the actual test.
2340          */
2341         (*tests[i].func)();
2342         /*
2343          * Clean up and report afterwards.
2344          */
2345         testworkdir = NULL;
2346         /* Restore umask */
2347         umask(oldumask);
2348         /* Reset locale. */
2349         setlocale(LC_ALL, "C");
2350         /* Reset directory. */
2351         if (!assertChdir(tmpdir)) {
2352                 fprintf(stderr, "ERROR: Couldn't chdir to temp dir %s\n",
2353                     tmpdir);
2354                 exit(1);
2355         }
2356         /* Report per-test summaries. */
2357         tests[i].failures = failures - failures_before;
2358         test_summarize(tests[i].failures);
2359         /* Close the per-test log file. */
2360         fclose(logfile);
2361         logfile = NULL;
2362         /* If there were no failures, we can remove the work dir and logfile. */
2363         if (tests[i].failures == 0) {
2364                 if (!keep_temp_files && assertChdir(tmpdir)) {
2365 #if defined(_WIN32) && !defined(__CYGWIN__)
2366                         /* Make sure not to leave empty directories.
2367                          * Sometimes a processing of closing files used by tests
2368                          * is not done, then rmdir will be failed and it will
2369                          * leave a empty test directory. So we should wait a few
2370                          * seconds and retry rmdir. */
2371                         int r, t;
2372                         for (t = 0; t < 10; t++) {
2373                                 if (t > 0)
2374                                         Sleep(1000);
2375                                 r = systemf("rmdir /S /Q %s", tests[i].name);
2376                                 if (r == 0)
2377                                         break;
2378                         }
2379                         systemf("del %s", logfilename);
2380 #else
2381                         systemf("rm -rf %s", tests[i].name);
2382                         systemf("rm %s", logfilename);
2383 #endif
2384                 }
2385         }
2386         /* Return appropriate status. */
2387         return (tests[i].failures);
2388 }
2389
2390 /*
2391  *
2392  *
2393  * MAIN and support routines.
2394  *
2395  *
2396  */
2397
2398 static void
2399 usage(const char *program)
2400 {
2401         static const int limit = sizeof(tests) / sizeof(tests[0]);
2402         int i;
2403
2404         printf("Usage: %s [options] <test> <test> ...\n", program);
2405         printf("Default is to run all tests.\n");
2406         printf("Otherwise, specify the numbers of the tests you wish to run.\n");
2407         printf("Options:\n");
2408         printf("  -d  Dump core after any failure, for debugging.\n");
2409         printf("  -k  Keep all temp files.\n");
2410         printf("      Default: temp files for successful tests deleted.\n");
2411 #ifdef PROGRAM
2412         printf("  -p <path>  Path to executable to be tested.\n");
2413         printf("      Default: path taken from " ENVBASE " environment variable.\n");
2414 #endif
2415         printf("  -q  Quiet.\n");
2416         printf("  -r <dir>   Path to dir containing reference files.\n");
2417         printf("      Default: Current directory.\n");
2418         printf("  -u  Keep running specifies tests until one fails.\n");
2419         printf("  -v  Verbose.\n");
2420         printf("Available tests:\n");
2421         for (i = 0; i < limit; i++)
2422                 printf("  %d: %s\n", i, tests[i].name);
2423         exit(1);
2424 }
2425
2426 static char *
2427 get_refdir(const char *d)
2428 {
2429         char tried[512] = { '\0' };
2430         char buff[128];
2431         char *pwd, *p;
2432
2433         /* If a dir was specified, try that */
2434         if (d != NULL) {
2435                 pwd = NULL;
2436                 snprintf(buff, sizeof(buff), "%s", d);
2437                 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2438                 if (p != NULL) goto success;
2439                 strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2440                 strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2441                 goto failure;
2442         }
2443
2444         /* Get the current dir. */
2445 #ifdef PATH_MAX
2446         pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */
2447 #else
2448         pwd = getcwd(NULL, 0);
2449 #endif
2450         while (pwd[strlen(pwd) - 1] == '\n')
2451                 pwd[strlen(pwd) - 1] = '\0';
2452
2453         /* Look for a known file. */
2454         snprintf(buff, sizeof(buff), "%s", pwd);
2455         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2456         if (p != NULL) goto success;
2457         strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2458         strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2459
2460         snprintf(buff, sizeof(buff), "%s/test", pwd);
2461         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2462         if (p != NULL) goto success;
2463         strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2464         strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2465
2466 #if defined(LIBRARY)
2467         snprintf(buff, sizeof(buff), "%s/%s/test", pwd, LIBRARY);
2468 #else
2469         snprintf(buff, sizeof(buff), "%s/%s/test", pwd, PROGRAM);
2470 #endif
2471         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2472         if (p != NULL) goto success;
2473         strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2474         strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2475
2476 #if defined(PROGRAM_ALIAS)
2477         snprintf(buff, sizeof(buff), "%s/%s/test", pwd, PROGRAM_ALIAS);
2478         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2479         if (p != NULL) goto success;
2480         strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2481         strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2482 #endif
2483
2484         if (memcmp(pwd, "/usr/obj", 8) == 0) {
2485                 snprintf(buff, sizeof(buff), "%s", pwd + 8);
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                 snprintf(buff, sizeof(buff), "%s/test", pwd + 8);
2492                 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
2493                 if (p != NULL) goto success;
2494                 strncat(tried, buff, sizeof(tried) - strlen(tried) - 1);
2495                 strncat(tried, "\n", sizeof(tried) - strlen(tried) - 1);
2496         }
2497
2498 failure:
2499         printf("Unable to locate known reference file %s\n", KNOWNREF);
2500         printf("  Checked following directories:\n%s\n", tried);
2501 #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
2502         DebugBreak();
2503 #endif
2504         exit(1);
2505
2506 success:
2507         free(p);
2508         free(pwd);
2509         return strdup(buff);
2510 }
2511
2512 int
2513 main(int argc, char **argv)
2514 {
2515         static const int limit = sizeof(tests) / sizeof(tests[0]);
2516         int test_set[sizeof(tests) / sizeof(tests[0])];
2517         int i = 0, j = 0, tests_run = 0, tests_failed = 0, option;
2518         time_t now;
2519         char *refdir_alloc = NULL;
2520         const char *progname;
2521         char **saved_argv;
2522         const char *tmp, *option_arg, *p;
2523         char tmpdir[256], *pwd, *testprogdir, *tmp2 = NULL, *vlevel = NULL;
2524         char tmpdir_timestamp[256];
2525
2526         (void)argc; /* UNUSED */
2527
2528         /* Get the current dir. */
2529 #ifdef PATH_MAX
2530         pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */
2531 #else
2532         pwd = getcwd(NULL, 0);
2533 #endif
2534         while (pwd[strlen(pwd) - 1] == '\n')
2535                 pwd[strlen(pwd) - 1] = '\0';
2536
2537 #if defined(HAVE__CrtSetReportMode)
2538         /* To stop to run the default invalid parameter handler. */
2539         _set_invalid_parameter_handler(invalid_parameter_handler);
2540         /* Disable annoying assertion message box. */
2541         _CrtSetReportMode(_CRT_ASSERT, 0);
2542 #endif
2543
2544         /*
2545          * Name of this program, used to build root of our temp directory
2546          * tree.
2547          */
2548         progname = p = argv[0];
2549         if ((testprogdir = (char *)malloc(strlen(progname) + 1)) == NULL)
2550         {
2551                 fprintf(stderr, "ERROR: Out of memory.");
2552                 exit(1);
2553         }
2554         strcpy(testprogdir, progname);
2555         while (*p != '\0') {
2556                 /* Support \ or / dir separators for Windows compat. */
2557                 if (*p == '/' || *p == '\\')
2558                 {
2559                         progname = p + 1;
2560                         i = j;
2561                 }
2562                 ++p;
2563                 j++;
2564         }
2565         testprogdir[i] = '\0';
2566 #if defined(_WIN32) && !defined(__CYGWIN__)
2567         if (testprogdir[0] != '/' && testprogdir[0] != '\\' &&
2568             !(((testprogdir[0] >= 'a' && testprogdir[0] <= 'z') ||
2569                (testprogdir[0] >= 'A' && testprogdir[0] <= 'Z')) &&
2570                 testprogdir[1] == ':' &&
2571                 (testprogdir[2] == '/' || testprogdir[2] == '\\')))
2572 #else
2573         if (testprogdir[0] != '/')
2574 #endif
2575         {
2576                 /* Fixup path for relative directories. */
2577                 if ((testprogdir = (char *)realloc(testprogdir,
2578                         strlen(pwd) + 1 + strlen(testprogdir) + 1)) == NULL)
2579                 {
2580                         fprintf(stderr, "ERROR: Out of memory.");
2581                         exit(1);
2582                 }
2583                 memmove(testprogdir + strlen(pwd) + 1, testprogdir,
2584                     strlen(testprogdir));
2585                 memcpy(testprogdir, pwd, strlen(pwd));
2586                 testprogdir[strlen(pwd)] = '/';
2587         }
2588
2589 #ifdef PROGRAM
2590         /* Get the target program from environment, if available. */
2591         testprogfile = getenv(ENVBASE);
2592 #endif
2593
2594         if (getenv("TMPDIR") != NULL)
2595                 tmp = getenv("TMPDIR");
2596         else if (getenv("TMP") != NULL)
2597                 tmp = getenv("TMP");
2598         else if (getenv("TEMP") != NULL)
2599                 tmp = getenv("TEMP");
2600         else if (getenv("TEMPDIR") != NULL)
2601                 tmp = getenv("TEMPDIR");
2602         else
2603                 tmp = "/tmp";
2604
2605         /* Allow -d to be controlled through the environment. */
2606         if (getenv(ENVBASE "_DEBUG") != NULL)
2607                 dump_on_failure = 1;
2608
2609         /* Allow -v to be controlled through the environment. */
2610         if (getenv("_VERBOSITY_LEVEL") != NULL)
2611         {
2612                 vlevel = getenv("_VERBOSITY_LEVEL");
2613                 verbosity = atoi(vlevel);
2614                 if (verbosity < VERBOSITY_SUMMARY_ONLY || verbosity > VERBOSITY_FULL)
2615                 {
2616                         /* Unsupported verbosity levels are silently ignored */
2617                         vlevel = NULL;
2618                         verbosity = VERBOSITY_PASSFAIL;
2619                 }
2620         }
2621
2622         /* Get the directory holding test files from environment. */
2623         refdir = getenv(ENVBASE "_TEST_FILES");
2624
2625         /*
2626          * Parse options, without using getopt(), which isn't available
2627          * on all platforms.
2628          */
2629         ++argv; /* Skip program name */
2630         while (*argv != NULL) {
2631                 if (**argv != '-')
2632                         break;
2633                 p = *argv++;
2634                 ++p; /* Skip '-' */
2635                 while (*p != '\0') {
2636                         option = *p++;
2637                         option_arg = NULL;
2638                         /* If 'opt' takes an argument, parse that. */
2639                         if (option == 'p' || option == 'r') {
2640                                 if (*p != '\0')
2641                                         option_arg = p;
2642                                 else if (*argv == NULL) {
2643                                         fprintf(stderr,
2644                                             "Option -%c requires argument.\n",
2645                                             option);
2646                                         usage(progname);
2647                                 } else
2648                                         option_arg = *argv++;
2649                                 p = ""; /* End of this option word. */
2650                         }
2651
2652                         /* Now, handle the option. */
2653                         switch (option) {
2654                         case 'd':
2655                                 dump_on_failure = 1;
2656                                 break;
2657                         case 'k':
2658                                 keep_temp_files = 1;
2659                                 break;
2660                         case 'p':
2661 #ifdef PROGRAM
2662                                 testprogfile = option_arg;
2663 #else
2664                                 fprintf(stderr, "-p option not permitted\n");
2665                                 usage(progname);
2666 #endif
2667                                 break;
2668                         case 'q':
2669                                 if (!vlevel)
2670                                         verbosity--;
2671                                 break;
2672                         case 'r':
2673                                 refdir = option_arg;
2674                                 break;
2675                         case 'u':
2676                                 until_failure++;
2677                                 break;
2678                         case 'v':
2679                                 if (!vlevel)
2680                                         verbosity++;
2681                                 break;
2682                         default:
2683                                 fprintf(stderr, "Unrecognized option '%c'\n",
2684                                     option);
2685                                 usage(progname);
2686                         }
2687                 }
2688         }
2689
2690         /*
2691          * Sanity-check that our options make sense.
2692          */
2693 #ifdef PROGRAM
2694         if (testprogfile == NULL)
2695         {
2696                 if ((tmp2 = (char *)malloc(strlen(testprogdir) + 1 +
2697                         strlen(PROGRAM) + 1)) == NULL)
2698                 {
2699                         fprintf(stderr, "ERROR: Out of memory.");
2700                         exit(1);
2701                 }
2702                 strcpy(tmp2, testprogdir);
2703                 strcat(tmp2, "/");
2704                 strcat(tmp2, PROGRAM);
2705                 testprogfile = tmp2;
2706         }
2707
2708         {
2709                 char *testprg;
2710 #if defined(_WIN32) && !defined(__CYGWIN__)
2711                 /* Command.com sometimes rejects '/' separators. */
2712                 testprg = strdup(testprogfile);
2713                 for (i = 0; testprg[i] != '\0'; i++) {
2714                         if (testprg[i] == '/')
2715                                 testprg[i] = '\\';
2716                 }
2717                 testprogfile = testprg;
2718 #endif
2719                 /* Quote the name that gets put into shell command lines. */
2720                 testprg = malloc(strlen(testprogfile) + 3);
2721                 strcpy(testprg, "\"");
2722                 strcat(testprg, testprogfile);
2723                 strcat(testprg, "\"");
2724                 testprog = testprg;
2725         }
2726 #endif
2727
2728 #if !defined(_WIN32) && defined(SIGPIPE)
2729         {   /* Ignore SIGPIPE signals */
2730                 struct sigaction sa;
2731                 sa.sa_handler = SIG_IGN;
2732                 sigemptyset(&sa.sa_mask);
2733                 sa.sa_flags = 0;
2734                 sigaction(SIGPIPE, &sa, NULL);
2735         }
2736 #endif
2737
2738         /*
2739          * Create a temp directory for the following tests.
2740          * Include the time the tests started as part of the name,
2741          * to make it easier to track the results of multiple tests.
2742          */
2743         now = time(NULL);
2744         for (i = 0; ; i++) {
2745                 strftime(tmpdir_timestamp, sizeof(tmpdir_timestamp),
2746                     "%Y-%m-%dT%H.%M.%S",
2747                     localtime(&now));
2748                 sprintf(tmpdir, "%s/%s.%s-%03d", tmp, progname,
2749                     tmpdir_timestamp, i);
2750                 if (assertMakeDir(tmpdir,0755))
2751                         break;
2752                 if (i >= 999) {
2753                         fprintf(stderr,
2754                             "ERROR: Unable to create temp directory %s\n",
2755                             tmpdir);
2756                         exit(1);
2757                 }
2758         }
2759
2760         /*
2761          * If the user didn't specify a directory for locating
2762          * reference files, try to find the reference files in
2763          * the "usual places."
2764          */
2765         refdir = refdir_alloc = get_refdir(refdir);
2766
2767         /*
2768          * Banner with basic information.
2769          */
2770         printf("\n");
2771         printf("If tests fail or crash, details will be in:\n");
2772         printf("   %s\n", tmpdir);
2773         printf("\n");
2774         if (verbosity > VERBOSITY_SUMMARY_ONLY) {
2775                 printf("Reference files will be read from: %s\n", refdir);
2776 #ifdef PROGRAM
2777                 printf("Running tests on: %s\n", testprog);
2778 #endif
2779                 printf("Exercising: ");
2780                 fflush(stdout);
2781                 printf("%s\n", EXTRA_VERSION);
2782         } else {
2783                 printf("Running ");
2784                 fflush(stdout);
2785         }
2786
2787         /*
2788          * Run some or all of the individual tests.
2789          */
2790         saved_argv = argv;
2791         do {
2792                 argv = saved_argv;
2793                 do {
2794                         int test_num;
2795
2796                         test_num = get_test_set(test_set, limit, *argv, tests);
2797                         if (test_num < 0) {
2798                                 printf("*** INVALID Test %s\n", *argv);
2799                                 free(refdir_alloc);
2800                                 free(testprogdir);
2801                                 usage(progname);
2802                                 return (1);
2803                         }
2804                         for (i = 0; i < test_num; i++) {
2805                                 tests_run++;
2806                                 if (test_run(test_set[i], tmpdir)) {
2807                                         tests_failed++;
2808                                         if (until_failure)
2809                                                 goto finish;
2810                                 }
2811                         }
2812                         if (*argv != NULL)
2813                                 argv++;
2814                 } while (*argv != NULL);
2815         } while (until_failure);
2816
2817 finish:
2818         /* Must be freed after all tests run */
2819         free(tmp2);
2820         free(testprogdir);
2821         free(pwd);
2822
2823         /*
2824          * Report summary statistics.
2825          */
2826         if (verbosity > VERBOSITY_SUMMARY_ONLY) {
2827                 printf("\n");
2828                 printf("Totals:\n");
2829                 printf("  Tests run:         %8d\n", tests_run);
2830                 printf("  Tests failed:      %8d\n", tests_failed);
2831                 printf("  Assertions checked:%8d\n", assertions);
2832                 printf("  Assertions failed: %8d\n", failures);
2833                 printf("  Skips reported:    %8d\n", skips);
2834         }
2835         if (failures) {
2836                 printf("\n");
2837                 printf("Failing tests:\n");
2838                 for (i = 0; i < limit; ++i) {
2839                         if (tests[i].failures)
2840                                 printf("  %d: %s (%d failures)\n", i,
2841                                     tests[i].name, tests[i].failures);
2842                 }
2843                 printf("\n");
2844                 printf("Details for failing tests: %s\n", tmpdir);
2845                 printf("\n");
2846         } else {
2847                 if (verbosity == VERBOSITY_SUMMARY_ONLY)
2848                         printf("\n");
2849                 printf("%d tests passed, no failures\n", tests_run);
2850         }
2851
2852         free(refdir_alloc);
2853
2854         /* If the final tmpdir is empty, we can remove it. */
2855         /* This should be the usual case when all tests succeed. */
2856         assertChdir("..");
2857         rmdir(tmpdir);
2858
2859         return (tests_failed ? 1 : 0);
2860 }