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