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