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