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