]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/libarchive/test_utils/test_main.c
MFC r368207,368607:
[FreeBSD/stable/10.git] / contrib / libarchive / test_utils / 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 #ifdef HAVE_LINUX_FS_H
49 #include <linux/fs.h>
50 #endif
51 #include <limits.h>
52 #include <locale.h>
53 #ifdef HAVE_SIGNAL_H
54 #include <signal.h>
55 #endif
56 #include <stdarg.h>
57 #include <time.h>
58
59 #ifdef HAVE_SIGNAL_H
60 #endif
61 #ifdef HAVE_ACL_LIBACL_H
62 #include <acl/libacl.h>
63 #endif
64 #ifdef HAVE_SYS_TYPES_H
65 #include <sys/types.h>
66 #endif
67 #ifdef HAVE_SYS_ACL_H
68 #include <sys/acl.h>
69 #endif
70 #ifdef HAVE_SYS_EA_H
71 #include <sys/ea.h>
72 #endif
73 #ifdef HAVE_SYS_EXTATTR_H
74 #include <sys/extattr.h>
75 #endif
76 #if HAVE_SYS_XATTR_H
77 #include <sys/xattr.h>
78 #elif HAVE_ATTR_XATTR_H
79 #include <attr/xattr.h>
80 #endif
81 #ifdef HAVE_SYS_RICHACL_H
82 #include <sys/richacl.h>
83 #endif
84 #if HAVE_MEMBERSHIP_H
85 #include <membership.h>
86 #endif
87
88 /*
89  *
90  * Windows support routines
91  *
92  * Note: Configuration is a tricky issue.  Using HAVE_* feature macros
93  * in the test harness is dangerous because they cover up
94  * configuration errors.  The classic example of this is omitting a
95  * configure check.  If libarchive and libarchive_test both look for
96  * the same feature macro, such errors are hard to detect.  Platform
97  * macros (e.g., _WIN32 or __GNUC__) are a little better, but can
98  * easily lead to very messy code.  It's best to limit yourself
99  * to only the most generic programming techniques in the test harness
100  * and thus avoid conditionals altogether.  Where that's not possible,
101  * try to minimize conditionals by grouping platform-specific tests in
102  * one place (e.g., test_acl_freebsd) or by adding new assert()
103  * functions (e.g., assertMakeHardlink()) to cover up platform
104  * differences.  Platform-specific coding in libarchive_test is often
105  * a symptom that some capability is missing from libarchive itself.
106  */
107 #if defined(_WIN32) && !defined(__CYGWIN__)
108 #include <io.h>
109 #include <direct.h>
110 #include <windows.h>
111 #ifndef F_OK
112 #define F_OK (0)
113 #endif
114 #ifndef S_ISDIR
115 #define S_ISDIR(m)  ((m) & _S_IFDIR)
116 #endif
117 #ifndef S_ISREG
118 #define S_ISREG(m)  ((m) & _S_IFREG)
119 #endif
120 #if !defined(__BORLANDC__)
121 #define access _access
122 #undef chdir
123 #define chdir _chdir
124 #endif
125 #ifndef fileno
126 #define fileno _fileno
127 #endif
128 /*#define fstat _fstat64*/
129 #if !defined(__BORLANDC__)
130 #define getcwd _getcwd
131 #endif
132 #define lstat stat
133 /*#define lstat _stat64*/
134 /*#define stat _stat64*/
135 #define rmdir _rmdir
136 #if !defined(__BORLANDC__)
137 #define strdup _strdup
138 #define umask _umask
139 #endif
140 #define int64_t __int64
141 #endif
142
143 #if defined(HAVE__CrtSetReportMode)
144 # include <crtdbg.h>
145 #endif
146
147 mode_t umasked(mode_t expected_mode)
148 {
149         mode_t mode = umask(0);
150         umask(mode);
151         return expected_mode & ~mode;
152 }
153
154 /* Path to working directory for current test */
155 const char *testworkdir;
156 #ifdef PROGRAM
157 /* Pathname of exe to be tested. */
158 const char *testprogfile;
159 /* Name of exe to use in printf-formatted command strings. */
160 /* On Windows, this includes leading/trailing quotes. */
161 const char *testprog;
162 #endif
163
164 #if defined(_WIN32) && !defined(__CYGWIN__)
165 static void     *GetFunctionKernel32(const char *);
166 static int       my_CreateSymbolicLinkA(const char *, const char *, int);
167 static int       my_CreateHardLinkA(const char *, const char *);
168 static int       my_GetFileInformationByName(const char *,
169                      BY_HANDLE_FILE_INFORMATION *);
170
171 typedef struct _REPARSE_DATA_BUFFER {
172         ULONG   ReparseTag;
173         USHORT ReparseDataLength;
174         USHORT  Reserved;
175         union {
176                 struct {
177                         USHORT  SubstituteNameOffset;
178                         USHORT  SubstituteNameLength;
179                         USHORT  PrintNameOffset;
180                         USHORT  PrintNameLength;
181                         ULONG   Flags;
182                         WCHAR   PathBuffer[1];
183                 } SymbolicLinkReparseBuffer;
184                 struct {
185                         USHORT  SubstituteNameOffset;
186                         USHORT  SubstituteNameLength;
187                         USHORT  PrintNameOffset;
188                         USHORT  PrintNameLength;
189                         WCHAR   PathBuffer[1];
190                 } MountPointReparseBuffer;
191                 struct {
192                         UCHAR   DataBuffer[1];
193                 } GenericReparseBuffer;
194         } DUMMYUNIONNAME;
195 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
196
197 static void *
198 GetFunctionKernel32(const char *name)
199 {
200         static HINSTANCE lib;
201         static int set;
202         if (!set) {
203                 set = 1;
204                 lib = LoadLibrary("kernel32.dll");
205         }
206         if (lib == NULL) {
207                 fprintf(stderr, "Can't load kernel32.dll?!\n");
208                 exit(1);
209         }
210         return (void *)GetProcAddress(lib, name);
211 }
212
213 static int
214 my_CreateSymbolicLinkA(const char *linkname, const char *target,
215     int targetIsDir)
216 {
217         static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, DWORD);
218         DWORD attrs;
219         static int set;
220         int ret, tmpflags, llen, tlen;
221         int flags = 0;
222         char *src, *tgt, *p;
223         if (!set) {
224                 set = 1;
225                 f = GetFunctionKernel32("CreateSymbolicLinkA");
226         }
227         if (f == NULL)
228                 return (0);
229
230         tlen = strlen(target);
231         llen = strlen(linkname);
232
233         if (tlen == 0 || llen == 0)
234                 return (0);
235
236         tgt = malloc((tlen + 1) * sizeof(char));
237         if (tgt == NULL)
238                 return (0);
239         src = malloc((llen + 1) * sizeof(char));
240         if (src == NULL) {
241                 free(tgt);
242                 return (0);
243         }
244
245         /*
246          * Translate slashes to backslashes
247          */
248         p = src;
249         while(*linkname != '\0') {
250                 if (*linkname == '/')
251                         *p = '\\';
252                 else
253                         *p = *linkname;
254                 linkname++;
255                 p++;
256         }
257         *p = '\0';
258
259         p = tgt;
260         while(*target != '\0') {
261                 if (*target == '/')
262                         *p = '\\';
263                 else
264                         *p = *target;
265                 target++;
266                 p++;
267         }
268         *p = '\0';
269
270         /*
271          * Each test has to specify if a file or a directory symlink
272          * should be created.
273          */
274         if (targetIsDir) {
275 #if defined(SYMBOLIC_LINK_FLAG_DIRECTORY)
276                 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
277 #else
278                 flags |= 0x1;
279 #endif
280         }
281
282 #if defined(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)
283         tmpflags = flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
284 #else
285         tmpflags = flags | 0x2;
286 #endif
287         /*
288          * Windows won't overwrite existing links
289          */
290         attrs = GetFileAttributesA(linkname);
291         if (attrs != INVALID_FILE_ATTRIBUTES) {
292                 if (attrs & FILE_ATTRIBUTE_DIRECTORY)
293                         RemoveDirectoryA(linkname);
294                 else
295                         DeleteFileA(linkname);
296         }
297
298         ret = (*f)(src, tgt, tmpflags);
299         /*
300          * Prior to Windows 10 the SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
301          * is not understood
302          */
303         if (!ret)
304                 ret = (*f)(src, tgt, flags);
305
306         free(src);
307         free(tgt);
308         return (ret);
309 }
310
311 static int
312 my_CreateHardLinkA(const char *linkname, const char *target)
313 {
314         static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, LPSECURITY_ATTRIBUTES);
315         static int set;
316         if (!set) {
317                 set = 1;
318                 f = GetFunctionKernel32("CreateHardLinkA");
319         }
320         return f == NULL ? 0 : (*f)(linkname, target, NULL);
321 }
322
323 static int
324 my_GetFileInformationByName(const char *path, BY_HANDLE_FILE_INFORMATION *bhfi)
325 {
326         HANDLE h;
327         int r;
328
329         memset(bhfi, 0, sizeof(*bhfi));
330         h = CreateFile(path, FILE_READ_ATTRIBUTES, 0, NULL,
331                 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
332         if (h == INVALID_HANDLE_VALUE)
333                 return (0);
334         r = GetFileInformationByHandle(h, bhfi);
335         CloseHandle(h);
336         return (r);
337 }
338 #endif
339
340 #if defined(HAVE__CrtSetReportMode) && !defined(__WATCOMC__)
341 static void
342 invalid_parameter_handler(const wchar_t * expression,
343     const wchar_t * function, const wchar_t * file,
344     unsigned int line, uintptr_t pReserved)
345 {
346         /* nop */
347         // Silence unused-parameter compiler warnings.
348         (void)expression;
349         (void)function;
350         (void)file;
351         (void)line;
352         (void)pReserved;
353 }
354 #endif
355
356 /*
357  *
358  * OPTIONS FLAGS
359  *
360  */
361
362 /* Enable core dump on failure. */
363 static int dump_on_failure = 0;
364 /* Default is to remove temp dirs and log data for successful tests. */
365 static int keep_temp_files = 0;
366 /* Default is to run the specified tests once and report errors. */
367 static int until_failure = 0;
368 /* Default is to just report pass/fail for each test. */
369 static int verbosity = 0;
370 #define VERBOSITY_SUMMARY_ONLY -1 /* -q */
371 #define VERBOSITY_PASSFAIL 0   /* Default */
372 #define VERBOSITY_LIGHT_REPORT 1 /* -v */
373 #define VERBOSITY_FULL 2 /* -vv */
374 /* A few places generate even more output for verbosity > VERBOSITY_FULL,
375  * mostly for debugging the test harness itself. */
376 /* Cumulative count of assertion failures. */
377 static int failures = 0;
378 /* Cumulative count of reported skips. */
379 static int skips = 0;
380 /* Cumulative count of assertions checked. */
381 static int assertions = 0;
382
383 /* Directory where uuencoded reference files can be found. */
384 static const char *refdir;
385
386 /*
387  * Report log information selectively to console and/or disk log.
388  */
389 static int log_console = 0;
390 static FILE *logfile;
391 static void __LA_PRINTFLIKE(1, 0)
392 vlogprintf(const char *fmt, va_list ap)
393 {
394 #ifdef va_copy
395         va_list lfap;
396         va_copy(lfap, ap);
397 #endif
398         if (log_console)
399                 vfprintf(stdout, fmt, ap);
400         if (logfile != NULL)
401 #ifdef va_copy
402                 vfprintf(logfile, fmt, lfap);
403         va_end(lfap);
404 #else
405                 vfprintf(logfile, fmt, ap);
406 #endif
407 }
408
409 static void __LA_PRINTFLIKE(1, 2)
410 logprintf(const char *fmt, ...)
411 {
412         va_list ap;
413         va_start(ap, fmt);
414         vlogprintf(fmt, ap);
415         va_end(ap);
416 }
417
418 /* Set up a message to display only if next assertion fails. */
419 static char msgbuff[4096];
420 static const char *msg, *nextmsg;
421 void
422 failure(const char *fmt, ...)
423 {
424         va_list ap;
425         if (fmt == NULL) {
426                 nextmsg = NULL;
427         } else {
428                 va_start(ap, fmt);
429                 vsprintf(msgbuff, fmt, ap);
430                 va_end(ap);
431                 nextmsg = msgbuff;
432         }
433 }
434
435 /*
436  * Copy arguments into file-local variables.
437  * This was added to permit vararg assert() functions without needing
438  * variadic wrapper macros.  Turns out that the vararg capability is almost
439  * never used, so almost all of the vararg assertions can be simplified
440  * by removing the vararg capability and reworking the wrapper macro to
441  * pass __FILE__, __LINE__ directly into the function instead of using
442  * this hook.  I suspect this machinery is used so rarely that we
443  * would be better off just removing it entirely.  That would simplify
444  * the code here noticeably.
445  */
446 static const char *skipping_filename;
447 static int skipping_line;
448 void skipping_setup(const char *filename, int line)
449 {
450         skipping_filename = filename;
451         skipping_line = line;
452 }
453
454 /* Called at the beginning of each assert() function. */
455 static void
456 assertion_count(const char *file, int line)
457 {
458         (void)file; /* UNUSED */
459         (void)line; /* UNUSED */
460         ++assertions;
461         /* Proper handling of "failure()" message. */
462         msg = nextmsg;
463         nextmsg = NULL;
464         /* Uncomment to print file:line after every assertion.
465          * Verbose, but occasionally useful in tracking down crashes. */
466         /* printf("Checked %s:%d\n", file, line); */
467 }
468
469 /*
470  * For each test source file, we remember how many times each
471  * assertion was reported.  Cleared before each new test,
472  * used by test_summarize().
473  */
474 static struct line {
475         int count;
476         int skip;
477 }  failed_lines[10000];
478 const char *failed_filename;
479
480 /* Count this failure, setup up log destination and handle initial report. */
481 static void __LA_PRINTFLIKE(3, 4)
482 failure_start(const char *filename, int line, const char *fmt, ...)
483 {
484         va_list ap;
485
486         /* Record another failure for this line. */
487         ++failures;
488         failed_filename = filename;
489         failed_lines[line].count++;
490
491         /* Determine whether to log header to console. */
492         switch (verbosity) {
493         case VERBOSITY_LIGHT_REPORT:
494                 log_console = (failed_lines[line].count < 2);
495                 break;
496         default:
497                 log_console = (verbosity >= VERBOSITY_FULL);
498         }
499
500         /* Log file:line header for this failure */
501         va_start(ap, fmt);
502 #if _MSC_VER
503         logprintf("%s(%d): ", filename, line);
504 #else
505         logprintf("%s:%d: ", filename, line);
506 #endif
507         vlogprintf(fmt, ap);
508         va_end(ap);
509         logprintf("\n");
510
511         if (msg != NULL && msg[0] != '\0') {
512                 logprintf("   Description: %s\n", msg);
513                 msg = NULL;
514         }
515
516         /* Determine whether to log details to console. */
517         if (verbosity == VERBOSITY_LIGHT_REPORT)
518                 log_console = 0;
519 }
520
521 /* Complete reporting of failed tests. */
522 /*
523  * The 'extra' hook here is used by libarchive to include libarchive
524  * error messages with assertion failures.  It could also be used
525  * to add strerror() output, for example.  Just define the EXTRA_DUMP()
526  * macro appropriately.
527  */
528 static void
529 failure_finish(void *extra)
530 {
531         (void)extra; /* UNUSED (maybe) */
532 #ifdef EXTRA_DUMP
533         if (extra != NULL) {
534                 logprintf("    errno: %d\n", EXTRA_ERRNO(extra));
535                 logprintf("   detail: %s\n", EXTRA_DUMP(extra));
536         }
537 #endif
538
539         if (dump_on_failure) {
540                 fprintf(stderr,
541                     " *** forcing core dump so failure can be debugged ***\n");
542                 abort();
543         }
544 }
545
546 /* Inform user that we're skipping some checks. */
547 void
548 test_skipping(const char *fmt, ...)
549 {
550         char buff[1024];
551         va_list ap;
552
553         va_start(ap, fmt);
554         vsprintf(buff, fmt, ap);
555         va_end(ap);
556         /* Use failure() message if set. */
557         msg = nextmsg;
558         nextmsg = NULL;
559         /* failure_start() isn't quite right, but is awfully convenient. */
560         failure_start(skipping_filename, skipping_line, "SKIPPING: %s", buff);
561         --failures; /* Undo failures++ in failure_start() */
562         /* Don't failure_finish() here. */
563         /* Mark as skip, so doesn't count as failed test. */
564         failed_lines[skipping_line].skip = 1;
565         ++skips;
566 }
567
568 /*
569  *
570  * ASSERTIONS
571  *
572  */
573
574 /* Generic assert() just displays the failed condition. */
575 int
576 assertion_assert(const char *file, int line, int value,
577     const char *condition, void *extra)
578 {
579         assertion_count(file, line);
580         if (!value) {
581                 failure_start(file, line, "Assertion failed: %s", condition);
582                 failure_finish(extra);
583         }
584         return (value);
585 }
586
587 /* chdir() and report any errors */
588 int
589 assertion_chdir(const char *file, int line, const char *pathname)
590 {
591         assertion_count(file, line);
592         if (chdir(pathname) == 0)
593                 return (1);
594         failure_start(file, line, "chdir(\"%s\")", pathname);
595         failure_finish(NULL);
596         return (0);
597
598 }
599
600 /* change file/directory permissions and errors if it fails */
601 int
602 assertion_chmod(const char *file, int line, const char *pathname, int mode)
603 {
604         assertion_count(file, line);
605         if (chmod(pathname, mode) == 0)
606                 return (1);
607         failure_start(file, line, "chmod(\"%s\", %4.o)", pathname, mode);
608         failure_finish(NULL);
609         return (0);
610
611 }
612
613 /* Verify two integers are equal. */
614 int
615 assertion_equal_int(const char *file, int line,
616     long long v1, const char *e1, long long v2, const char *e2, void *extra)
617 {
618         assertion_count(file, line);
619         if (v1 == v2)
620                 return (1);
621         failure_start(file, line, "%s != %s", e1, e2);
622         logprintf("      %s=%lld (0x%llx, 0%llo)\n", e1, v1, v1, v1);
623         logprintf("      %s=%lld (0x%llx, 0%llo)\n", e2, v2, v2, v2);
624         failure_finish(extra);
625         return (0);
626 }
627
628 /*
629  * Utility to convert a single UTF-8 sequence.
630  */
631 static int
632 _utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
633 {
634         static const char utf8_count[256] = {
635                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
636                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
637                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
638                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
639                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
640                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
641                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
642                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
643                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
644                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
645                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
646                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
647                  0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
648                  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
649                  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
650                  4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
651         };
652         int ch;
653         int cnt;
654         uint32_t wc;
655
656         *pwc = 0;
657
658         /* Sanity check. */
659         if (n == 0)
660                 return (0);
661         /*
662          * Decode 1-4 bytes depending on the value of the first byte.
663          */
664         ch = (unsigned char)*s;
665         if (ch == 0)
666                 return (0); /* Standard:  return 0 for end-of-string. */
667         cnt = utf8_count[ch];
668
669         /* Invalid sequence or there are not plenty bytes. */
670         if (n < (size_t)cnt)
671                 return (-1);
672
673         /* Make a Unicode code point from a single UTF-8 sequence. */
674         switch (cnt) {
675         case 1: /* 1 byte sequence. */
676                 *pwc = ch & 0x7f;
677                 return (cnt);
678         case 2: /* 2 bytes sequence. */
679                 if ((s[1] & 0xc0) != 0x80) return (-1);
680                 *pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
681                 return (cnt);
682         case 3: /* 3 bytes sequence. */
683                 if ((s[1] & 0xc0) != 0x80) return (-1);
684                 if ((s[2] & 0xc0) != 0x80) return (-1);
685                 wc = ((ch & 0x0f) << 12)
686                     | ((s[1] & 0x3f) << 6)
687                     | (s[2] & 0x3f);
688                 if (wc < 0x800)
689                         return (-1);/* Overlong sequence. */
690                 break;
691         case 4: /* 4 bytes sequence. */
692                 if (n < 4)
693                         return (-1);
694                 if ((s[1] & 0xc0) != 0x80) return (-1);
695                 if ((s[2] & 0xc0) != 0x80) return (-1);
696                 if ((s[3] & 0xc0) != 0x80) return (-1);
697                 wc = ((ch & 0x07) << 18)
698                     | ((s[1] & 0x3f) << 12)
699                     | ((s[2] & 0x3f) << 6)
700                     | (s[3] & 0x3f);
701                 if (wc < 0x10000)
702                         return (-1);/* Overlong sequence. */
703                 break;
704         default:
705                 return (-1);
706         }
707
708         /* The code point larger than 0x10FFFF is not legal
709          * Unicode values. */
710         if (wc > 0x10FFFF)
711                 return (-1);
712         /* Correctly gets a Unicode, returns used bytes. */
713         *pwc = wc;
714         return (cnt);
715 }
716
717 static void strdump(const char *e, const char *p, int ewidth, int utf8)
718 {
719         const char *q = p;
720
721         logprintf("      %*s = ", ewidth, e);
722         if (p == NULL) {
723                 logprintf("NULL\n");
724                 return;
725         }
726         logprintf("\"");
727         while (*p != '\0') {
728                 unsigned int c = 0xff & *p++;
729                 switch (c) {
730                 case '\a': logprintf("\\a"); break;
731                 case '\b': logprintf("\\b"); break;
732                 case '\n': logprintf("\\n"); break;
733                 case '\r': logprintf("\\r"); break;
734                 default:
735                         if (c >= 32 && c < 127)
736                                 logprintf("%c", c);
737                         else
738                                 logprintf("\\x%02X", c);
739                 }
740         }
741         logprintf("\"");
742         logprintf(" (length %d)", q == NULL ? -1 : (int)strlen(q));
743
744         /*
745          * If the current string is UTF-8, dump its code points.
746          */
747         if (utf8) {
748                 size_t len;
749                 uint32_t uc;
750                 int n;
751                 int cnt = 0;
752
753                 p = q;
754                 len = strlen(p);
755                 logprintf(" [");
756                 while ((n = _utf8_to_unicode(&uc, p, len)) > 0) {
757                         if (p != q)
758                                 logprintf(" ");
759                         logprintf("%04X", uc);
760                         p += n;
761                         len -= n;
762                         cnt++;
763                 }
764                 logprintf("]");
765                 logprintf(" (count %d", cnt);
766                 if (n < 0) {
767                         logprintf(",unknown %zu bytes", len);
768                 }
769                 logprintf(")");
770
771         }
772         logprintf("\n");
773 }
774
775 /* Verify two strings are equal, dump them if not. */
776 int
777 assertion_equal_string(const char *file, int line,
778     const char *v1, const char *e1,
779     const char *v2, const char *e2,
780     void *extra, int utf8)
781 {
782         int l1, l2;
783
784         assertion_count(file, line);
785         if (v1 == v2 || (v1 != NULL && v2 != NULL && strcmp(v1, v2) == 0))
786                 return (1);
787         failure_start(file, line, "%s != %s", e1, e2);
788         l1 = (int)strlen(e1);
789         l2 = (int)strlen(e2);
790         if (l1 < l2)
791                 l1 = l2;
792         strdump(e1, v1, l1, utf8);
793         strdump(e2, v2, l1, utf8);
794         failure_finish(extra);
795         return (0);
796 }
797
798 static void
799 wcsdump(const char *e, const wchar_t *w)
800 {
801         logprintf("      %s = ", e);
802         if (w == NULL) {
803                 logprintf("(null)");
804                 return;
805         }
806         logprintf("\"");
807         while (*w != L'\0') {
808                 unsigned int c = *w++;
809                 if (c >= 32 && c < 127)
810                         logprintf("%c", c);
811                 else if (c < 256)
812                         logprintf("\\x%02X", c);
813                 else if (c < 0x10000)
814                         logprintf("\\u%04X", c);
815                 else
816                         logprintf("\\U%08X", c);
817         }
818         logprintf("\"\n");
819 }
820
821 #ifndef HAVE_WCSCMP
822 static int
823 wcscmp(const wchar_t *s1, const wchar_t *s2)
824 {
825
826         while (*s1 == *s2++) {
827                 if (*s1++ == L'\0')
828                         return 0;
829         }
830         if (*s1 > *--s2)
831                 return 1;
832         else
833                 return -1;
834 }
835 #endif
836
837 /* Verify that two wide strings are equal, dump them if not. */
838 int
839 assertion_equal_wstring(const char *file, int line,
840     const wchar_t *v1, const char *e1,
841     const wchar_t *v2, const char *e2,
842     void *extra)
843 {
844         assertion_count(file, line);
845         if (v1 == v2)
846                 return (1);
847         if (v1 != NULL && v2 != NULL && wcscmp(v1, v2) == 0)
848                 return (1);
849         failure_start(file, line, "%s != %s", e1, e2);
850         wcsdump(e1, v1);
851         wcsdump(e2, v2);
852         failure_finish(extra);
853         return (0);
854 }
855
856 /*
857  * Pretty standard hexdump routine.  As a bonus, if ref != NULL, then
858  * any bytes in p that differ from ref will be highlighted with '_'
859  * before and after the hex value.
860  */
861 static void
862 hexdump(const char *p, const char *ref, size_t l, size_t offset)
863 {
864         size_t i, j;
865         char sep;
866
867         if (p == NULL) {
868                 logprintf("(null)\n");
869                 return;
870         }
871         for(i=0; i < l; i+=16) {
872                 logprintf("%04x", (unsigned)(i + offset));
873                 sep = ' ';
874                 for (j = 0; j < 16 && i + j < l; j++) {
875                         if (ref != NULL && p[i + j] != ref[i + j])
876                                 sep = '_';
877                         logprintf("%c%02x", sep, 0xff & (int)p[i+j]);
878                         if (ref != NULL && p[i + j] == ref[i + j])
879                                 sep = ' ';
880                 }
881                 for (; j < 16; j++) {
882                         logprintf("%c  ", sep);
883                         sep = ' ';
884                 }
885                 logprintf("%c", sep);
886                 for (j=0; j < 16 && i + j < l; j++) {
887                         int c = p[i + j];
888                         if (c >= ' ' && c <= 126)
889                                 logprintf("%c", c);
890                         else
891                                 logprintf(".");
892                 }
893                 logprintf("\n");
894         }
895 }
896
897 /* Verify that two blocks of memory are the same, display the first
898  * block of differences if they're not. */
899 int
900 assertion_equal_mem(const char *file, int line,
901     const void *_v1, const char *e1,
902     const void *_v2, const char *e2,
903     size_t l, const char *ld, void *extra)
904 {
905         const char *v1 = (const char *)_v1;
906         const char *v2 = (const char *)_v2;
907         size_t offset;
908
909         assertion_count(file, line);
910         if (v1 == v2 || (v1 != NULL && v2 != NULL && memcmp(v1, v2, l) == 0))
911                 return (1);
912         if (v1 == NULL || v2 == NULL)
913                 return (0);
914
915         failure_start(file, line, "%s != %s", e1, e2);
916         logprintf("      size %s = %d\n", ld, (int)l);
917         /* Dump 48 bytes (3 lines) so that the first difference is
918          * in the second line. */
919         offset = 0;
920         while (l > 64 && memcmp(v1, v2, 32) == 0) {
921                 /* Two lines agree, so step forward one line. */
922                 v1 += 16;
923                 v2 += 16;
924                 l -= 16;
925                 offset += 16;
926         }
927         logprintf("      Dump of %s\n", e1);
928         hexdump(v1, v2, l < 128 ? l : 128, offset);
929         logprintf("      Dump of %s\n", e2);
930         hexdump(v2, v1, l < 128 ? l : 128, offset);
931         logprintf("\n");
932         failure_finish(extra);
933         return (0);
934 }
935
936 /* Verify that a block of memory is filled with the specified byte. */
937 int
938 assertion_memory_filled_with(const char *file, int line,
939     const void *_v1, const char *vd,
940     size_t l, const char *ld,
941     char b, const char *bd, void *extra)
942 {
943         const char *v1 = (const char *)_v1;
944         size_t c = 0;
945         size_t i;
946         (void)ld; /* UNUSED */
947
948         assertion_count(file, line);
949
950         for (i = 0; i < l; ++i) {
951                 if (v1[i] == b) {
952                         ++c;
953                 }
954         }
955         if (c == l)
956                 return (1);
957
958         failure_start(file, line, "%s (size %d) not filled with %s", vd, (int)l, bd);
959         logprintf("   Only %d bytes were correct\n", (int)c);
960         failure_finish(extra);
961         return (0);
962 }
963
964 /* Verify that the named file exists and is empty. */
965 int
966 assertion_empty_file(const char *filename, int line, const char *f1)
967 {
968         char buff[1024];
969         struct stat st;
970         ssize_t s;
971         FILE *f;
972
973         assertion_count(filename, line);
974
975         if (stat(f1, &st) != 0) {
976                 failure_start(filename, line, "Stat failed: %s", f1);
977                 failure_finish(NULL);
978                 return (0);
979         }
980         if (st.st_size == 0)
981                 return (1);
982
983         failure_start(filename, line, "File should be empty: %s", f1);
984         logprintf("    File size: %d\n", (int)st.st_size);
985         logprintf("    Contents:\n");
986         f = fopen(f1, "rb");
987         if (f == NULL) {
988                 logprintf("    Unable to open %s\n", f1);
989         } else {
990                 s = ((off_t)sizeof(buff) < st.st_size) ?
991                     (ssize_t)sizeof(buff) : (ssize_t)st.st_size;
992                 s = fread(buff, 1, s, f);
993                 hexdump(buff, NULL, s, 0);
994                 fclose(f);
995         }
996         failure_finish(NULL);
997         return (0);
998 }
999
1000 /* Verify that the named file exists and is not empty. */
1001 int
1002 assertion_non_empty_file(const char *filename, int line, const char *f1)
1003 {
1004         struct stat st;
1005
1006         assertion_count(filename, line);
1007
1008         if (stat(f1, &st) != 0) {
1009                 failure_start(filename, line, "Stat failed: %s", f1);
1010                 failure_finish(NULL);
1011                 return (0);
1012         }
1013         if (st.st_size == 0) {
1014                 failure_start(filename, line, "File empty: %s", f1);
1015                 failure_finish(NULL);
1016                 return (0);
1017         }
1018         return (1);
1019 }
1020
1021 /* Verify that two files have the same contents. */
1022 /* TODO: hexdump the first bytes that actually differ. */
1023 int
1024 assertion_equal_file(const char *filename, int line, const char *fn1, const char *fn2)
1025 {
1026         char buff1[1024];
1027         char buff2[1024];
1028         FILE *f1, *f2;
1029         int n1, n2;
1030
1031         assertion_count(filename, line);
1032
1033         f1 = fopen(fn1, "rb");
1034         f2 = fopen(fn2, "rb");
1035         if (f1 == NULL || f2 == NULL) {
1036                 if (f1) fclose(f1);
1037                 if (f2) fclose(f2);
1038                 return (0);
1039         }
1040         for (;;) {
1041                 n1 = (int)fread(buff1, 1, sizeof(buff1), f1);
1042                 n2 = (int)fread(buff2, 1, sizeof(buff2), f2);
1043                 if (n1 != n2)
1044                         break;
1045                 if (n1 == 0 && n2 == 0) {
1046                         fclose(f1);
1047                         fclose(f2);
1048                         return (1);
1049                 }
1050                 if (memcmp(buff1, buff2, n1) != 0)
1051                         break;
1052         }
1053         fclose(f1);
1054         fclose(f2);
1055         failure_start(filename, line, "Files not identical");
1056         logprintf("  file1=\"%s\"\n", fn1);
1057         logprintf("  file2=\"%s\"\n", fn2);
1058         failure_finish(NULL);
1059         return (0);
1060 }
1061
1062 /* Verify that the named file does exist. */
1063 int
1064 assertion_file_exists(const char *filename, int line, const char *f)
1065 {
1066         assertion_count(filename, line);
1067
1068 #if defined(_WIN32) && !defined(__CYGWIN__)
1069         if (!_access(f, 0))
1070                 return (1);
1071 #else
1072         if (!access(f, F_OK))
1073                 return (1);
1074 #endif
1075         failure_start(filename, line, "File should exist: %s", f);
1076         failure_finish(NULL);
1077         return (0);
1078 }
1079
1080 /* Verify that the named file doesn't exist. */
1081 int
1082 assertion_file_not_exists(const char *filename, int line, const char *f)
1083 {
1084         assertion_count(filename, line);
1085
1086 #if defined(_WIN32) && !defined(__CYGWIN__)
1087         if (_access(f, 0))
1088                 return (1);
1089 #else
1090         if (access(f, F_OK))
1091                 return (1);
1092 #endif
1093         failure_start(filename, line, "File should not exist: %s", f);
1094         failure_finish(NULL);
1095         return (0);
1096 }
1097
1098 /* Compare the contents of a file to a block of memory. */
1099 int
1100 assertion_file_contents(const char *filename, int line, const void *buff, int s, const char *fn)
1101 {
1102         char *contents;
1103         FILE *f;
1104         int n;
1105
1106         assertion_count(filename, line);
1107
1108         f = fopen(fn, "rb");
1109         if (f == NULL) {
1110                 failure_start(filename, line,
1111                     "File should exist: %s", fn);
1112                 failure_finish(NULL);
1113                 return (0);
1114         }
1115         contents = malloc(s * 2);
1116         n = (int)fread(contents, 1, s * 2, f);
1117         fclose(f);
1118         if (n == s && memcmp(buff, contents, s) == 0) {
1119                 free(contents);
1120                 return (1);
1121         }
1122         failure_start(filename, line, "File contents don't match");
1123         logprintf("  file=\"%s\"\n", fn);
1124         if (n > 0)
1125                 hexdump(contents, buff, n > 512 ? 512 : n, 0);
1126         else {
1127                 logprintf("  File empty, contents should be:\n");
1128                 hexdump(buff, NULL, s > 512 ? 512 : s, 0);
1129         }
1130         failure_finish(NULL);
1131         free(contents);
1132         return (0);
1133 }
1134
1135 /* Check the contents of a text file, being tolerant of line endings. */
1136 int
1137 assertion_text_file_contents(const char *filename, int line, const char *buff, const char *fn)
1138 {
1139         char *contents;
1140         const char *btxt, *ftxt;
1141         FILE *f;
1142         int n, s;
1143
1144         assertion_count(filename, line);
1145         f = fopen(fn, "r");
1146         if (f == NULL) {
1147                 failure_start(filename, line,
1148                     "File doesn't exist: %s", fn);
1149                 failure_finish(NULL);
1150                 return (0);
1151         }
1152         s = (int)strlen(buff);
1153         contents = malloc(s * 2 + 128);
1154         n = (int)fread(contents, 1, s * 2 + 128 - 1, f);
1155         if (n >= 0)
1156                 contents[n] = '\0';
1157         fclose(f);
1158         /* Compare texts. */
1159         btxt = buff;
1160         ftxt = (const char *)contents;
1161         while (*btxt != '\0' && *ftxt != '\0') {
1162                 if (*btxt == *ftxt) {
1163                         ++btxt;
1164                         ++ftxt;
1165                         continue;
1166                 }
1167                 if (btxt[0] == '\n' && ftxt[0] == '\r' && ftxt[1] == '\n') {
1168                         /* Pass over different new line characters. */
1169                         ++btxt;
1170                         ftxt += 2;
1171                         continue;
1172                 }
1173                 break;
1174         }
1175         if (*btxt == '\0' && *ftxt == '\0') {
1176                 free(contents);
1177                 return (1);
1178         }
1179         failure_start(filename, line, "Contents don't match");
1180         logprintf("  file=\"%s\"\n", fn);
1181         if (n > 0) {
1182                 hexdump(contents, buff, n, 0);
1183                 logprintf("  expected\n");
1184                 hexdump(buff, contents, s, 0);
1185         } else {
1186                 logprintf("  File empty, contents should be:\n");
1187                 hexdump(buff, NULL, s, 0);
1188         }
1189         failure_finish(NULL);
1190         free(contents);
1191         return (0);
1192 }
1193
1194 /* Verify that a text file contains the specified lines, regardless of order */
1195 /* This could be more efficient if we sorted both sets of lines, etc, but
1196  * since this is used only for testing and only ever deals with a dozen or so
1197  * lines at a time, this relatively crude approach is just fine. */
1198 int
1199 assertion_file_contains_lines_any_order(const char *file, int line,
1200     const char *pathname, const char *lines[])
1201 {
1202         char *buff;
1203         size_t buff_size;
1204         size_t expected_count, actual_count, i, j;
1205         char **expected = NULL;
1206         char *p, **actual = NULL;
1207         char c;
1208         int expected_failure = 0, actual_failure = 0;
1209
1210         assertion_count(file, line);
1211
1212         buff = slurpfile(&buff_size, "%s", pathname);
1213         if (buff == NULL) {
1214                 failure_start(pathname, line, "Can't read file: %s", pathname);
1215                 failure_finish(NULL);
1216                 return (0);
1217         }
1218
1219         /* Make a copy of the provided lines and count up the expected
1220          * file size. */
1221         for (i = 0; lines[i] != NULL; ++i) {
1222         }
1223         expected_count = i;
1224         if (expected_count) {
1225                 expected = malloc(sizeof(char *) * expected_count);
1226                 if (expected == NULL) {
1227                         failure_start(pathname, line, "Can't allocate memory");
1228                         failure_finish(NULL);
1229                         free(expected);
1230                         free(buff);
1231                         return (0);
1232                 }
1233                 for (i = 0; lines[i] != NULL; ++i) {
1234                         expected[i] = strdup(lines[i]);
1235                 }
1236         }
1237
1238         /* Break the file into lines */
1239         actual_count = 0;
1240         for (c = '\0', p = buff; p < buff + buff_size; ++p) {
1241                 if (*p == '\x0d' || *p == '\x0a')
1242                         *p = '\0';
1243                 if (c == '\0' && *p != '\0')
1244                         ++actual_count;
1245                 c = *p;
1246         }
1247         if (actual_count) {
1248                 actual = calloc(sizeof(char *), actual_count);
1249                 if (actual == NULL) {
1250                         failure_start(pathname, line, "Can't allocate memory");
1251                         failure_finish(NULL);
1252                         free(expected);
1253                         free(buff);
1254                         return (0);
1255                 }
1256                 for (j = 0, p = buff; p < buff + buff_size;
1257                     p += 1 + strlen(p)) {
1258                         if (*p != '\0') {
1259                                 actual[j] = p;
1260                                 ++j;
1261                         }
1262                 }
1263         }
1264
1265         /* Erase matching lines from both lists */
1266         for (i = 0; i < expected_count; ++i) {
1267                 if (expected[i] == NULL)
1268                         continue;
1269                 for (j = 0; j < actual_count; ++j) {
1270                         if (actual[j] == NULL)
1271                                 continue;
1272                         if (strcmp(expected[i], actual[j]) == 0) {
1273                                 free(expected[i]);
1274                                 expected[i] = NULL;
1275                                 actual[j] = NULL;
1276                                 break;
1277                         }
1278                 }
1279         }
1280
1281         /* If there's anything left, it's a failure */
1282         for (i = 0; i < expected_count; ++i) {
1283                 if (expected[i] != NULL)
1284                         ++expected_failure;
1285         }
1286         for (j = 0; j < actual_count; ++j) {
1287                 if (actual[j] != NULL)
1288                         ++actual_failure;
1289         }
1290         if (expected_failure == 0 && actual_failure == 0) {
1291                 free(buff);
1292                 free(expected);
1293                 free(actual);
1294                 return (1);
1295         }
1296         failure_start(file, line, "File doesn't match: %s", pathname);
1297         for (i = 0; i < expected_count; ++i) {
1298                 if (expected[i] != NULL) {
1299                         logprintf("  Expected but not present: %s\n", expected[i]);
1300                         free(expected[i]);
1301                 }
1302         }
1303         for (j = 0; j < actual_count; ++j) {
1304                 if (actual[j] != NULL)
1305                         logprintf("  Present but not expected: %s\n", actual[j]);
1306         }
1307         failure_finish(NULL);
1308         free(buff);
1309         free(expected);
1310         free(actual);
1311         return (0);
1312 }
1313
1314 /* Verify that a text file does not contains the specified strings */
1315 int
1316 assertion_file_contains_no_invalid_strings(const char *file, int line,
1317     const char *pathname, const char *strings[])
1318 {
1319         char *buff;
1320         int i;
1321
1322         buff = slurpfile(NULL, "%s", pathname);
1323         if (buff == NULL) {
1324                 failure_start(file, line, "Can't read file: %s", pathname);
1325                 failure_finish(NULL);
1326                 return (0);
1327         }
1328
1329         for (i = 0; strings[i] != NULL; ++i) {
1330                 if (strstr(buff, strings[i]) != NULL) {
1331                         failure_start(file, line, "Invalid string in %s: %s", pathname,
1332                             strings[i]);
1333                         failure_finish(NULL);
1334                         free(buff);
1335                         return(0);
1336                 }
1337         }
1338
1339         free(buff);
1340         return (0);
1341 }
1342
1343 /* Test that two paths point to the same file. */
1344 /* As a side-effect, asserts that both files exist. */
1345 static int
1346 is_hardlink(const char *file, int line,
1347     const char *path1, const char *path2)
1348 {
1349 #if defined(_WIN32) && !defined(__CYGWIN__)
1350         BY_HANDLE_FILE_INFORMATION bhfi1, bhfi2;
1351         int r;
1352
1353         assertion_count(file, line);
1354         r = my_GetFileInformationByName(path1, &bhfi1);
1355         if (r == 0) {
1356                 failure_start(file, line, "File %s can't be inspected?", path1);
1357                 failure_finish(NULL);
1358                 return (0);
1359         }
1360         r = my_GetFileInformationByName(path2, &bhfi2);
1361         if (r == 0) {
1362                 failure_start(file, line, "File %s can't be inspected?", path2);
1363                 failure_finish(NULL);
1364                 return (0);
1365         }
1366         return (bhfi1.dwVolumeSerialNumber == bhfi2.dwVolumeSerialNumber
1367                 && bhfi1.nFileIndexHigh == bhfi2.nFileIndexHigh
1368                 && bhfi1.nFileIndexLow == bhfi2.nFileIndexLow);
1369 #else
1370         struct stat st1, st2;
1371         int r;
1372
1373         assertion_count(file, line);
1374         r = lstat(path1, &st1);
1375         if (r != 0) {
1376                 failure_start(file, line, "File should exist: %s", path1);
1377                 failure_finish(NULL);
1378                 return (0);
1379         }
1380         r = lstat(path2, &st2);
1381         if (r != 0) {
1382                 failure_start(file, line, "File should exist: %s", path2);
1383                 failure_finish(NULL);
1384                 return (0);
1385         }
1386         return (st1.st_ino == st2.st_ino && st1.st_dev == st2.st_dev);
1387 #endif
1388 }
1389
1390 int
1391 assertion_is_hardlink(const char *file, int line,
1392     const char *path1, const char *path2)
1393 {
1394         if (is_hardlink(file, line, path1, path2))
1395                 return (1);
1396         failure_start(file, line,
1397             "Files %s and %s are not hardlinked", path1, path2);
1398         failure_finish(NULL);
1399         return (0);
1400 }
1401
1402 int
1403 assertion_is_not_hardlink(const char *file, int line,
1404     const char *path1, const char *path2)
1405 {
1406         if (!is_hardlink(file, line, path1, path2))
1407                 return (1);
1408         failure_start(file, line,
1409             "Files %s and %s should not be hardlinked", path1, path2);
1410         failure_finish(NULL);
1411         return (0);
1412 }
1413
1414 /* Verify a/b/mtime of 'pathname'. */
1415 /* If 'recent', verify that it's within last 10 seconds. */
1416 static int
1417 assertion_file_time(const char *file, int line,
1418     const char *pathname, long t, long nsec, char type, int recent)
1419 {
1420         long long filet, filet_nsec;
1421         int r;
1422
1423 #if defined(_WIN32) && !defined(__CYGWIN__)
1424 #define EPOC_TIME       (116444736000000000ULL)
1425         FILETIME fxtime, fbirthtime, fatime, fmtime;
1426         ULARGE_INTEGER wintm;
1427         HANDLE h;
1428         fxtime.dwLowDateTime = 0;
1429         fxtime.dwHighDateTime = 0;
1430
1431         assertion_count(file, line);
1432         /* Note: FILE_FLAG_BACKUP_SEMANTICS applies to open
1433          * a directory file. If not, CreateFile() will fail when
1434          * the pathname is a directory. */
1435         h = CreateFile(pathname, FILE_READ_ATTRIBUTES, 0, NULL,
1436             OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1437         if (h == INVALID_HANDLE_VALUE) {
1438                 failure_start(file, line, "Can't access %s\n", pathname);
1439                 failure_finish(NULL);
1440                 return (0);
1441         }
1442         r = GetFileTime(h, &fbirthtime, &fatime, &fmtime);
1443         switch (type) {
1444         case 'a': fxtime = fatime; break;
1445         case 'b': fxtime = fbirthtime; break;
1446         case 'm': fxtime = fmtime; break;
1447         }
1448         CloseHandle(h);
1449         if (r == 0) {
1450                 failure_start(file, line, "Can't GetFileTime %s\n", pathname);
1451                 failure_finish(NULL);
1452                 return (0);
1453         }
1454         wintm.LowPart = fxtime.dwLowDateTime;
1455         wintm.HighPart = fxtime.dwHighDateTime;
1456         filet = (wintm.QuadPart - EPOC_TIME) / 10000000;
1457         filet_nsec = ((wintm.QuadPart - EPOC_TIME) % 10000000) * 100;
1458         nsec = (nsec / 100) * 100; /* Round the request */
1459 #else
1460         struct stat st;
1461
1462         assertion_count(file, line);
1463         r = lstat(pathname, &st);
1464         if (r != 0) {
1465                 failure_start(file, line, "Can't stat %s\n", pathname);
1466                 failure_finish(NULL);
1467                 return (0);
1468         }
1469         switch (type) {
1470         case 'a': filet = st.st_atime; break;
1471         case 'm': filet = st.st_mtime; break;
1472         case 'b': filet = 0; break;
1473         default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);
1474                 exit(1);
1475         }
1476 #if defined(__FreeBSD__)
1477         switch (type) {
1478         case 'a': filet_nsec = st.st_atimespec.tv_nsec; break;
1479         case 'b': filet = st.st_birthtime;
1480                 /* FreeBSD filesystems that don't support birthtime
1481                  * (e.g., UFS1) always return -1 here. */
1482                 if (filet == -1) {
1483                         return (1);
1484                 }
1485                 filet_nsec = st.st_birthtimespec.tv_nsec; break;
1486         case 'm': filet_nsec = st.st_mtimespec.tv_nsec; break;
1487         default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);
1488                 exit(1);
1489         }
1490         /* FreeBSD generally only stores to microsecond res, so round. */
1491         filet_nsec = (filet_nsec / 1000) * 1000;
1492         nsec = (nsec / 1000) * 1000;
1493 #else
1494         filet_nsec = nsec = 0;  /* Generic POSIX only has whole seconds. */
1495         if (type == 'b') return (1); /* Generic POSIX doesn't have birthtime */
1496 #if defined(__HAIKU__)
1497         if (type == 'a') return (1); /* Haiku doesn't have atime. */
1498 #endif
1499 #endif
1500 #endif
1501         if (recent) {
1502                 /* Check that requested time is up-to-date. */
1503                 time_t now = time(NULL);
1504                 if (filet < now - 10 || filet > now + 1) {
1505                         failure_start(file, line,
1506                             "File %s has %ctime %lld, %lld seconds ago\n",
1507                             pathname, type, filet, now - filet);
1508                         failure_finish(NULL);
1509                         return (0);
1510                 }
1511         } else if (filet != t || filet_nsec != nsec) {
1512                 failure_start(file, line,
1513                     "File %s has %ctime %lld.%09lld, expected %ld.%09ld",
1514                     pathname, type, filet, filet_nsec, t, nsec);
1515                 failure_finish(NULL);
1516                 return (0);
1517         }
1518         return (1);
1519 }
1520
1521 /* Verify atime of 'pathname'. */
1522 int
1523 assertion_file_atime(const char *file, int line,
1524     const char *pathname, long t, long nsec)
1525 {
1526         return assertion_file_time(file, line, pathname, t, nsec, 'a', 0);
1527 }
1528
1529 /* Verify atime of 'pathname' is up-to-date. */
1530 int
1531 assertion_file_atime_recent(const char *file, int line, const char *pathname)
1532 {
1533         return assertion_file_time(file, line, pathname, 0, 0, 'a', 1);
1534 }
1535
1536 /* Verify birthtime of 'pathname'. */
1537 int
1538 assertion_file_birthtime(const char *file, int line,
1539     const char *pathname, long t, long nsec)
1540 {
1541         return assertion_file_time(file, line, pathname, t, nsec, 'b', 0);
1542 }
1543
1544 /* Verify birthtime of 'pathname' is up-to-date. */
1545 int
1546 assertion_file_birthtime_recent(const char *file, int line,
1547     const char *pathname)
1548 {
1549         return assertion_file_time(file, line, pathname, 0, 0, 'b', 1);
1550 }
1551
1552 /* Verify mode of 'pathname'. */
1553 int
1554 assertion_file_mode(const char *file, int line, const char *pathname, int expected_mode)
1555 {
1556         int mode;
1557         int r;
1558
1559         assertion_count(file, line);
1560 #if defined(_WIN32) && !defined(__CYGWIN__)
1561         failure_start(file, line, "assertFileMode not yet implemented for Windows");
1562         (void)mode; /* UNUSED */
1563         (void)r; /* UNUSED */
1564         (void)pathname; /* UNUSED */
1565         (void)expected_mode; /* UNUSED */
1566 #else
1567         {
1568                 struct stat st;
1569                 r = lstat(pathname, &st);
1570                 mode = (int)(st.st_mode & 0777);
1571         }
1572         if (r == 0 && mode == expected_mode)
1573                         return (1);
1574         failure_start(file, line, "File %s has mode %o, expected %o",
1575             pathname, mode, expected_mode);
1576 #endif
1577         failure_finish(NULL);
1578         return (0);
1579 }
1580
1581 /* Verify mtime of 'pathname'. */
1582 int
1583 assertion_file_mtime(const char *file, int line,
1584     const char *pathname, long t, long nsec)
1585 {
1586         return assertion_file_time(file, line, pathname, t, nsec, 'm', 0);
1587 }
1588
1589 /* Verify mtime of 'pathname' is up-to-date. */
1590 int
1591 assertion_file_mtime_recent(const char *file, int line, const char *pathname)
1592 {
1593         return assertion_file_time(file, line, pathname, 0, 0, 'm', 1);
1594 }
1595
1596 /* Verify number of links to 'pathname'. */
1597 int
1598 assertion_file_nlinks(const char *file, int line,
1599     const char *pathname, int nlinks)
1600 {
1601 #if defined(_WIN32) && !defined(__CYGWIN__)
1602         BY_HANDLE_FILE_INFORMATION bhfi;
1603         int r;
1604
1605         assertion_count(file, line);
1606         r = my_GetFileInformationByName(pathname, &bhfi);
1607         if (r != 0 && bhfi.nNumberOfLinks == (DWORD)nlinks)
1608                 return (1);
1609         failure_start(file, line, "File %s has %jd links, expected %d",
1610             pathname, (intmax_t)bhfi.nNumberOfLinks, nlinks);
1611         failure_finish(NULL);
1612         return (0);
1613 #else
1614         struct stat st;
1615         int r;
1616
1617         assertion_count(file, line);
1618         r = lstat(pathname, &st);
1619         if (r == 0 && (int)st.st_nlink == nlinks)
1620                 return (1);
1621         failure_start(file, line, "File %s has %jd links, expected %d",
1622             pathname, (intmax_t)st.st_nlink, nlinks);
1623         failure_finish(NULL);
1624         return (0);
1625 #endif
1626 }
1627
1628 /* Verify size of 'pathname'. */
1629 int
1630 assertion_file_size(const char *file, int line, const char *pathname, long size)
1631 {
1632         int64_t filesize;
1633         int r;
1634
1635         assertion_count(file, line);
1636 #if defined(_WIN32) && !defined(__CYGWIN__)
1637         {
1638                 BY_HANDLE_FILE_INFORMATION bhfi;
1639                 r = !my_GetFileInformationByName(pathname, &bhfi);
1640                 filesize = ((int64_t)bhfi.nFileSizeHigh << 32) + bhfi.nFileSizeLow;
1641         }
1642 #else
1643         {
1644                 struct stat st;
1645                 r = lstat(pathname, &st);
1646                 filesize = st.st_size;
1647         }
1648 #endif
1649         if (r == 0 && filesize == size)
1650                         return (1);
1651         failure_start(file, line, "File %s has size %ld, expected %ld",
1652             pathname, (long)filesize, (long)size);
1653         failure_finish(NULL);
1654         return (0);
1655 }
1656
1657 /* Assert that 'pathname' is a dir.  If mode >= 0, verify that too. */
1658 int
1659 assertion_is_dir(const char *file, int line, const char *pathname, int mode)
1660 {
1661         struct stat st;
1662         int r;
1663
1664 #if defined(_WIN32) && !defined(__CYGWIN__)
1665         (void)mode; /* UNUSED */
1666 #endif
1667         assertion_count(file, line);
1668         r = lstat(pathname, &st);
1669         if (r != 0) {
1670                 failure_start(file, line, "Dir should exist: %s", pathname);
1671                 failure_finish(NULL);
1672                 return (0);
1673         }
1674         if (!S_ISDIR(st.st_mode)) {
1675                 failure_start(file, line, "%s is not a dir", pathname);
1676                 failure_finish(NULL);
1677                 return (0);
1678         }
1679 #if !defined(_WIN32) || defined(__CYGWIN__)
1680         /* Windows doesn't handle permissions the same way as POSIX,
1681          * so just ignore the mode tests. */
1682         /* TODO: Can we do better here? */
1683         if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {
1684                 failure_start(file, line, "Dir %s has wrong mode", pathname);
1685                 logprintf("  Expected: 0%3o\n", mode);
1686                 logprintf("  Found: 0%3o\n", st.st_mode & 07777);
1687                 failure_finish(NULL);
1688                 return (0);
1689         }
1690 #endif
1691         return (1);
1692 }
1693
1694 /* Verify that 'pathname' is a regular file.  If 'mode' is >= 0,
1695  * verify that too. */
1696 int
1697 assertion_is_reg(const char *file, int line, const char *pathname, int mode)
1698 {
1699         struct stat st;
1700         int r;
1701
1702 #if defined(_WIN32) && !defined(__CYGWIN__)
1703         (void)mode; /* UNUSED */
1704 #endif
1705         assertion_count(file, line);
1706         r = lstat(pathname, &st);
1707         if (r != 0 || !S_ISREG(st.st_mode)) {
1708                 failure_start(file, line, "File should exist: %s", pathname);
1709                 failure_finish(NULL);
1710                 return (0);
1711         }
1712 #if !defined(_WIN32) || defined(__CYGWIN__)
1713         /* Windows doesn't handle permissions the same way as POSIX,
1714          * so just ignore the mode tests. */
1715         /* TODO: Can we do better here? */
1716         if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {
1717                 failure_start(file, line, "File %s has wrong mode", pathname);
1718                 logprintf("  Expected: 0%3o\n", mode);
1719                 logprintf("  Found: 0%3o\n", st.st_mode & 07777);
1720                 failure_finish(NULL);
1721                 return (0);
1722         }
1723 #endif
1724         return (1);
1725 }
1726
1727 /*
1728  * Check whether 'pathname' is a symbolic link.  If 'contents' is
1729  * non-NULL, verify that the symlink has those contents.
1730  *
1731  * On platforms with directory symlinks, set isdir to 0 to test for a file
1732  * symlink and to 1 to test for a directory symlink. On other platforms
1733  * the variable is ignored.
1734  */
1735 static int
1736 is_symlink(const char *file, int line,
1737     const char *pathname, const char *contents, int isdir)
1738 {
1739 #if defined(_WIN32) && !defined(__CYGWIN__)
1740         HANDLE h;
1741         DWORD inbytes;
1742         REPARSE_DATA_BUFFER *buf;
1743         BY_HANDLE_FILE_INFORMATION st;
1744         size_t len, len2;
1745         wchar_t *linknamew, *contentsw;
1746         const char *p;
1747         char *s, *pn;
1748         int ret = 0;
1749         BYTE *indata;
1750         const DWORD flag = FILE_FLAG_BACKUP_SEMANTICS |
1751             FILE_FLAG_OPEN_REPARSE_POINT;
1752
1753         /* Replace slashes with backslashes in pathname */
1754         pn = malloc((strlen(pathname) + 1) * sizeof(char));
1755         p = pathname;
1756         s = pn;
1757         while(*p != '\0') {
1758                 if(*p == '/')
1759                         *s = '\\';
1760                 else
1761                         *s = *p;
1762                 p++;
1763                 s++;
1764         }
1765         *s = '\0';
1766
1767         h = CreateFileA(pn, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1768             flag, NULL);
1769         free(pn);
1770         if (h == INVALID_HANDLE_VALUE) {
1771                 failure_start(file, line, "Can't access %s\n", pathname);
1772                 failure_finish(NULL);
1773                 return (0);
1774         }
1775         ret = GetFileInformationByHandle(h, &st);
1776         if (ret == 0) {
1777                 failure_start(file, line,
1778                     "Can't stat: %s", pathname);
1779                 failure_finish(NULL);
1780         } else if ((st.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) {
1781                 failure_start(file, line,
1782                     "Not a symlink: %s", pathname);
1783                 failure_finish(NULL);
1784                 ret = 0;
1785         }
1786         if (isdir && ((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) {
1787                 failure_start(file, line,
1788                     "Not a directory symlink: %s", pathname);
1789                 failure_finish(NULL);
1790                 ret = 0;
1791         }
1792         if (!isdir &&
1793             ((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
1794                 failure_start(file, line,
1795                     "Not a file symlink: %s", pathname);
1796                 failure_finish(NULL);
1797                 ret = 0;
1798         }
1799         if (ret == 0) {
1800                 CloseHandle(h);
1801                 return (0);
1802         }
1803
1804         indata = malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
1805         ret = DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, NULL, 0, indata,
1806             1024, &inbytes, NULL);
1807         CloseHandle(h);
1808         if (ret == 0) {
1809                 free(indata);
1810                 failure_start(file, line,
1811                     "Could not retrieve symlink target: %s", pathname);
1812                 failure_finish(NULL);
1813                 return (0);
1814         }
1815
1816         buf = (REPARSE_DATA_BUFFER *) indata;
1817         if (buf->ReparseTag != IO_REPARSE_TAG_SYMLINK) {
1818                 free(indata);
1819                 /* File is not a symbolic link */
1820                 failure_start(file, line,
1821                     "Not a symlink: %s", pathname);
1822                 failure_finish(NULL);
1823                 return (0);
1824         }
1825
1826         if (contents == NULL) {
1827                 free(indata);
1828                 return (1);
1829         }
1830
1831         len = buf->SymbolicLinkReparseBuffer.SubstituteNameLength;
1832
1833         linknamew = malloc(len + sizeof(wchar_t));
1834         if (linknamew == NULL) {
1835                 free(indata);
1836                 return (0);
1837         }
1838
1839         memcpy(linknamew, &((BYTE *)buf->SymbolicLinkReparseBuffer.PathBuffer)
1840             [buf->SymbolicLinkReparseBuffer.SubstituteNameOffset], len);
1841         free(indata);
1842
1843         linknamew[len / sizeof(wchar_t)] = L'\0';
1844
1845         contentsw = malloc(len + sizeof(wchar_t));
1846         if (contentsw == NULL) {
1847                 free(linknamew);
1848                 return (0);
1849         }
1850
1851         len2 = mbsrtowcs(contentsw, &contents, (len + sizeof(wchar_t)
1852             / sizeof(wchar_t)), NULL);
1853
1854         if (len2 > 0 && wcscmp(linknamew, contentsw) != 0)
1855                 ret = 1;
1856
1857         free(linknamew);
1858         free(contentsw);
1859         return (ret);
1860 #else
1861         char buff[300];
1862         struct stat st;
1863         ssize_t linklen;
1864         int r;
1865
1866         (void)isdir; /* UNUSED */
1867         assertion_count(file, line);
1868         r = lstat(pathname, &st);
1869         if (r != 0) {
1870                 failure_start(file, line,
1871                     "Symlink should exist: %s", pathname);
1872                 failure_finish(NULL);
1873                 return (0);
1874         }
1875         if (!S_ISLNK(st.st_mode))
1876                 return (0);
1877         if (contents == NULL)
1878                 return (1);
1879         linklen = readlink(pathname, buff, sizeof(buff) - 1);
1880         if (linklen < 0) {
1881                 failure_start(file, line, "Can't read symlink %s", pathname);
1882                 failure_finish(NULL);
1883                 return (0);
1884         }
1885         buff[linklen] = '\0';
1886         if (strcmp(buff, contents) != 0)
1887                 return (0);
1888         return (1);
1889 #endif
1890 }
1891
1892 /* Assert that path is a symlink that (optionally) contains contents. */
1893 int
1894 assertion_is_symlink(const char *file, int line,
1895     const char *path, const char *contents, int isdir)
1896 {
1897         if (is_symlink(file, line, path, contents, isdir))
1898                 return (1);
1899         if (contents)
1900                 failure_start(file, line, "File %s is not a symlink to %s",
1901                     path, contents);
1902         else
1903                 failure_start(file, line, "File %s is not a symlink", path);
1904         failure_finish(NULL);
1905         return (0);
1906 }
1907
1908
1909 /* Create a directory and report any errors. */
1910 int
1911 assertion_make_dir(const char *file, int line, const char *dirname, int mode)
1912 {
1913         assertion_count(file, line);
1914 #if defined(_WIN32) && !defined(__CYGWIN__)
1915         (void)mode; /* UNUSED */
1916         if (0 == _mkdir(dirname))
1917                 return (1);
1918 #else
1919         if (0 == mkdir(dirname, mode)) {
1920                 if (0 == chmod(dirname, mode)) {
1921                         assertion_file_mode(file, line, dirname, mode);
1922                         return (1);
1923                 }
1924         }
1925 #endif
1926         failure_start(file, line, "Could not create directory %s", dirname);
1927         failure_finish(NULL);
1928         return(0);
1929 }
1930
1931 /* Create a file with the specified contents and report any failures. */
1932 int
1933 assertion_make_file(const char *file, int line,
1934     const char *path, int mode, int csize, const void *contents)
1935 {
1936 #if defined(_WIN32) && !defined(__CYGWIN__)
1937         /* TODO: Rework this to set file mode as well. */
1938         FILE *f;
1939         (void)mode; /* UNUSED */
1940         assertion_count(file, line);
1941         f = fopen(path, "wb");
1942         if (f == NULL) {
1943                 failure_start(file, line, "Could not create file %s", path);
1944                 failure_finish(NULL);
1945                 return (0);
1946         }
1947         if (contents != NULL) {
1948                 size_t wsize;
1949
1950                 if (csize < 0)
1951                         wsize = strlen(contents);
1952                 else
1953                         wsize = (size_t)csize;
1954                 if (wsize != fwrite(contents, 1, wsize, f)) {
1955                         fclose(f);
1956                         failure_start(file, line,
1957                             "Could not write file %s", path);
1958                         failure_finish(NULL);
1959                         return (0);
1960                 }
1961         }
1962         fclose(f);
1963         return (1);
1964 #else
1965         int fd;
1966         assertion_count(file, line);
1967         fd = open(path, O_CREAT | O_WRONLY, mode >= 0 ? mode : 0644);
1968         if (fd < 0) {
1969                 failure_start(file, line, "Could not create %s", path);
1970                 failure_finish(NULL);
1971                 return (0);
1972         }
1973         if (0 != chmod(path, mode)) {
1974                 failure_start(file, line, "Could not chmod %s", path);
1975                 failure_finish(NULL);
1976                 close(fd);
1977                 return (0);
1978         }
1979         if (contents != NULL) {
1980                 ssize_t wsize;
1981
1982                 if (csize < 0)
1983                         wsize = (ssize_t)strlen(contents);
1984                 else
1985                         wsize = (ssize_t)csize;
1986                 if (wsize != write(fd, contents, wsize)) {
1987                         close(fd);
1988                         failure_start(file, line,
1989                             "Could not write to %s", path);
1990                         failure_finish(NULL);
1991                         close(fd);
1992                         return (0);
1993                 }
1994         }
1995         close(fd);
1996         assertion_file_mode(file, line, path, mode);
1997         return (1);
1998 #endif
1999 }
2000
2001 /* Create a hardlink and report any failures. */
2002 int
2003 assertion_make_hardlink(const char *file, int line,
2004     const char *newpath, const char *linkto)
2005 {
2006         int succeeded;
2007
2008         assertion_count(file, line);
2009 #if defined(_WIN32) && !defined(__CYGWIN__)
2010         succeeded = my_CreateHardLinkA(newpath, linkto);
2011 #elif HAVE_LINK
2012         succeeded = !link(linkto, newpath);
2013 #else
2014         succeeded = 0;
2015 #endif
2016         if (succeeded)
2017                 return (1);
2018         failure_start(file, line, "Could not create hardlink");
2019         logprintf("   New link: %s\n", newpath);
2020         logprintf("   Old name: %s\n", linkto);
2021         failure_finish(NULL);
2022         return(0);
2023 }
2024
2025 /*
2026  * Create a symlink and report any failures.
2027  *
2028  * Windows symlinks need to know if the target is a directory.
2029  */
2030 int
2031 assertion_make_symlink(const char *file, int line,
2032     const char *newpath, const char *linkto, int targetIsDir)
2033 {
2034 #if defined(_WIN32) && !defined(__CYGWIN__)
2035         assertion_count(file, line);
2036         if (my_CreateSymbolicLinkA(newpath, linkto, targetIsDir))
2037                 return (1);
2038 #elif HAVE_SYMLINK
2039         (void)targetIsDir; /* UNUSED */
2040         assertion_count(file, line);
2041         if (0 == symlink(linkto, newpath))
2042                 return (1);
2043 #else
2044         (void)targetIsDir; /* UNUSED */
2045 #endif
2046         failure_start(file, line, "Could not create symlink");
2047         logprintf("   New link: %s\n", newpath);
2048         logprintf("   Old name: %s\n", linkto);
2049         failure_finish(NULL);
2050         return(0);
2051 }
2052
2053 /* Set umask, report failures. */
2054 int
2055 assertion_umask(const char *file, int line, int mask)
2056 {
2057         assertion_count(file, line);
2058         (void)file; /* UNUSED */
2059         (void)line; /* UNUSED */
2060         umask(mask);
2061         return (1);
2062 }
2063
2064 /* Set times, report failures. */
2065 int
2066 assertion_utimes(const char *file, int line,
2067     const char *pathname, long at, long at_nsec, long mt, long mt_nsec)
2068 {
2069         int r;
2070
2071 #if defined(_WIN32) && !defined(__CYGWIN__)
2072 #define WINTIME(sec, nsec) ((Int32x32To64(sec, 10000000) + EPOC_TIME)\
2073          + (((nsec)/1000)*10))
2074         HANDLE h;
2075         ULARGE_INTEGER wintm;
2076         FILETIME fatime, fmtime;
2077         FILETIME *pat, *pmt;
2078
2079         assertion_count(file, line);
2080         h = CreateFileA(pathname,GENERIC_READ | GENERIC_WRITE,
2081                     FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
2082                     FILE_FLAG_BACKUP_SEMANTICS, NULL);
2083         if (h == INVALID_HANDLE_VALUE) {
2084                 failure_start(file, line, "Can't access %s\n", pathname);
2085                 failure_finish(NULL);
2086                 return (0);
2087         }
2088
2089         if (at > 0 || at_nsec > 0) {
2090                 wintm.QuadPart = WINTIME(at, at_nsec);
2091                 fatime.dwLowDateTime = wintm.LowPart;
2092                 fatime.dwHighDateTime = wintm.HighPart;
2093                 pat = &fatime;
2094         } else
2095                 pat = NULL;
2096         if (mt > 0 || mt_nsec > 0) {
2097                 wintm.QuadPart = WINTIME(mt, mt_nsec);
2098                 fmtime.dwLowDateTime = wintm.LowPart;
2099                 fmtime.dwHighDateTime = wintm.HighPart;
2100                 pmt = &fmtime;
2101         } else
2102                 pmt = NULL;
2103         if (pat != NULL || pmt != NULL)
2104                 r = SetFileTime(h, NULL, pat, pmt);
2105         else
2106                 r = 1;
2107         CloseHandle(h);
2108         if (r == 0) {
2109                 failure_start(file, line, "Can't SetFileTime %s\n", pathname);
2110                 failure_finish(NULL);
2111                 return (0);
2112         }
2113         return (1);
2114 #else /* defined(_WIN32) && !defined(__CYGWIN__) */
2115         struct stat st;
2116         struct timeval times[2];
2117
2118 #if !defined(__FreeBSD__)
2119         mt_nsec = at_nsec = 0;  /* Generic POSIX only has whole seconds. */
2120 #endif
2121         if (mt == 0 && mt_nsec == 0 && at == 0 && at_nsec == 0)
2122                 return (1);
2123
2124         r = lstat(pathname, &st);
2125         if (r < 0) {
2126                 failure_start(file, line, "Can't stat %s\n", pathname);
2127                 failure_finish(NULL);
2128                 return (0);
2129         }
2130
2131         if (mt == 0 && mt_nsec == 0) {
2132                 mt = st.st_mtime;
2133 #if defined(__FreeBSD__)
2134                 mt_nsec = st.st_mtimespec.tv_nsec;
2135                 /* FreeBSD generally only stores to microsecond res, so round. */
2136                 mt_nsec = (mt_nsec / 1000) * 1000;
2137 #endif
2138         }
2139         if (at == 0 && at_nsec == 0) {
2140                 at = st.st_atime;
2141 #if defined(__FreeBSD__)
2142                 at_nsec = st.st_atimespec.tv_nsec;
2143                 /* FreeBSD generally only stores to microsecond res, so round. */
2144                 at_nsec = (at_nsec / 1000) * 1000;
2145 #endif
2146         }
2147
2148         times[1].tv_sec = mt;
2149         times[1].tv_usec = mt_nsec / 1000;
2150
2151         times[0].tv_sec = at;
2152         times[0].tv_usec = at_nsec / 1000;
2153
2154 #ifdef HAVE_LUTIMES
2155         r = lutimes(pathname, times);
2156 #else
2157         r = utimes(pathname, times);
2158 #endif
2159         if (r < 0) {
2160                 failure_start(file, line, "Can't utimes %s\n", pathname);
2161                 failure_finish(NULL);
2162                 return (0);
2163         }
2164         return (1);
2165 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
2166 }
2167
2168 /* Compare file flags */
2169 int
2170 assertion_compare_fflags(const char *file, int line, const char *patha,
2171     const char *pathb, int nomatch)
2172 {
2173 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2174         struct stat sa, sb;
2175
2176         assertion_count(file, line);
2177
2178         if (stat(patha, &sa) < 0)
2179                 return (0);
2180         if (stat(pathb, &sb) < 0)
2181                 return (0);
2182         if (!nomatch && sa.st_flags != sb.st_flags) {
2183                 failure_start(file, line, "File flags should be identical: "
2184                     "%s=%#010x %s=%#010x", patha, sa.st_flags, pathb,
2185                     sb.st_flags);
2186                 failure_finish(NULL);
2187                 return (0);
2188         }
2189         if (nomatch && sa.st_flags == sb.st_flags) {
2190                 failure_start(file, line, "File flags should be different: "
2191                     "%s=%#010x %s=%#010x", patha, sa.st_flags, pathb,
2192                     sb.st_flags);
2193                 failure_finish(NULL);
2194                 return (0);
2195         }
2196 #elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) && \
2197        defined(FS_NODUMP_FL)) || \
2198       (defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \
2199          && defined(EXT2_NODUMP_FL))
2200         int fd, r, flagsa, flagsb;
2201
2202         assertion_count(file, line);
2203         fd = open(patha, O_RDONLY | O_NONBLOCK);
2204         if (fd < 0) {
2205                 failure_start(file, line, "Can't open %s\n", patha);
2206                 failure_finish(NULL);
2207                 return (0);
2208         }
2209         r = ioctl(fd,
2210 #ifdef FS_IOC_GETFLAGS
2211             FS_IOC_GETFLAGS,
2212 #else
2213             EXT2_IOC_GETFLAGS,
2214 #endif
2215             &flagsa);
2216         close(fd);
2217         if (r < 0) {
2218                 failure_start(file, line, "Can't get flags %s\n", patha);
2219                 failure_finish(NULL);
2220                 return (0);
2221         }
2222         fd = open(pathb, O_RDONLY | O_NONBLOCK);
2223         if (fd < 0) {
2224                 failure_start(file, line, "Can't open %s\n", pathb);
2225                 failure_finish(NULL);
2226                 return (0);
2227         }
2228         r = ioctl(fd,
2229 #ifdef FS_IOC_GETFLAGS
2230             FS_IOC_GETFLAGS,
2231 #else
2232             EXT2_IOC_GETFLAGS,
2233 #endif
2234             &flagsb);
2235         close(fd);
2236         if (r < 0) {
2237                 failure_start(file, line, "Can't get flags %s\n", pathb);
2238                 failure_finish(NULL);
2239                 return (0);
2240         }
2241         if (!nomatch && flagsa != flagsb) {
2242                 failure_start(file, line, "File flags should be identical: "
2243                     "%s=%#010x %s=%#010x", patha, flagsa, pathb, flagsb);
2244                 failure_finish(NULL);
2245                 return (0);
2246         }
2247         if (nomatch && flagsa == flagsb) {
2248                 failure_start(file, line, "File flags should be different: "
2249                     "%s=%#010x %s=%#010x", patha, flagsa, pathb, flagsb);
2250                 failure_finish(NULL);
2251                 return (0);
2252         }
2253 #else
2254         (void)patha; /* UNUSED */
2255         (void)pathb; /* UNUSED */
2256         (void)nomatch; /* UNUSED */
2257         assertion_count(file, line);
2258 #endif
2259         return (1);
2260 }
2261
2262 /* Set nodump, report failures. */
2263 int
2264 assertion_set_nodump(const char *file, int line, const char *pathname)
2265 {
2266 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2267         int r;
2268
2269         assertion_count(file, line);
2270         r = chflags(pathname, UF_NODUMP);
2271         if (r < 0) {
2272                 failure_start(file, line, "Can't set nodump %s\n", pathname);
2273                 failure_finish(NULL);
2274                 return (0);
2275         }
2276 #elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) && \
2277        defined(FS_NODUMP_FL)) || \
2278       (defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \
2279          && defined(EXT2_NODUMP_FL))
2280         int fd, r, flags;
2281
2282         assertion_count(file, line);
2283         fd = open(pathname, O_RDONLY | O_NONBLOCK);
2284         if (fd < 0) {
2285                 failure_start(file, line, "Can't open %s\n", pathname);
2286                 failure_finish(NULL);
2287                 return (0);
2288         }
2289         r = ioctl(fd,
2290 #ifdef FS_IOC_GETFLAGS
2291             FS_IOC_GETFLAGS,
2292 #else
2293             EXT2_IOC_GETFLAGS,
2294 #endif
2295             &flags);
2296         if (r < 0) {
2297                 failure_start(file, line, "Can't get flags %s\n", pathname);
2298                 failure_finish(NULL);
2299                 return (0);
2300         }
2301 #ifdef FS_NODUMP_FL
2302         flags |= FS_NODUMP_FL;
2303 #else
2304         flags |= EXT2_NODUMP_FL;
2305 #endif
2306
2307          r = ioctl(fd,
2308 #ifdef FS_IOC_SETFLAGS
2309             FS_IOC_SETFLAGS,
2310 #else
2311             EXT2_IOC_SETFLAGS,
2312 #endif
2313             &flags);
2314         if (r < 0) {
2315                 failure_start(file, line, "Can't set nodump %s\n", pathname);
2316                 failure_finish(NULL);
2317                 return (0);
2318         }
2319         close(fd);
2320 #else
2321         (void)pathname; /* UNUSED */
2322         assertion_count(file, line);
2323 #endif
2324         return (1);
2325 }
2326
2327 #ifdef PROGRAM
2328 static void assert_version_id(char **qq, size_t *ss)
2329 {
2330         char *q = *qq;
2331         size_t s = *ss;
2332
2333         /* Version number is a series of digits and periods. */
2334         while (s > 0 && (*q == '.' || (*q >= '0' && *q <= '9'))) {
2335                 ++q;
2336                 --s;
2337         }
2338
2339         if (q[0] == 'd' && q[1] == 'e' && q[2] == 'v') {
2340                 q += 3;
2341                 s -= 3;
2342         }
2343         
2344         /* Skip a single trailing a,b,c, or d. */
2345         if (*q == 'a' || *q == 'b' || *q == 'c' || *q == 'd')
2346                 ++q;
2347
2348         /* Version number terminated by space. */
2349         failure("No space after version: ``%s''", q);
2350         assert(s > 1);
2351         failure("No space after version: ``%s''", q);
2352         assert(*q == ' ');
2353
2354         ++q; --s;
2355
2356         *qq = q;
2357         *ss = s;
2358 }
2359
2360
2361 /*
2362  * Check program version
2363  */
2364 void assertVersion(const char *prog, const char *base)
2365 {
2366         int r;
2367         char *p, *q;
2368         size_t s;
2369         size_t prog_len = strlen(base);
2370
2371         r = systemf("%s --version >version.stdout 2>version.stderr", prog);
2372         if (r != 0)
2373                 r = systemf("%s -W version >version.stdout 2>version.stderr",
2374                     prog);
2375
2376         failure("Unable to run either %s --version or %s -W version",
2377                 prog, prog);
2378         if (!assert(r == 0))
2379                 return;
2380
2381         /* --version should generate nothing to stdout. */
2382         assertEmptyFile("version.stderr");
2383
2384         /* Verify format of version message. */
2385         q = p = slurpfile(&s, "version.stdout");
2386
2387         /* Version message should start with name of program, then space. */
2388         assert(s > prog_len + 1);
2389         
2390         failure("Version must start with '%s': ``%s''", base, p);
2391         if (!assertEqualMem(q, base, prog_len)) {
2392                 free(p);
2393                 return;
2394         }
2395
2396         q += prog_len; s -= prog_len;
2397
2398         assert(*q == ' ');
2399         q++; s--;
2400
2401         assert_version_id(&q, &s);
2402
2403         /* Separator. */
2404         failure("No `-' between program name and versions: ``%s''", p);
2405         assertEqualMem(q, "- ", 2);
2406         q += 2; s -= 2;
2407
2408         failure("Not long enough for libarchive version: ``%s''", p);
2409         assert(s > 11);
2410
2411         failure("Libarchive version must start with `libarchive': ``%s''", p);
2412         assertEqualMem(q, "libarchive ", 11);
2413
2414         q += 11; s -= 11;
2415
2416         assert_version_id(&q, &s);
2417
2418         /* Skip arbitrary third-party version numbers. */
2419         while (s > 0 && (*q == ' ' || *q == '-' || *q == '/' || *q == '.' ||
2420             isalnum((unsigned char)*q))) {
2421                 ++q;
2422                 --s;
2423         }
2424
2425         /* All terminated by end-of-line. */
2426         assert(s >= 1);
2427
2428         /* Skip an optional CR character (e.g., Windows) */
2429         failure("Version output must end with \\n or \\r\\n");
2430
2431         if (*q == '\r') { ++q; --s; }
2432         assertEqualMem(q, "\n", 1);
2433
2434         free(p);
2435 }
2436 #endif  /* PROGRAM */
2437
2438 /*
2439  *
2440  *  UTILITIES for use by tests.
2441  *
2442  */
2443
2444 /*
2445  * Check whether platform supports symlinks.  This is intended
2446  * for tests to use in deciding whether to bother testing symlink
2447  * support; if the platform doesn't support symlinks, there's no point
2448  * in checking whether the program being tested can create them.
2449  *
2450  * Note that the first time this test is called, we actually go out to
2451  * disk to create and verify a symlink.  This is necessary because
2452  * symlink support is actually a property of a particular filesystem
2453  * and can thus vary between directories on a single system.  After
2454  * the first call, this returns the cached result from memory, so it's
2455  * safe to call it as often as you wish.
2456  */
2457 int
2458 canSymlink(void)
2459 {
2460         /* Remember the test result */
2461         static int value = 0, tested = 0;
2462         if (tested)
2463                 return (value);
2464
2465         ++tested;
2466         assertion_make_file(__FILE__, __LINE__, "canSymlink.0", 0644, 1, "a");
2467         /* Note: Cygwin has its own symlink() emulation that does not
2468          * use the Win32 CreateSymbolicLink() function. */
2469 #if defined(_WIN32) && !defined(__CYGWIN__)
2470         value = my_CreateSymbolicLinkA("canSymlink.1", "canSymlink.0", 0)
2471             && is_symlink(__FILE__, __LINE__, "canSymlink.1", "canSymlink.0",
2472             0);
2473 #elif HAVE_SYMLINK
2474         value = (0 == symlink("canSymlink.0", "canSymlink.1"))
2475             && is_symlink(__FILE__, __LINE__, "canSymlink.1","canSymlink.0",
2476             0);
2477 #endif
2478         return (value);
2479 }
2480
2481 /* Platform-dependent options for hiding the output of a subcommand. */
2482 #if defined(_WIN32) && !defined(__CYGWIN__)
2483 static const char *redirectArgs = ">NUL 2>NUL"; /* Win32 cmd.exe */
2484 #else
2485 static const char *redirectArgs = ">/dev/null 2>/dev/null"; /* POSIX 'sh' */
2486 #endif
2487 /*
2488  * Can this platform run the bzip2 program?
2489  */
2490 int
2491 canBzip2(void)
2492 {
2493         static int tested = 0, value = 0;
2494         if (!tested) {
2495                 tested = 1;
2496                 if (systemf("bzip2 --help %s", redirectArgs) == 0)
2497                         value = 1;
2498         }
2499         return (value);
2500 }
2501
2502 /*
2503  * Can this platform run the grzip program?
2504  */
2505 int
2506 canGrzip(void)
2507 {
2508         static int tested = 0, value = 0;
2509         if (!tested) {
2510                 tested = 1;
2511                 if (systemf("grzip -V %s", redirectArgs) == 0)
2512                         value = 1;
2513         }
2514         return (value);
2515 }
2516
2517 /*
2518  * Can this platform run the gzip program?
2519  */
2520 int
2521 canGzip(void)
2522 {
2523         static int tested = 0, value = 0;
2524         if (!tested) {
2525                 tested = 1;
2526                 if (systemf("gzip --help %s", redirectArgs) == 0)
2527                         value = 1;
2528         }
2529         return (value);
2530 }
2531
2532 /*
2533  * Can this platform run the lrzip program?
2534  */
2535 int
2536 canRunCommand(const char *cmd)
2537 {
2538   static int tested = 0, value = 0;
2539   if (!tested) {
2540     tested = 1;
2541     if (systemf("%s %s", cmd, redirectArgs) == 0)
2542       value = 1;
2543   }
2544   return (value);
2545 }
2546
2547 int
2548 canLrzip(void)
2549 {
2550         static int tested = 0, value = 0;
2551         if (!tested) {
2552                 tested = 1;
2553                 if (systemf("lrzip -V %s", redirectArgs) == 0)
2554                         value = 1;
2555         }
2556         return (value);
2557 }
2558
2559 /*
2560  * Can this platform run the lz4 program?
2561  */
2562 int
2563 canLz4(void)
2564 {
2565         static int tested = 0, value = 0;
2566         if (!tested) {
2567                 tested = 1;
2568                 if (systemf("lz4 --help %s", redirectArgs) == 0)
2569                         value = 1;
2570         }
2571         return (value);
2572 }
2573
2574 /*
2575  * Can this platform run the zstd program?
2576  */
2577 int
2578 canZstd(void)
2579 {
2580         static int tested = 0, value = 0;
2581         if (!tested) {
2582                 tested = 1;
2583                 if (systemf("zstd --help %s", redirectArgs) == 0)
2584                         value = 1;
2585         }
2586         return (value);
2587 }
2588
2589 /*
2590  * Can this platform run the lzip program?
2591  */
2592 int
2593 canLzip(void)
2594 {
2595         static int tested = 0, value = 0;
2596         if (!tested) {
2597                 tested = 1;
2598                 if (systemf("lzip --help %s", redirectArgs) == 0)
2599                         value = 1;
2600         }
2601         return (value);
2602 }
2603
2604 /*
2605  * Can this platform run the lzma program?
2606  */
2607 int
2608 canLzma(void)
2609 {
2610         static int tested = 0, value = 0;
2611         if (!tested) {
2612                 tested = 1;
2613                 if (systemf("lzma %s", redirectArgs) == 0)
2614                         value = 1;
2615         }
2616         return (value);
2617 }
2618
2619 /*
2620  * Can this platform run the lzop program?
2621  */
2622 int
2623 canLzop(void)
2624 {
2625         static int tested = 0, value = 0;
2626         if (!tested) {
2627                 tested = 1;
2628                 if (systemf("lzop --help %s", redirectArgs) == 0)
2629                         value = 1;
2630         }
2631         return (value);
2632 }
2633
2634 /*
2635  * Can this platform run the xz program?
2636  */
2637 int
2638 canXz(void)
2639 {
2640         static int tested = 0, value = 0;
2641         if (!tested) {
2642                 tested = 1;
2643                 if (systemf("xz --help %s", redirectArgs) == 0)
2644                         value = 1;
2645         }
2646         return (value);
2647 }
2648
2649 /*
2650  * Can this filesystem handle nodump flags.
2651  */
2652 int
2653 canNodump(void)
2654 {
2655 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2656         const char *path = "cannodumptest";
2657         struct stat sb;
2658
2659         assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);
2660         if (chflags(path, UF_NODUMP) < 0)
2661                 return (0);
2662         if (stat(path, &sb) < 0)
2663                 return (0);
2664         if (sb.st_flags & UF_NODUMP)
2665                 return (1);
2666 #elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) \
2667          && defined(FS_NODUMP_FL)) || \
2668       (defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \
2669          && defined(EXT2_NODUMP_FL))
2670         const char *path = "cannodumptest";
2671         int fd, r, flags;
2672
2673         assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);
2674         fd = open(path, O_RDONLY | O_NONBLOCK);
2675         if (fd < 0)
2676                 return (0);
2677         r = ioctl(fd,
2678 #ifdef FS_IOC_GETFLAGS
2679             FS_IOC_GETFLAGS,
2680 #else
2681             EXT2_IOC_GETFLAGS,
2682 #endif
2683             &flags);
2684         if (r < 0)
2685                 return (0);
2686 #ifdef FS_NODUMP_FL
2687         flags |= FS_NODUMP_FL;
2688 #else
2689         flags |= EXT2_NODUMP_FL;
2690 #endif
2691         r = ioctl(fd,
2692 #ifdef FS_IOC_SETFLAGS
2693             FS_IOC_SETFLAGS,
2694 #else
2695             EXT2_IOC_SETFLAGS,
2696 #endif
2697            &flags);
2698         if (r < 0)
2699                 return (0);
2700         close(fd);
2701         fd = open(path, O_RDONLY | O_NONBLOCK);
2702         if (fd < 0)
2703                 return (0);
2704         r = ioctl(fd,
2705 #ifdef FS_IOC_GETFLAGS
2706             FS_IOC_GETFLAGS,
2707 #else
2708             EXT2_IOC_GETFLAGS,
2709 #endif
2710             &flags);
2711         if (r < 0)
2712                 return (0);
2713         close(fd);
2714 #ifdef FS_NODUMP_FL
2715         if (flags & FS_NODUMP_FL)
2716 #else
2717         if (flags & EXT2_NODUMP_FL)
2718 #endif
2719                 return (1);
2720 #endif
2721         return (0);
2722 }
2723
2724 /* Get extended attribute value from a path */
2725 void *
2726 getXattr(const char *path, const char *name, size_t *sizep)
2727
2728         void *value = NULL;
2729 #if ARCHIVE_XATTR_SUPPORT
2730         ssize_t size;
2731 #if ARCHIVE_XATTR_LINUX
2732         size = lgetxattr(path, name, NULL, 0);
2733 #elif ARCHIVE_XATTR_DARWIN
2734         size = getxattr(path, name, NULL, 0, 0, XATTR_NOFOLLOW);
2735 #elif ARCHIVE_XATTR_AIX
2736         size = lgetea(path, name, NULL, 0);
2737 #elif ARCHIVE_XATTR_FREEBSD
2738         size = extattr_get_link(path, EXTATTR_NAMESPACE_USER, name + 5,
2739             NULL, 0);
2740 #endif
2741
2742         if (size >= 0) {
2743                 value = malloc(size);
2744 #if ARCHIVE_XATTR_LINUX
2745                 size = lgetxattr(path, name, value, size);
2746 #elif ARCHIVE_XATTR_DARWIN
2747                 size = getxattr(path, name, value, size, 0, XATTR_NOFOLLOW);
2748 #elif ARCHIVE_XATTR_AIX
2749                 size = lgetea(path, name, value, size);
2750 #elif ARCHIVE_XATTR_FREEBSD
2751                 size = extattr_get_link(path, EXTATTR_NAMESPACE_USER, name + 5,
2752                     value, size);
2753 #endif
2754                 if (size < 0) {
2755                         free(value);
2756                         value = NULL;
2757                 }
2758         }
2759         if (size < 0)
2760                 *sizep = 0;
2761         else
2762                 *sizep = (size_t)size;
2763 #else   /* !ARCHIVE_XATTR_SUPPORT */
2764         (void)path;     /* UNUSED */
2765         (void)name;     /* UNUSED */
2766         *sizep = 0;
2767 #endif  /* !ARCHIVE_XATTR_SUPPORT */
2768         return (value);
2769 }
2770
2771 /*
2772  * Set extended attribute on a path
2773  * Returns 0 on error, 1 on success
2774  */
2775 int
2776 setXattr(const char *path, const char *name, const void *value, size_t size)
2777 {
2778 #if ARCHIVE_XATTR_SUPPORT
2779 #if ARCHIVE_XATTR_LINUX
2780         if (lsetxattr(path, name, value, size, 0) == 0)
2781 #elif ARCHIVE_XATTR_DARWIN
2782         if (setxattr(path, name, value, size, 0, XATTR_NOFOLLOW) == 0)
2783 #elif ARCHIVE_XATTR_AIX
2784         if (lsetea(path, name, value, size, 0) == 0)
2785 #elif ARCHIVE_XATTR_FREEBSD
2786         if (extattr_set_link(path, EXTATTR_NAMESPACE_USER, name + 5, value,
2787             size) > -1)
2788 #else
2789         if (0)
2790 #endif
2791                 return (1);
2792 #else   /* !ARCHIVE_XATTR_SUPPORT */
2793         (void)path;     /* UNUSED */
2794         (void)name;     /* UNUSED */
2795         (void)value;    /* UNUSED */
2796         (void)size;     /* UNUSED */
2797 #endif  /* !ARCHIVE_XATTR_SUPPORT */
2798         return (0);
2799 }
2800
2801 #if ARCHIVE_ACL_SUNOS
2802 /* Fetch ACLs on Solaris using acl() or facl() */
2803 void *
2804 sunacl_get(int cmd, int *aclcnt, int fd, const char *path)
2805 {
2806         int cnt, cntcmd;
2807         size_t size;
2808         void *aclp;
2809
2810         if (cmd == GETACL) {
2811                 cntcmd = GETACLCNT;
2812                 size = sizeof(aclent_t);
2813         }
2814 #if ARCHIVE_ACL_SUNOS_NFS4
2815         else if (cmd == ACE_GETACL) {
2816                 cntcmd = ACE_GETACLCNT;
2817                 size = sizeof(ace_t);
2818         }
2819 #endif
2820         else {
2821                 errno = EINVAL;
2822                 *aclcnt = -1;
2823                 return (NULL);
2824         }
2825
2826         aclp = NULL;
2827         cnt = -2;
2828         while (cnt == -2 || (cnt == -1 && errno == ENOSPC)) {
2829                 if (path != NULL)
2830                         cnt = acl(path, cntcmd, 0, NULL);
2831                 else
2832                         cnt = facl(fd, cntcmd, 0, NULL);
2833
2834                 if (cnt > 0) {
2835                         if (aclp == NULL)
2836                                 aclp = malloc(cnt * size);
2837                         else
2838                                 aclp = realloc(NULL, cnt * size);
2839                         if (aclp != NULL) {
2840                                 if (path != NULL)
2841                                         cnt = acl(path, cmd, cnt, aclp);
2842                                 else
2843                                         cnt = facl(fd, cmd, cnt, aclp);
2844                         }
2845                 } else {
2846                         free(aclp);
2847                         aclp = NULL;
2848                         break;
2849                 }
2850         }
2851
2852         *aclcnt = cnt;
2853         return (aclp);
2854 }
2855 #endif /* ARCHIVE_ACL_SUNOS */
2856
2857 /*
2858  * Set test ACLs on a path
2859  * Return values:
2860  * 0: error setting ACLs
2861  * ARCHIVE_TEST_ACL_TYPE_POSIX1E: POSIX.1E ACLs have been set
2862  * ARCHIVE_TEST_ACL_TYPE_NFS4: NFSv4 or extended ACLs have been set
2863  */
2864 int
2865 setTestAcl(const char *path)
2866 {
2867 #if ARCHIVE_ACL_SUPPORT
2868         int r = 1;
2869 #if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_DARWIN
2870         acl_t acl;
2871 #endif
2872 #if ARCHIVE_ACL_LIBRICHACL
2873         struct richacl *richacl;
2874 #endif
2875 #if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_FREEBSD
2876         const char *acltext_posix1e = "user:1:rw-,"
2877             "group:15:r-x,"
2878             "user::rwx,"
2879             "group::rwx,"
2880             "other::r-x,"
2881             "mask::rwx";
2882 #elif ARCHIVE_ACL_SUNOS /* Solaris POSIX.1e */
2883         aclent_t aclp_posix1e[] = {
2884             { USER_OBJ, -1, 4 | 2 | 1 },
2885             { USER, 1, 4 | 2 },
2886             { GROUP_OBJ, -1, 4 | 2 | 1 },
2887             { GROUP, 15, 4 | 1 },
2888             { CLASS_OBJ, -1, 4 | 2 | 1 },
2889             { OTHER_OBJ, -1, 4 | 2 | 1 }
2890         };
2891 #endif
2892 #if ARCHIVE_ACL_FREEBSD /* FreeBSD NFS4 */
2893         const char *acltext_nfs4 = "user:1:rwpaRcs::allow:1,"
2894             "group:15:rxaRcs::allow:15,"
2895             "owner@:rwpxaARWcCos::allow,"
2896             "group@:rwpxaRcs::allow,"
2897             "everyone@:rxaRcs::allow";
2898 #elif ARCHIVE_ACL_LIBRICHACL
2899         const char *acltext_nfs4 = "owner:rwpxaARWcCoS::mask,"
2900             "group:rwpxaRcS::mask,"
2901             "other:rxaRcS::mask,"
2902             "user:1:rwpaRcS::allow,"
2903             "group:15:rxaRcS::allow,"
2904             "owner@:rwpxaARWcCoS::allow,"
2905             "group@:rwpxaRcS::allow,"
2906             "everyone@:rxaRcS::allow";
2907 #elif ARCHIVE_ACL_SUNOS_NFS4 /* Solaris NFS4 */
2908         ace_t aclp_nfs4[] = {
2909             { 1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |
2910               ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS | ACE_READ_ACL |
2911               ACE_SYNCHRONIZE, 0, ACE_ACCESS_ALLOWED_ACE_TYPE },
2912             { 15, ACE_READ_DATA | ACE_EXECUTE | ACE_READ_ATTRIBUTES |
2913               ACE_READ_NAMED_ATTRS | ACE_READ_ACL | ACE_SYNCHRONIZE,
2914               ACE_IDENTIFIER_GROUP, ACE_ACCESS_ALLOWED_ACE_TYPE },
2915             { -1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |
2916               ACE_EXECUTE | ACE_READ_ATTRIBUTES | ACE_WRITE_ATTRIBUTES |
2917               ACE_READ_NAMED_ATTRS | ACE_WRITE_NAMED_ATTRS |
2918               ACE_READ_ACL | ACE_WRITE_ACL | ACE_WRITE_OWNER | ACE_SYNCHRONIZE,
2919               ACE_OWNER, ACE_ACCESS_ALLOWED_ACE_TYPE },
2920             { -1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |
2921               ACE_EXECUTE | ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS |
2922               ACE_READ_ACL | ACE_SYNCHRONIZE, ACE_GROUP | ACE_IDENTIFIER_GROUP,
2923               ACE_ACCESS_ALLOWED_ACE_TYPE },
2924             { -1, ACE_READ_DATA | ACE_EXECUTE | ACE_READ_ATTRIBUTES |
2925               ACE_READ_NAMED_ATTRS | ACE_READ_ACL | ACE_SYNCHRONIZE,
2926               ACE_EVERYONE, ACE_ACCESS_ALLOWED_ACE_TYPE }
2927         };
2928 #elif ARCHIVE_ACL_DARWIN /* Mac OS X */
2929         acl_entry_t aclent;
2930         acl_permset_t permset;
2931         const uid_t uid = 1;
2932         uuid_t uuid;
2933         int i;
2934         const acl_perm_t acl_perms[] = {
2935                 ACL_READ_DATA,
2936                 ACL_WRITE_DATA,
2937                 ACL_APPEND_DATA,
2938                 ACL_EXECUTE,
2939                 ACL_READ_ATTRIBUTES,
2940                 ACL_READ_EXTATTRIBUTES,
2941                 ACL_READ_SECURITY,
2942 #if HAVE_DECL_ACL_SYNCHRONIZE
2943                 ACL_SYNCHRONIZE
2944 #endif
2945         };
2946 #endif /* ARCHIVE_ACL_DARWIN */
2947
2948 #if ARCHIVE_ACL_FREEBSD
2949         acl = acl_from_text(acltext_nfs4);
2950         failure("acl_from_text() error: %s", strerror(errno));
2951         if (assert(acl != NULL) == 0)
2952                 return (0);
2953 #elif ARCHIVE_ACL_LIBRICHACL
2954         richacl = richacl_from_text(acltext_nfs4, NULL, NULL);
2955         failure("richacl_from_text() error: %s", strerror(errno));
2956         if (assert(richacl != NULL) == 0)
2957                 return (0);
2958 #elif ARCHIVE_ACL_DARWIN
2959         acl = acl_init(1);
2960         failure("acl_init() error: %s", strerror(errno));
2961         if (assert(acl != NULL) == 0)
2962                 return (0);
2963         r = acl_create_entry(&acl, &aclent);
2964         failure("acl_create_entry() error: %s", strerror(errno));
2965         if (assertEqualInt(r, 0) == 0)
2966                 goto testacl_free;
2967         r = acl_set_tag_type(aclent, ACL_EXTENDED_ALLOW);
2968         failure("acl_set_tag_type() error: %s", strerror(errno));
2969         if (assertEqualInt(r, 0) == 0)
2970                 goto testacl_free;
2971         r = acl_get_permset(aclent, &permset);
2972         failure("acl_get_permset() error: %s", strerror(errno));
2973         if (assertEqualInt(r, 0) == 0)
2974                 goto testacl_free;
2975         for (i = 0; i < (int)(sizeof(acl_perms) / sizeof(acl_perms[0])); i++) {
2976                 r = acl_add_perm(permset, acl_perms[i]);
2977                 failure("acl_add_perm() error: %s", strerror(errno));
2978                 if (assertEqualInt(r, 0) == 0)
2979                         goto testacl_free;
2980         }
2981         r = acl_set_permset(aclent, permset);
2982         failure("acl_set_permset() error: %s", strerror(errno));
2983         if (assertEqualInt(r, 0) == 0)
2984                 goto testacl_free;
2985         r = mbr_uid_to_uuid(uid, uuid);
2986         failure("mbr_uid_to_uuid() error: %s", strerror(errno));
2987         if (assertEqualInt(r, 0) == 0)
2988                 goto testacl_free;
2989         r = acl_set_qualifier(aclent, uuid);
2990         failure("acl_set_qualifier() error: %s", strerror(errno));
2991         if (assertEqualInt(r, 0) == 0)
2992                 goto testacl_free;
2993 #endif /* ARCHIVE_ACL_DARWIN */
2994
2995 #if ARCHIVE_ACL_NFS4
2996 #if ARCHIVE_ACL_FREEBSD
2997         r = acl_set_file(path, ACL_TYPE_NFS4, acl);
2998         acl_free(acl);
2999 #elif ARCHIVE_ACL_LIBRICHACL
3000         r = richacl_set_file(path, richacl);
3001         richacl_free(richacl);
3002 #elif ARCHIVE_ACL_SUNOS_NFS4
3003         r = acl(path, ACE_SETACL,
3004             (int)(sizeof(aclp_nfs4)/sizeof(aclp_nfs4[0])), aclp_nfs4);
3005 #elif ARCHIVE_ACL_DARWIN
3006         r = acl_set_file(path, ACL_TYPE_EXTENDED, acl);
3007         acl_free(acl);
3008 #endif
3009         if (r == 0)
3010                 return (ARCHIVE_TEST_ACL_TYPE_NFS4);
3011 #endif  /* ARCHIVE_ACL_NFS4 */
3012
3013 #if ARCHIVE_ACL_POSIX1E
3014 #if ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_LIBACL
3015         acl = acl_from_text(acltext_posix1e);
3016         failure("acl_from_text() error: %s", strerror(errno));
3017         if (assert(acl != NULL) == 0)
3018                 return (0);
3019
3020         r = acl_set_file(path, ACL_TYPE_ACCESS, acl);
3021         acl_free(acl);
3022 #elif ARCHIVE_ACL_SUNOS
3023         r = acl(path, SETACL,
3024             (int)(sizeof(aclp_posix1e)/sizeof(aclp_posix1e[0])), aclp_posix1e);
3025 #endif
3026         if (r == 0)
3027                 return (ARCHIVE_TEST_ACL_TYPE_POSIX1E);
3028         else
3029                 return (0);
3030 #endif /* ARCHIVE_ACL_POSIX1E */
3031 #if ARCHIVE_ACL_DARWIN
3032 testacl_free:
3033         acl_free(acl);
3034 #endif
3035 #endif /* ARCHIVE_ACL_SUPPORT */
3036         (void)path;     /* UNUSED */
3037         return (0);
3038 }
3039
3040 /*
3041  * Sleep as needed; useful for verifying disk timestamp changes by
3042  * ensuring that the wall-clock time has actually changed before we
3043  * go back to re-read something from disk.
3044  */
3045 void
3046 sleepUntilAfter(time_t t)
3047 {
3048         while (t >= time(NULL))
3049 #if defined(_WIN32) && !defined(__CYGWIN__)
3050                 Sleep(500);
3051 #else
3052                 sleep(1);
3053 #endif
3054 }
3055
3056 /*
3057  * Call standard system() call, but build up the command line using
3058  * sprintf() conventions.
3059  */
3060 int
3061 systemf(const char *fmt, ...)
3062 {
3063         char buff[8192];
3064         va_list ap;
3065         int r;
3066
3067         va_start(ap, fmt);
3068         vsprintf(buff, fmt, ap);
3069         if (verbosity > VERBOSITY_FULL)
3070                 logprintf("Cmd: %s\n", buff);
3071         r = system(buff);
3072         va_end(ap);
3073         return (r);
3074 }
3075
3076 /*
3077  * Slurp a file into memory for ease of comparison and testing.
3078  * Returns size of file in 'sizep' if non-NULL, null-terminates
3079  * data in memory for ease of use.
3080  */
3081 char *
3082 slurpfile(size_t * sizep, const char *fmt, ...)
3083 {
3084         char filename[8192];
3085         struct stat st;
3086         va_list ap;
3087         char *p;
3088         ssize_t bytes_read;
3089         FILE *f;
3090         int r;
3091
3092         va_start(ap, fmt);
3093         vsprintf(filename, fmt, ap);
3094         va_end(ap);
3095
3096         f = fopen(filename, "rb");
3097         if (f == NULL) {
3098                 /* Note: No error; non-existent file is okay here. */
3099                 return (NULL);
3100         }
3101         r = fstat(fileno(f), &st);
3102         if (r != 0) {
3103                 logprintf("Can't stat file %s\n", filename);
3104                 fclose(f);
3105                 return (NULL);
3106         }
3107         p = malloc((size_t)st.st_size + 1);
3108         if (p == NULL) {
3109                 logprintf("Can't allocate %ld bytes of memory to read file %s\n",
3110                     (long int)st.st_size, filename);
3111                 fclose(f);
3112                 return (NULL);
3113         }
3114         bytes_read = fread(p, 1, (size_t)st.st_size, f);
3115         if (bytes_read < st.st_size) {
3116                 logprintf("Can't read file %s\n", filename);
3117                 fclose(f);
3118                 free(p);
3119                 return (NULL);
3120         }
3121         p[st.st_size] = '\0';
3122         if (sizep != NULL)
3123                 *sizep = (size_t)st.st_size;
3124         fclose(f);
3125         return (p);
3126 }
3127
3128 /*
3129  * Slurp a file into memory for ease of comparison and testing.
3130  * Returns size of file in 'sizep' if non-NULL, null-terminates
3131  * data in memory for ease of use.
3132  */
3133 void
3134 dumpfile(const char *filename, void *data, size_t len)
3135 {
3136         ssize_t bytes_written;
3137         FILE *f;
3138
3139         f = fopen(filename, "wb");
3140         if (f == NULL) {
3141                 logprintf("Can't open file %s for writing\n", filename);
3142                 return;
3143         }
3144         bytes_written = fwrite(data, 1, len, f);
3145         if (bytes_written < (ssize_t)len)
3146                 logprintf("Can't write file %s\n", filename);
3147         fclose(f);
3148 }
3149
3150 /* Read a uuencoded file from the reference directory, decode, and
3151  * write the result into the current directory. */
3152 #define VALID_UUDECODE(c) (c >= 32 && c <= 96)
3153 #define UUDECODE(c) (((c) - 0x20) & 0x3f)
3154 void
3155 extract_reference_file(const char *name)
3156 {
3157         char buff[1024];
3158         FILE *in, *out;
3159
3160         sprintf(buff, "%s/%s.uu", refdir, name);
3161         in = fopen(buff, "r");
3162         failure("Couldn't open reference file %s", buff);
3163         assert(in != NULL);
3164         if (in == NULL)
3165                 return;
3166         /* Read up to and including the 'begin' line. */
3167         for (;;) {
3168                 if (fgets(buff, sizeof(buff), in) == NULL) {
3169                         /* TODO: This is a failure. */
3170                         return;
3171                 }
3172                 if (memcmp(buff, "begin ", 6) == 0)
3173                         break;
3174         }
3175         /* Now, decode the rest and write it. */
3176         out = fopen(name, "wb");
3177         while (fgets(buff, sizeof(buff), in) != NULL) {
3178                 char *p = buff;
3179                 int bytes;
3180
3181                 if (memcmp(buff, "end", 3) == 0)
3182                         break;
3183
3184                 bytes = UUDECODE(*p++);
3185                 while (bytes > 0) {
3186                         int n = 0;
3187                         /* Write out 1-3 bytes from that. */
3188                         if (bytes > 0) {
3189                                 assert(VALID_UUDECODE(p[0]));
3190                                 assert(VALID_UUDECODE(p[1]));
3191                                 n = UUDECODE(*p++) << 18;
3192                                 n |= UUDECODE(*p++) << 12;
3193                                 fputc(n >> 16, out);
3194                                 --bytes;
3195                         }
3196                         if (bytes > 0) {
3197                                 assert(VALID_UUDECODE(p[0]));
3198                                 n |= UUDECODE(*p++) << 6;
3199                                 fputc((n >> 8) & 0xFF, out);
3200                                 --bytes;
3201                         }
3202                         if (bytes > 0) {
3203                                 assert(VALID_UUDECODE(p[0]));
3204                                 n |= UUDECODE(*p++);
3205                                 fputc(n & 0xFF, out);
3206                                 --bytes;
3207                         }
3208                 }
3209         }
3210         fclose(out);
3211         fclose(in);
3212 }
3213
3214 void
3215 copy_reference_file(const char *name)
3216 {
3217         char buff[1024];
3218         FILE *in, *out;
3219         size_t rbytes;
3220
3221         sprintf(buff, "%s/%s", refdir, name);
3222         in = fopen(buff, "rb");
3223         failure("Couldn't open reference file %s", buff);
3224         assert(in != NULL);
3225         if (in == NULL)
3226                 return;
3227         /* Now, decode the rest and write it. */
3228         /* Not a lot of error checking here; the input better be right. */
3229         out = fopen(name, "wb");
3230         while ((rbytes = fread(buff, 1, sizeof(buff), in)) > 0) {
3231                 if (fwrite(buff, 1, rbytes, out) != rbytes) {
3232                         logprintf("Error: fwrite\n");
3233                         break;
3234                 }
3235         }
3236         fclose(out);
3237         fclose(in);
3238 }
3239
3240 int
3241 is_LargeInode(const char *file)
3242 {
3243 #if defined(_WIN32) && !defined(__CYGWIN__)
3244         BY_HANDLE_FILE_INFORMATION bhfi;
3245         int r;
3246
3247         r = my_GetFileInformationByName(file, &bhfi);
3248         if (r != 0)
3249                 return (0);
3250         return (bhfi.nFileIndexHigh & 0x0000FFFFUL);
3251 #else
3252         struct stat st;
3253         int64_t ino;
3254
3255         if (stat(file, &st) < 0)
3256                 return (0);
3257         ino = (int64_t)st.st_ino;
3258         return (ino > 0xffffffff);
3259 #endif
3260 }
3261
3262 void
3263 extract_reference_files(const char **names)
3264 {
3265         while (names && *names)
3266                 extract_reference_file(*names++);
3267 }
3268
3269 #ifndef PROGRAM
3270 /* Set ACLs */
3271 int
3272 assertion_entry_set_acls(const char *file, int line, struct archive_entry *ae,
3273     struct archive_test_acl_t *acls, int n)
3274 {
3275         int i, r, ret;
3276
3277         assertion_count(file, line);
3278
3279         ret = 0;
3280         archive_entry_acl_clear(ae);
3281         for (i = 0; i < n; i++) {
3282                 r = archive_entry_acl_add_entry(ae,
3283                     acls[i].type, acls[i].permset, acls[i].tag,
3284                     acls[i].qual, acls[i].name);
3285                 if (r != 0) {
3286                         ret = 1;
3287                         failure_start(file, line, "type=%#010x, "
3288                             "permset=%#010x, tag=%d, qual=%d name=%s",
3289                             acls[i].type, acls[i].permset, acls[i].tag,
3290                             acls[i].qual, acls[i].name);
3291                         failure_finish(NULL);
3292                 }
3293         }
3294
3295         return (ret);
3296 }
3297
3298 static int
3299 archive_test_acl_match(struct archive_test_acl_t *acl, int type, int permset,
3300     int tag, int qual, const char *name)
3301 {
3302         if (type != acl->type)
3303                 return (0);
3304         if (permset != acl->permset)
3305                 return (0);
3306         if (tag != acl->tag)
3307                 return (0);
3308         if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ)
3309                 return (1);
3310         if (tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ)
3311                 return (1);
3312         if (tag == ARCHIVE_ENTRY_ACL_EVERYONE)
3313                 return (1);
3314         if (tag == ARCHIVE_ENTRY_ACL_OTHER)
3315                 return (1);
3316         if (qual != acl->qual)
3317                 return (0);
3318         if (name == NULL) {
3319                 if (acl->name == NULL || acl->name[0] == '\0')
3320                         return (1);
3321                 return (0);
3322         }
3323         if (acl->name == NULL) {
3324                 if (name[0] == '\0')
3325                         return (1);
3326                 return (0);
3327         }
3328         return (0 == strcmp(name, acl->name));
3329 }
3330
3331 /* Compare ACLs */
3332 int
3333 assertion_entry_compare_acls(const char *file, int line,
3334     struct archive_entry *ae, struct archive_test_acl_t *acls, int cnt,
3335     int want_type, int mode)
3336 {
3337         int *marker;
3338         int i, r, n, ret;
3339         int type, permset, tag, qual;
3340         int matched;
3341         const char *name;
3342
3343         assertion_count(file, line);
3344
3345         ret = 0;
3346         n = 0;
3347         marker = malloc(sizeof(marker[0]) * cnt);
3348
3349         for (i = 0; i < cnt; i++) {
3350                 if ((acls[i].type & want_type) != 0) {
3351                         marker[n] = i;
3352                         n++;
3353                 }
3354         }
3355
3356         if (n == 0) {
3357                 failure_start(file, line, "No ACL's to compare, type mask: %d",
3358                     want_type);
3359                 return (1);
3360         }
3361
3362         while (0 == (r = archive_entry_acl_next(ae, want_type,
3363                          &type, &permset, &tag, &qual, &name))) {
3364                 for (i = 0, matched = 0; i < n && !matched; i++) {
3365                         if (archive_test_acl_match(&acls[marker[i]], type,
3366                             permset, tag, qual, name)) {
3367                                 /* We found a match; remove it. */
3368                                 marker[i] = marker[n - 1];
3369                                 n--;
3370                                 matched = 1;
3371                         }
3372                 }
3373                 if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS
3374                     && tag == ARCHIVE_ENTRY_ACL_USER_OBJ) {
3375                         if (!matched) {
3376                                 failure_start(file, line, "No match for "
3377                                     "user_obj perm");
3378                                 failure_finish(NULL);
3379                                 ret = 1;
3380                         }
3381                         if ((permset << 6) != (mode & 0700)) {
3382                                 failure_start(file, line, "USER_OBJ permset "
3383                                     "(%02o) != user mode (%02o)", permset,
3384                                     07 & (mode >> 6));
3385                                 failure_finish(NULL);
3386                                 ret = 1;
3387                         }
3388                 } else if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS
3389                     && tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ) {
3390                         if (!matched) {
3391                                 failure_start(file, line, "No match for "
3392                                     "group_obj perm");
3393                                 failure_finish(NULL);
3394                                 ret = 1;
3395                         }
3396                         if ((permset << 3) != (mode & 0070)) {
3397                                 failure_start(file, line, "GROUP_OBJ permset "
3398                                     "(%02o) != group mode (%02o)", permset,
3399                                     07 & (mode >> 3));
3400                                 failure_finish(NULL);
3401                                 ret = 1;
3402                         }
3403                 } else if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS
3404                     && tag == ARCHIVE_ENTRY_ACL_OTHER) {
3405                         if (!matched) {
3406                                 failure_start(file, line, "No match for "
3407                                     "other perm");
3408                                 failure_finish(NULL);
3409                                 ret = 1;
3410                         }
3411                         if ((permset << 0) != (mode & 0007)) {
3412                                 failure_start(file, line, "OTHER permset "
3413                                     "(%02o) != other mode (%02o)", permset,
3414                                     mode & 07);
3415                                 failure_finish(NULL);
3416                                 ret = 1;
3417                         }
3418                 } else if (matched != 1) {
3419                         failure_start(file, line, "Could not find match for "
3420                             "ACL (type=%#010x,permset=%#010x,tag=%d,qual=%d,"
3421                             "name=``%s'')", type, permset, tag, qual, name);
3422                         failure_finish(NULL);
3423                         ret = 1;
3424                 }
3425         }
3426         if (r != ARCHIVE_EOF) {
3427                 failure_start(file, line, "Should not exit before EOF");
3428                 failure_finish(NULL);
3429                 ret = 1;
3430         }
3431         if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0 &&
3432             (mode_t)(mode & 0777) != (archive_entry_mode(ae) & 0777)) {
3433                 failure_start(file, line, "Mode (%02o) and entry mode (%02o) "
3434                     "mismatch", mode, archive_entry_mode(ae));
3435                 failure_finish(NULL);
3436                 ret = 1;
3437         }
3438         if (n != 0) {
3439                 failure_start(file, line, "Could not find match for ACL "
3440                     "(type=%#010x,permset=%#010x,tag=%d,qual=%d,name=``%s'')",
3441                     acls[marker[0]].type, acls[marker[0]].permset,
3442                     acls[marker[0]].tag, acls[marker[0]].qual,
3443                     acls[marker[0]].name);
3444                 failure_finish(NULL);
3445                 ret = 1;
3446                 /* Number of ACLs not matched should == 0 */
3447         }
3448         free(marker);
3449         return (ret);
3450 }
3451 #endif  /* !defined(PROGRAM) */
3452
3453 /*
3454  *
3455  * TEST management
3456  *
3457  */
3458
3459 /*
3460  * "list.h" is simply created by "grep DEFINE_TEST test_*.c"; it has
3461  * a line like
3462  *      DEFINE_TEST(test_function)
3463  * for each test.
3464  */
3465
3466 /* Use "list.h" to declare all of the test functions. */
3467 #undef DEFINE_TEST
3468 #define DEFINE_TEST(name) void name(void);
3469 #include "list.h"
3470
3471 /* Use "list.h" to create a list of all tests (functions and names). */
3472 #undef DEFINE_TEST
3473 #define DEFINE_TEST(n) { n, #n, 0 },
3474 struct test_list_t tests[] = {
3475         #include "list.h"
3476 };
3477
3478 /*
3479  * Summarize repeated failures in the just-completed test.
3480  */
3481 static void
3482 test_summarize(int failed, int skips_num)
3483 {
3484         unsigned int i;
3485
3486         switch (verbosity) {
3487         case VERBOSITY_SUMMARY_ONLY:
3488                 printf(failed ? "E" : ".");
3489                 fflush(stdout);
3490                 break;
3491         case VERBOSITY_PASSFAIL:
3492                 printf(failed ? "FAIL\n" : skips_num ? "ok (S)\n" : "ok\n");
3493                 break;
3494         }
3495
3496         log_console = (verbosity == VERBOSITY_LIGHT_REPORT);
3497
3498         for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {
3499                 if (failed_lines[i].count > 1 && !failed_lines[i].skip)
3500                         logprintf("%s:%d: Summary: Failed %d times\n",
3501                             failed_filename, i, failed_lines[i].count);
3502         }
3503         /* Clear the failure history for the next file. */
3504         failed_filename = NULL;
3505         memset(failed_lines, 0, sizeof(failed_lines));
3506 }
3507
3508 /*
3509  * Actually run a single test, with appropriate setup and cleanup.
3510  */
3511 static int
3512 test_run(int i, const char *tmpdir)
3513 {
3514 #ifdef PATH_MAX
3515         char workdir[PATH_MAX * 2];
3516 #else
3517         char workdir[1024 * 2];
3518 #endif
3519         char logfilename[64];
3520         int failures_before = failures;
3521         int skips_before = skips;
3522         int oldumask;
3523
3524         switch (verbosity) {
3525         case VERBOSITY_SUMMARY_ONLY: /* No per-test reports at all */
3526                 break;
3527         case VERBOSITY_PASSFAIL: /* rest of line will include ok/FAIL marker */
3528                 printf("%3d: %-64s", i, tests[i].name);
3529                 fflush(stdout);
3530                 break;
3531         default: /* Title of test, details will follow */
3532                 printf("%3d: %s\n", i, tests[i].name);
3533         }
3534
3535         /* Chdir to the top-level work directory. */
3536         if (!assertChdir(tmpdir)) {
3537                 fprintf(stderr,
3538                     "ERROR: Can't chdir to top work dir %s\n", tmpdir);
3539                 exit(1);
3540         }
3541         /* Create a log file for this test. */
3542         sprintf(logfilename, "%s.log", tests[i].name);
3543         logfile = fopen(logfilename, "w");
3544         fprintf(logfile, "%s\n\n", tests[i].name);
3545         /* Chdir() to a work dir for this specific test. */
3546         snprintf(workdir, sizeof(workdir), "%s/%s", tmpdir, tests[i].name);
3547         testworkdir = workdir;
3548         if (!assertMakeDir(testworkdir, 0755)
3549             || !assertChdir(testworkdir)) {
3550                 fprintf(stderr,
3551                     "ERROR: Can't chdir to work dir %s\n", testworkdir);
3552                 exit(1);
3553         }
3554         /* Explicitly reset the locale before each test. */
3555         setlocale(LC_ALL, "C");
3556         /* Record the umask before we run the test. */
3557         umask(oldumask = umask(0));
3558         /*
3559          * Run the actual test.
3560          */
3561         (*tests[i].func)();
3562         /*
3563          * Clean up and report afterwards.
3564          */
3565         testworkdir = NULL;
3566         /* Restore umask */
3567         umask(oldumask);
3568         /* Reset locale. */
3569         setlocale(LC_ALL, "C");
3570         /* Reset directory. */
3571         if (!assertChdir(tmpdir)) {
3572                 fprintf(stderr, "ERROR: Couldn't chdir to temp dir %s\n",
3573                     tmpdir);
3574                 exit(1);
3575         }
3576         /* Report per-test summaries. */
3577         tests[i].failures = failures - failures_before;
3578         test_summarize(tests[i].failures, skips - skips_before);
3579         /* Close the per-test log file. */
3580         fclose(logfile);
3581         logfile = NULL;
3582         /* If there were no failures, we can remove the work dir and logfile. */
3583         if (tests[i].failures == 0) {
3584                 if (!keep_temp_files && assertChdir(tmpdir)) {
3585 #if defined(_WIN32) && !defined(__CYGWIN__)
3586                         /* Make sure not to leave empty directories.
3587                          * Sometimes a processing of closing files used by tests
3588                          * is not done, then rmdir will be failed and it will
3589                          * leave a empty test directory. So we should wait a few
3590                          * seconds and retry rmdir. */
3591                         int r, t;
3592                         for (t = 0; t < 10; t++) {
3593                                 if (t > 0)
3594                                         Sleep(1000);
3595                                 r = systemf("rmdir /S /Q %s", tests[i].name);
3596                                 if (r == 0)
3597                                         break;
3598                         }
3599                         systemf("del %s", logfilename);
3600 #else
3601                         systemf("rm -rf %s", tests[i].name);
3602                         systemf("rm %s", logfilename);
3603 #endif
3604                 }
3605         }
3606         /* Return appropriate status. */
3607         return (tests[i].failures);
3608 }
3609
3610 /*
3611  *
3612  *
3613  * MAIN and support routines.
3614  *
3615  *
3616  */
3617
3618 static void
3619 usage(const char *program)
3620 {
3621         static const int limit = sizeof(tests) / sizeof(tests[0]);
3622         int i;
3623
3624         printf("Usage: %s [options] <test> <test> ...\n", program);
3625         printf("Default is to run all tests.\n");
3626         printf("Otherwise, specify the numbers of the tests you wish to run.\n");
3627         printf("Options:\n");
3628         printf("  -d  Dump core after any failure, for debugging.\n");
3629         printf("  -k  Keep all temp files.\n");
3630         printf("      Default: temp files for successful tests deleted.\n");
3631 #ifdef PROGRAM
3632         printf("  -p <path>  Path to executable to be tested.\n");
3633         printf("      Default: path taken from " ENVBASE " environment variable.\n");
3634 #endif
3635         printf("  -q  Quiet.\n");
3636         printf("  -r <dir>   Path to dir containing reference files.\n");
3637         printf("      Default: Current directory.\n");
3638         printf("  -u  Keep running specifies tests until one fails.\n");
3639         printf("  -v  Verbose.\n");
3640         printf("Available tests:\n");
3641         for (i = 0; i < limit; i++)
3642                 printf("  %d: %s\n", i, tests[i].name);
3643         exit(1);
3644 }
3645
3646 static char *
3647 get_refdir(const char *d)
3648 {
3649         size_t tried_size, buff_size;
3650         char *buff, *tried, *pwd = NULL, *p = NULL;
3651
3652 #ifdef PATH_MAX
3653         buff_size = PATH_MAX;
3654 #else
3655         buff_size = 8192;
3656 #endif
3657         buff = calloc(buff_size, 1);
3658         if (buff == NULL) {
3659                 fprintf(stderr, "Unable to allocate memory\n");
3660                 exit(1);
3661         }
3662
3663         /* Allocate a buffer to hold the various directories we checked. */
3664         tried_size = buff_size * 2;
3665         tried = calloc(tried_size, 1);
3666         if (tried == NULL) {
3667                 fprintf(stderr, "Unable to allocate memory\n");
3668                 exit(1);
3669         }
3670
3671         /* If a dir was specified, try that */
3672         if (d != NULL) {
3673                 pwd = NULL;
3674                 snprintf(buff, buff_size, "%s", d);
3675                 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3676                 if (p != NULL) goto success;
3677                 strncat(tried, buff, tried_size - strlen(tried) - 1);
3678                 strncat(tried, "\n", tried_size - strlen(tried) - 1);
3679                 goto failure;
3680         }
3681
3682         /* Get the current dir. */
3683 #ifdef PATH_MAX
3684         pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */
3685 #else
3686         pwd = getcwd(NULL, 0);
3687 #endif
3688         while (pwd[strlen(pwd) - 1] == '\n')
3689                 pwd[strlen(pwd) - 1] = '\0';
3690
3691         /* Look for a known file. */
3692         snprintf(buff, buff_size, "%s", pwd);
3693         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3694         if (p != NULL) goto success;
3695         strncat(tried, buff, tried_size - strlen(tried) - 1);
3696         strncat(tried, "\n", tried_size - strlen(tried) - 1);
3697
3698         snprintf(buff, buff_size, "%s/test", pwd);
3699         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3700         if (p != NULL) goto success;
3701         strncat(tried, buff, tried_size - strlen(tried) - 1);
3702         strncat(tried, "\n", tried_size - strlen(tried) - 1);
3703
3704 #if defined(LIBRARY)
3705         snprintf(buff, buff_size, "%s/%s/test", pwd, LIBRARY);
3706 #else
3707         snprintf(buff, buff_size, "%s/%s/test", pwd, PROGRAM);
3708 #endif
3709         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3710         if (p != NULL) goto success;
3711         strncat(tried, buff, tried_size - strlen(tried) - 1);
3712         strncat(tried, "\n", tried_size - strlen(tried) - 1);
3713
3714 #if defined(PROGRAM_ALIAS)
3715         snprintf(buff, buff_size, "%s/%s/test", pwd, PROGRAM_ALIAS);
3716         p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3717         if (p != NULL) goto success;
3718         strncat(tried, buff, tried_size - strlen(tried) - 1);
3719         strncat(tried, "\n", tried_size - strlen(tried) - 1);
3720 #endif
3721
3722         if (memcmp(pwd, "/usr/obj", 8) == 0) {
3723                 snprintf(buff, buff_size, "%s", pwd + 8);
3724                 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3725                 if (p != NULL) goto success;
3726                 strncat(tried, buff, tried_size - strlen(tried) - 1);
3727                 strncat(tried, "\n", tried_size - strlen(tried) - 1);
3728
3729                 snprintf(buff, buff_size, "%s/test", pwd + 8);
3730                 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3731                 if (p != NULL) goto success;
3732                 strncat(tried, buff, tried_size - strlen(tried) - 1);
3733                 strncat(tried, "\n", tried_size - strlen(tried) - 1);
3734         }
3735
3736 failure:
3737         printf("Unable to locate known reference file %s\n", KNOWNREF);
3738         printf("  Checked following directories:\n%s\n", tried);
3739         printf("Use -r option to specify full path to reference directory\n");
3740 #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
3741         DebugBreak();
3742 #endif
3743         exit(1);
3744
3745 success:
3746         free(p);
3747         free(pwd);
3748         free(tried);
3749
3750         /* Copy result into a fresh buffer to reduce memory usage. */
3751         p = strdup(buff);
3752         free(buff);
3753         return p;
3754 }
3755
3756 int
3757 main(int argc, char **argv)
3758 {
3759         static const int limit = sizeof(tests) / sizeof(tests[0]);
3760         int test_set[sizeof(tests) / sizeof(tests[0])];
3761         int i = 0, j = 0, tests_run = 0, tests_failed = 0, option;
3762         time_t now;
3763         char *refdir_alloc = NULL;
3764         const char *progname;
3765         char **saved_argv;
3766         const char *tmp, *option_arg, *p;
3767 #ifdef PATH_MAX
3768         char tmpdir[PATH_MAX];
3769 #else
3770         char tmpdir[256];
3771 #endif
3772         char *pwd, *testprogdir, *tmp2 = NULL, *vlevel = NULL;
3773         char tmpdir_timestamp[32];
3774
3775         (void)argc; /* UNUSED */
3776
3777         /* Get the current dir. */
3778 #ifdef PATH_MAX
3779         pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */
3780 #else
3781         pwd = getcwd(NULL, 0);
3782 #endif
3783         while (pwd[strlen(pwd) - 1] == '\n')
3784                 pwd[strlen(pwd) - 1] = '\0';
3785
3786 #if defined(HAVE__CrtSetReportMode) && !defined(__WATCOMC__)
3787         /* To stop to run the default invalid parameter handler. */
3788         _set_invalid_parameter_handler(invalid_parameter_handler);
3789         /* Disable annoying assertion message box. */
3790         _CrtSetReportMode(_CRT_ASSERT, 0);
3791 #endif
3792
3793         /*
3794          * Name of this program, used to build root of our temp directory
3795          * tree.
3796          */
3797         progname = p = argv[0];
3798         if ((testprogdir = (char *)malloc(strlen(progname) + 1)) == NULL)
3799         {
3800                 fprintf(stderr, "ERROR: Out of memory.");
3801                 exit(1);
3802         }
3803         strcpy(testprogdir, progname);
3804         while (*p != '\0') {
3805                 /* Support \ or / dir separators for Windows compat. */
3806                 if (*p == '/' || *p == '\\')
3807                 {
3808                         progname = p + 1;
3809                         i = j;
3810                 }
3811                 ++p;
3812                 j++;
3813         }
3814         testprogdir[i] = '\0';
3815 #if defined(_WIN32) && !defined(__CYGWIN__)
3816         if (testprogdir[0] != '/' && testprogdir[0] != '\\' &&
3817             !(((testprogdir[0] >= 'a' && testprogdir[0] <= 'z') ||
3818                (testprogdir[0] >= 'A' && testprogdir[0] <= 'Z')) &&
3819                 testprogdir[1] == ':' &&
3820                 (testprogdir[2] == '/' || testprogdir[2] == '\\')))
3821 #else
3822         if (testprogdir[0] != '/')
3823 #endif
3824         {
3825                 /* Fixup path for relative directories. */
3826                 if ((testprogdir = (char *)realloc(testprogdir,
3827                         strlen(pwd) + 1 + strlen(testprogdir) + 1)) == NULL)
3828                 {
3829                         fprintf(stderr, "ERROR: Out of memory.");
3830                         exit(1);
3831                 }
3832                 memmove(testprogdir + strlen(pwd) + 1, testprogdir,
3833                     strlen(testprogdir) + 1);
3834                 memcpy(testprogdir, pwd, strlen(pwd));
3835                 testprogdir[strlen(pwd)] = '/';
3836         }
3837
3838 #ifdef PROGRAM
3839         /* Get the target program from environment, if available. */
3840         testprogfile = getenv(ENVBASE);
3841 #endif
3842
3843         if (getenv("TMPDIR") != NULL)
3844                 tmp = getenv("TMPDIR");
3845         else if (getenv("TMP") != NULL)
3846                 tmp = getenv("TMP");
3847         else if (getenv("TEMP") != NULL)
3848                 tmp = getenv("TEMP");
3849         else if (getenv("TEMPDIR") != NULL)
3850                 tmp = getenv("TEMPDIR");
3851         else
3852                 tmp = "/tmp";
3853
3854         /* Allow -d to be controlled through the environment. */
3855         if (getenv(ENVBASE "_DEBUG") != NULL)
3856                 dump_on_failure = 1;
3857
3858         /* Allow -v to be controlled through the environment. */
3859         if (getenv("_VERBOSITY_LEVEL") != NULL)
3860         {
3861                 vlevel = getenv("_VERBOSITY_LEVEL");
3862                 verbosity = atoi(vlevel);
3863                 if (verbosity < VERBOSITY_SUMMARY_ONLY || verbosity > VERBOSITY_FULL)
3864                 {
3865                         /* Unsupported verbosity levels are silently ignored */
3866                         vlevel = NULL;
3867                         verbosity = VERBOSITY_PASSFAIL;
3868                 }
3869         }
3870
3871         /* Get the directory holding test files from environment. */
3872         refdir = getenv(ENVBASE "_TEST_FILES");
3873
3874         /*
3875          * Parse options, without using getopt(), which isn't available
3876          * on all platforms.
3877          */
3878         ++argv; /* Skip program name */
3879         while (*argv != NULL) {
3880                 if (**argv != '-')
3881                         break;
3882                 p = *argv++;
3883                 ++p; /* Skip '-' */
3884                 while (*p != '\0') {
3885                         option = *p++;
3886                         option_arg = NULL;
3887                         /* If 'opt' takes an argument, parse that. */
3888                         if (option == 'p' || option == 'r') {
3889                                 if (*p != '\0')
3890                                         option_arg = p;
3891                                 else if (*argv == NULL) {
3892                                         fprintf(stderr,
3893                                             "Option -%c requires argument.\n",
3894                                             option);
3895                                         usage(progname);
3896                                 } else
3897                                         option_arg = *argv++;
3898                                 p = ""; /* End of this option word. */
3899                         }
3900
3901                         /* Now, handle the option. */
3902                         switch (option) {
3903                         case 'd':
3904                                 dump_on_failure = 1;
3905                                 break;
3906                         case 'k':
3907                                 keep_temp_files = 1;
3908                                 break;
3909                         case 'p':
3910 #ifdef PROGRAM
3911                                 testprogfile = option_arg;
3912 #else
3913                                 fprintf(stderr, "-p option not permitted\n");
3914                                 usage(progname);
3915 #endif
3916                                 break;
3917                         case 'q':
3918                                 if (!vlevel)
3919                                         verbosity--;
3920                                 break;
3921                         case 'r':
3922                                 refdir = option_arg;
3923                                 break;
3924                         case 'u':
3925                                 until_failure++;
3926                                 break;
3927                         case 'v':
3928                                 if (!vlevel)
3929                                         verbosity++;
3930                                 break;
3931                         default:
3932                                 fprintf(stderr, "Unrecognized option '%c'\n",
3933                                     option);
3934                                 usage(progname);
3935                         }
3936                 }
3937         }
3938
3939         /*
3940          * Sanity-check that our options make sense.
3941          */
3942 #ifdef PROGRAM
3943         if (testprogfile == NULL)
3944         {
3945                 if ((tmp2 = (char *)malloc(strlen(testprogdir) + 1 +
3946                         strlen(PROGRAM) + 1)) == NULL)
3947                 {
3948                         fprintf(stderr, "ERROR: Out of memory.");
3949                         exit(1);
3950                 }
3951                 strcpy(tmp2, testprogdir);
3952                 strcat(tmp2, "/");
3953                 strcat(tmp2, PROGRAM);
3954                 testprogfile = tmp2;
3955         }
3956
3957         {
3958                 char *testprg;
3959 #if defined(_WIN32) && !defined(__CYGWIN__)
3960                 /* Command.com sometimes rejects '/' separators. */
3961                 testprg = strdup(testprogfile);
3962                 for (i = 0; testprg[i] != '\0'; i++) {
3963                         if (testprg[i] == '/')
3964                                 testprg[i] = '\\';
3965                 }
3966                 testprogfile = testprg;
3967 #endif
3968                 /* Quote the name that gets put into shell command lines. */
3969                 testprg = malloc(strlen(testprogfile) + 3);
3970                 strcpy(testprg, "\"");
3971                 strcat(testprg, testprogfile);
3972                 strcat(testprg, "\"");
3973                 testprog = testprg;
3974         }
3975 #endif
3976
3977 #if !defined(_WIN32) && defined(SIGPIPE)
3978         {   /* Ignore SIGPIPE signals */
3979                 struct sigaction sa;
3980                 sa.sa_handler = SIG_IGN;
3981                 sigemptyset(&sa.sa_mask);
3982                 sa.sa_flags = 0;
3983                 sigaction(SIGPIPE, &sa, NULL);
3984         }
3985 #endif
3986
3987         /*
3988          * Create a temp directory for the following tests.
3989          * Include the time the tests started as part of the name,
3990          * to make it easier to track the results of multiple tests.
3991          */
3992         now = time(NULL);
3993         for (i = 0; ; i++) {
3994                 strftime(tmpdir_timestamp, sizeof(tmpdir_timestamp),
3995                     "%Y-%m-%dT%H.%M.%S",
3996                     localtime(&now));
3997                 if ((strlen(tmp) + 1 + strlen(progname) + 1 +
3998                     strlen(tmpdir_timestamp) + 1 + 3) >
3999                     (sizeof(tmpdir) / sizeof(char))) {
4000                         fprintf(stderr,
4001                             "ERROR: Temp directory pathname too long\n");
4002                         exit(1);
4003                 }
4004                 snprintf(tmpdir, sizeof(tmpdir), "%s/%s.%s-%03d", tmp,
4005                     progname, tmpdir_timestamp, i);
4006                 if (assertMakeDir(tmpdir,0755))
4007                         break;
4008                 if (i >= 999) {
4009                         fprintf(stderr,
4010                             "ERROR: Unable to create temp directory %s\n",
4011                             tmpdir);
4012                         exit(1);
4013                 }
4014         }
4015
4016         /*
4017          * If the user didn't specify a directory for locating
4018          * reference files, try to find the reference files in
4019          * the "usual places."
4020          */
4021         refdir = refdir_alloc = get_refdir(refdir);
4022
4023         /*
4024          * Banner with basic information.
4025          */
4026         printf("\n");
4027         printf("If tests fail or crash, details will be in:\n");
4028         printf("   %s\n", tmpdir);
4029         printf("\n");
4030         if (verbosity > VERBOSITY_SUMMARY_ONLY) {
4031                 printf("Reference files will be read from: %s\n", refdir);
4032 #ifdef PROGRAM
4033                 printf("Running tests on: %s\n", testprog);
4034 #endif
4035                 printf("Exercising: ");
4036                 fflush(stdout);
4037                 printf("%s\n", EXTRA_VERSION);
4038         } else {
4039                 printf("Running ");
4040                 fflush(stdout);
4041         }
4042
4043         /*
4044          * Run some or all of the individual tests.
4045          */
4046         saved_argv = argv;
4047         do {
4048                 argv = saved_argv;
4049                 do {
4050                         int test_num;
4051
4052                         test_num = get_test_set(test_set, limit, *argv, tests);
4053                         if (test_num < 0) {
4054                                 printf("*** INVALID Test %s\n", *argv);
4055                                 free(refdir_alloc);
4056                                 free(testprogdir);
4057                                 usage(progname);
4058                                 return (1);
4059                         }
4060                         for (i = 0; i < test_num; i++) {
4061                                 tests_run++;
4062                                 if (test_run(test_set[i], tmpdir)) {
4063                                         tests_failed++;
4064                                         if (until_failure)
4065                                                 goto finish;
4066                                 }
4067                         }
4068                         if (*argv != NULL)
4069                                 argv++;
4070                 } while (*argv != NULL);
4071         } while (until_failure);
4072
4073 finish:
4074         /* Must be freed after all tests run */
4075         free(tmp2);
4076         free(testprogdir);
4077         free(pwd);
4078
4079         /*
4080          * Report summary statistics.
4081          */
4082         if (verbosity > VERBOSITY_SUMMARY_ONLY) {
4083                 printf("\n");
4084                 printf("Totals:\n");
4085                 printf("  Tests run:         %8d\n", tests_run);
4086                 printf("  Tests failed:      %8d\n", tests_failed);
4087                 printf("  Assertions checked:%8d\n", assertions);
4088                 printf("  Assertions failed: %8d\n", failures);
4089                 printf("  Skips reported:    %8d\n", skips);
4090         }
4091         if (failures) {
4092                 printf("\n");
4093                 printf("Failing tests:\n");
4094                 for (i = 0; i < limit; ++i) {
4095                         if (tests[i].failures)
4096                                 printf("  %d: %s (%d failures)\n", i,
4097                                     tests[i].name, tests[i].failures);
4098                 }
4099                 printf("\n");
4100                 printf("Details for failing tests: %s\n", tmpdir);
4101                 printf("\n");
4102         } else {
4103                 if (verbosity == VERBOSITY_SUMMARY_ONLY)
4104                         printf("\n");
4105                 printf("%d tests passed, no failures\n", tests_run);
4106         }
4107
4108         free(refdir_alloc);
4109
4110         /* If the final tmpdir is empty, we can remove it. */
4111         /* This should be the usual case when all tests succeed. */
4112         assertChdir("..");
4113         rmdir(tmpdir);
4114
4115         return (tests_failed ? 1 : 0);
4116 }