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