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