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