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