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