1228753Smm/*
2228753Smm * Copyright (c) 2003-2009 Tim Kientzle
3228753Smm * All rights reserved.
4228753Smm *
5228753Smm * Redistribution and use in source and binary forms, with or without
6228753Smm * modification, are permitted provided that the following conditions
7228753Smm * are met:
8228753Smm * 1. Redistributions of source code must retain the above copyright
9228753Smm *    notice, this list of conditions and the following disclaimer.
10228753Smm * 2. Redistributions in binary form must reproduce the above copyright
11228753Smm *    notice, this list of conditions and the following disclaimer in the
12228753Smm *    documentation and/or other materials provided with the distribution.
13228753Smm *
14228753Smm * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15228753Smm * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16228753Smm * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17228753Smm * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18228753Smm * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19228753Smm * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20228753Smm * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21228753Smm * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22228753Smm * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23228753Smm * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24228753Smm */
25228753Smm
26228753Smm#include "test.h"
27248590Smm#include "test_utils.h"
28238825Smm#ifdef HAVE_SYS_IOCTL_H
29238825Smm#include <sys/ioctl.h>
30238825Smm#endif
31231200Smm#ifdef HAVE_SYS_TIME_H
32231200Smm#include <sys/time.h>
33231200Smm#endif
34228753Smm#include <errno.h>
35231200Smm#ifdef HAVE_ICONV_H
36231200Smm#include <iconv.h>
37231200Smm#endif
38238825Smm/*
39238825Smm * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
40238825Smm * As the include guards don't agree, the order of include is important.
41238825Smm */
42238825Smm#ifdef HAVE_LINUX_EXT2_FS_H
43238825Smm#include <linux/ext2_fs.h>      /* for Linux file flags */
44238825Smm#endif
45238825Smm#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
46238825Smm#include <ext2fs/ext2_fs.h>     /* Linux file flags, broken on Cygwin */
47238825Smm#endif
48314565Smm#ifdef HAVE_LINUX_FS_H
49314565Smm#include <linux/fs.h>
50314565Smm#endif
51231200Smm#include <limits.h>
52228753Smm#include <locale.h>
53231200Smm#ifdef HAVE_SIGNAL_H
54231200Smm#include <signal.h>
55231200Smm#endif
56228753Smm#include <stdarg.h>
57228753Smm#include <time.h>
58228753Smm
59316338Smm#ifdef HAVE_SIGNAL_H
60316338Smm#endif
61314571Smm#ifdef HAVE_ACL_LIBACL_H
62314571Smm#include <acl/libacl.h>
63314571Smm#endif
64314571Smm#ifdef HAVE_SYS_TYPES_H
65314571Smm#include <sys/types.h>
66314571Smm#endif
67314571Smm#ifdef HAVE_SYS_ACL_H
68314571Smm#include <sys/acl.h>
69314571Smm#endif
70316338Smm#ifdef HAVE_SYS_EA_H
71316338Smm#include <sys/ea.h>
72316338Smm#endif
73316338Smm#ifdef HAVE_SYS_EXTATTR_H
74316338Smm#include <sys/extattr.h>
75316338Smm#endif
76316338Smm#if HAVE_SYS_XATTR_H
77316338Smm#include <sys/xattr.h>
78316338Smm#elif HAVE_ATTR_XATTR_H
79316338Smm#include <attr/xattr.h>
80316338Smm#endif
81316338Smm#ifdef HAVE_SYS_RICHACL_H
82316338Smm#include <sys/richacl.h>
83316338Smm#endif
84316338Smm#if HAVE_MEMBERSHIP_H
85314571Smm#include <membership.h>
86314571Smm#endif
87314571Smm
88228753Smm/*
89228753Smm *
90228753Smm * Windows support routines
91228753Smm *
92228753Smm * Note: Configuration is a tricky issue.  Using HAVE_* feature macros
93228753Smm * in the test harness is dangerous because they cover up
94228753Smm * configuration errors.  The classic example of this is omitting a
95228753Smm * configure check.  If libarchive and libarchive_test both look for
96228753Smm * the same feature macro, such errors are hard to detect.  Platform
97228753Smm * macros (e.g., _WIN32 or __GNUC__) are a little better, but can
98228753Smm * easily lead to very messy code.  It's best to limit yourself
99228753Smm * to only the most generic programming techniques in the test harness
100228753Smm * and thus avoid conditionals altogether.  Where that's not possible,
101228753Smm * try to minimize conditionals by grouping platform-specific tests in
102228753Smm * one place (e.g., test_acl_freebsd) or by adding new assert()
103228753Smm * functions (e.g., assertMakeHardlink()) to cover up platform
104228753Smm * differences.  Platform-specific coding in libarchive_test is often
105228753Smm * a symptom that some capability is missing from libarchive itself.
106228753Smm */
107228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
108228753Smm#include <io.h>
109248590Smm#include <direct.h>
110228753Smm#include <windows.h>
111228753Smm#ifndef F_OK
112228753Smm#define F_OK (0)
113228753Smm#endif
114228753Smm#ifndef S_ISDIR
115228753Smm#define S_ISDIR(m)  ((m) & _S_IFDIR)
116228753Smm#endif
117228753Smm#ifndef S_ISREG
118228753Smm#define S_ISREG(m)  ((m) & _S_IFREG)
119228753Smm#endif
120228753Smm#if !defined(__BORLANDC__)
121228753Smm#define access _access
122231200Smm#undef chdir
123228753Smm#define chdir _chdir
124228753Smm#endif
125228753Smm#ifndef fileno
126228753Smm#define fileno _fileno
127228753Smm#endif
128228753Smm/*#define fstat _fstat64*/
129228753Smm#if !defined(__BORLANDC__)
130228753Smm#define getcwd _getcwd
131228753Smm#endif
132228753Smm#define lstat stat
133228753Smm/*#define lstat _stat64*/
134228753Smm/*#define stat _stat64*/
135228753Smm#define rmdir _rmdir
136228753Smm#if !defined(__BORLANDC__)
137228753Smm#define strdup _strdup
138228753Smm#define umask _umask
139228753Smm#endif
140228753Smm#define int64_t __int64
141228753Smm#endif
142228753Smm
143228753Smm#if defined(HAVE__CrtSetReportMode)
144228753Smm# include <crtdbg.h>
145228753Smm#endif
146228753Smm
147307214Smmmode_t umasked(mode_t expected_mode)
148307214Smm{
149307214Smm	mode_t mode = umask(0);
150307214Smm	umask(mode);
151307214Smm	return expected_mode & ~mode;
152307214Smm}
153307214Smm
154299425Smm/* Path to working directory for current test */
155299425Smmconst char *testworkdir;
156299425Smm#ifdef PROGRAM
157299425Smm/* Pathname of exe to be tested. */
158299425Smmconst char *testprogfile;
159299425Smm/* Name of exe to use in printf-formatted command strings. */
160299425Smm/* On Windows, this includes leading/trailing quotes. */
161299425Smmconst char *testprog;
162299425Smm#endif
163299425Smm
164228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
165238825Smmstatic void	*GetFunctionKernel32(const char *);
166238825Smmstatic int	 my_CreateSymbolicLinkA(const char *, const char *, int);
167238825Smmstatic int	 my_CreateHardLinkA(const char *, const char *);
168238825Smmstatic int	 my_GetFileInformationByName(const char *,
169238825Smm		     BY_HANDLE_FILE_INFORMATION *);
170238825Smm
171348608Smmtypedef struct _REPARSE_DATA_BUFFER {
172348608Smm	ULONG	ReparseTag;
173348608Smm	USHORT ReparseDataLength;
174348608Smm	USHORT	Reserved;
175348608Smm	union {
176348608Smm		struct {
177348608Smm			USHORT	SubstituteNameOffset;
178348608Smm			USHORT	SubstituteNameLength;
179348608Smm			USHORT	PrintNameOffset;
180348608Smm			USHORT	PrintNameLength;
181348608Smm			ULONG	Flags;
182348608Smm			WCHAR	PathBuffer[1];
183348608Smm		} SymbolicLinkReparseBuffer;
184348608Smm		struct {
185348608Smm			USHORT	SubstituteNameOffset;
186348608Smm			USHORT	SubstituteNameLength;
187348608Smm			USHORT	PrintNameOffset;
188348608Smm			USHORT	PrintNameLength;
189348608Smm			WCHAR	PathBuffer[1];
190348608Smm		} MountPointReparseBuffer;
191348608Smm		struct {
192348608Smm			UCHAR	DataBuffer[1];
193348608Smm		} GenericReparseBuffer;
194348608Smm	} DUMMYUNIONNAME;
195348608Smm} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
196348608Smm
197238825Smmstatic void *
198238825SmmGetFunctionKernel32(const char *name)
199228753Smm{
200228753Smm	static HINSTANCE lib;
201228753Smm	static int set;
202228753Smm	if (!set) {
203228753Smm		set = 1;
204228753Smm		lib = LoadLibrary("kernel32.dll");
205228753Smm	}
206228753Smm	if (lib == NULL) {
207228753Smm		fprintf(stderr, "Can't load kernel32.dll?!\n");
208228753Smm		exit(1);
209228753Smm	}
210228753Smm	return (void *)GetProcAddress(lib, name);
211228753Smm}
212228753Smm
213228753Smmstatic int
214348608Smmmy_CreateSymbolicLinkA(const char *linkname, const char *target,
215348608Smm    int targetIsDir)
216228753Smm{
217228753Smm	static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, DWORD);
218348608Smm	DWORD attrs;
219228753Smm	static int set;
220348608Smm	int ret, tmpflags, llen, tlen;
221348608Smm	int flags = 0;
222348608Smm	char *src, *tgt, *p;
223228753Smm	if (!set) {
224228753Smm		set = 1;
225228753Smm		f = GetFunctionKernel32("CreateSymbolicLinkA");
226228753Smm	}
227348608Smm	if (f == NULL)
228348608Smm		return (0);
229348608Smm
230348608Smm	tlen = strlen(target);
231348608Smm	llen = strlen(linkname);
232348608Smm
233348608Smm	if (tlen == 0 || llen == 0)
234348608Smm		return (0);
235348608Smm
236348608Smm	tgt = malloc((tlen + 1) * sizeof(char));
237348608Smm	if (tgt == NULL)
238348608Smm		return (0);
239348608Smm	src = malloc((llen + 1) * sizeof(char));
240348608Smm	if (src == NULL) {
241348608Smm		free(tgt);
242348608Smm		return (0);
243348608Smm	}
244348608Smm
245348608Smm	/*
246348608Smm	 * Translate slashes to backslashes
247348608Smm	 */
248348608Smm	p = src;
249348608Smm	while(*linkname != '\0') {
250348608Smm		if (*linkname == '/')
251348608Smm			*p = '\\';
252348608Smm		else
253348608Smm			*p = *linkname;
254348608Smm		linkname++;
255348608Smm		p++;
256348608Smm	}
257348608Smm	*p = '\0';
258348608Smm
259348608Smm	p = tgt;
260348608Smm	while(*target != '\0') {
261348608Smm		if (*target == '/')
262348608Smm			*p = '\\';
263348608Smm		else
264348608Smm			*p = *target;
265348608Smm		target++;
266348608Smm		p++;
267348608Smm	}
268348608Smm	*p = '\0';
269348608Smm
270348608Smm	/*
271348608Smm	 * Each test has to specify if a file or a directory symlink
272348608Smm	 * should be created.
273348608Smm	 */
274348608Smm	if (targetIsDir) {
275348608Smm#if defined(SYMBOLIC_LINK_FLAG_DIRECTORY)
276348608Smm		flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
277348608Smm#else
278348608Smm		flags |= 0x1;
279348608Smm#endif
280348608Smm	}
281348608Smm
282348608Smm#if defined(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)
283348608Smm	tmpflags = flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
284348608Smm#else
285348608Smm	tmpflags = flags | 0x2;
286348608Smm#endif
287348608Smm	/*
288348608Smm	 * Windows won't overwrite existing links
289348608Smm	 */
290348608Smm	attrs = GetFileAttributesA(linkname);
291348608Smm	if (attrs != INVALID_FILE_ATTRIBUTES) {
292348608Smm		if (attrs & FILE_ATTRIBUTE_DIRECTORY)
293348608Smm			RemoveDirectoryA(linkname);
294348608Smm		else
295348608Smm			DeleteFileA(linkname);
296348608Smm	}
297348608Smm
298348608Smm	ret = (*f)(src, tgt, tmpflags);
299348608Smm	/*
300348608Smm	 * Prior to Windows 10 the SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
301353377Smm	 * is not understood
302348608Smm	 */
303348608Smm	if (!ret)
304348608Smm		ret = (*f)(src, tgt, flags);
305348608Smm
306348608Smm	free(src);
307348608Smm	free(tgt);
308348608Smm	return (ret);
309228753Smm}
310228753Smm
311228753Smmstatic int
312228753Smmmy_CreateHardLinkA(const char *linkname, const char *target)
313228753Smm{
314228753Smm	static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, LPSECURITY_ATTRIBUTES);
315228753Smm	static int set;
316228753Smm	if (!set) {
317228753Smm		set = 1;
318228753Smm		f = GetFunctionKernel32("CreateHardLinkA");
319228753Smm	}
320228753Smm	return f == NULL ? 0 : (*f)(linkname, target, NULL);
321228753Smm}
322228753Smm
323238825Smmstatic int
324228753Smmmy_GetFileInformationByName(const char *path, BY_HANDLE_FILE_INFORMATION *bhfi)
325228753Smm{
326228753Smm	HANDLE h;
327228753Smm	int r;
328228753Smm
329228753Smm	memset(bhfi, 0, sizeof(*bhfi));
330228753Smm	h = CreateFile(path, FILE_READ_ATTRIBUTES, 0, NULL,
331231200Smm		OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
332228753Smm	if (h == INVALID_HANDLE_VALUE)
333228753Smm		return (0);
334228753Smm	r = GetFileInformationByHandle(h, bhfi);
335228753Smm	CloseHandle(h);
336228753Smm	return (r);
337228753Smm}
338228753Smm#endif
339228753Smm
340299425Smm#if defined(HAVE__CrtSetReportMode) && !defined(__WATCOMC__)
341228753Smmstatic void
342228753Smminvalid_parameter_handler(const wchar_t * expression,
343228753Smm    const wchar_t * function, const wchar_t * file,
344228753Smm    unsigned int line, uintptr_t pReserved)
345228753Smm{
346228753Smm	/* nop */
347313071Smm	// Silence unused-parameter compiler warnings.
348313071Smm	(void)expression;
349313071Smm	(void)function;
350313071Smm	(void)file;
351313071Smm	(void)line;
352313071Smm	(void)pReserved;
353228753Smm}
354228753Smm#endif
355228753Smm
356228753Smm/*
357228753Smm *
358228753Smm * OPTIONS FLAGS
359228753Smm *
360228753Smm */
361228753Smm
362228753Smm/* Enable core dump on failure. */
363228753Smmstatic int dump_on_failure = 0;
364228753Smm/* Default is to remove temp dirs and log data for successful tests. */
365228753Smmstatic int keep_temp_files = 0;
366231200Smm/* Default is to run the specified tests once and report errors. */
367231200Smmstatic int until_failure = 0;
368228753Smm/* Default is to just report pass/fail for each test. */
369228753Smmstatic int verbosity = 0;
370228753Smm#define	VERBOSITY_SUMMARY_ONLY -1 /* -q */
371228753Smm#define VERBOSITY_PASSFAIL 0   /* Default */
372228753Smm#define VERBOSITY_LIGHT_REPORT 1 /* -v */
373228753Smm#define VERBOSITY_FULL 2 /* -vv */
374228753Smm/* A few places generate even more output for verbosity > VERBOSITY_FULL,
375228753Smm * mostly for debugging the test harness itself. */
376228753Smm/* Cumulative count of assertion failures. */
377228753Smmstatic int failures = 0;
378228753Smm/* Cumulative count of reported skips. */
379228753Smmstatic int skips = 0;
380228753Smm/* Cumulative count of assertions checked. */
381228753Smmstatic int assertions = 0;
382228753Smm
383228753Smm/* Directory where uuencoded reference files can be found. */
384228753Smmstatic const char *refdir;
385228753Smm
386228753Smm/*
387228753Smm * Report log information selectively to console and/or disk log.
388228753Smm */
389228753Smmstatic int log_console = 0;
390228753Smmstatic FILE *logfile;
391358090Smmstatic void __LA_PRINTFLIKE(1, 0)
392228753Smmvlogprintf(const char *fmt, va_list ap)
393228753Smm{
394228753Smm#ifdef va_copy
395228753Smm	va_list lfap;
396228753Smm	va_copy(lfap, ap);
397228753Smm#endif
398228753Smm	if (log_console)
399228753Smm		vfprintf(stdout, fmt, ap);
400228753Smm	if (logfile != NULL)
401228753Smm#ifdef va_copy
402228753Smm		vfprintf(logfile, fmt, lfap);
403228753Smm	va_end(lfap);
404228753Smm#else
405228753Smm		vfprintf(logfile, fmt, ap);
406228753Smm#endif
407228753Smm}
408228753Smm
409358090Smmstatic void __LA_PRINTFLIKE(1, 2)
410228753Smmlogprintf(const char *fmt, ...)
411228753Smm{
412228753Smm	va_list ap;
413228753Smm	va_start(ap, fmt);
414228753Smm	vlogprintf(fmt, ap);
415228753Smm	va_end(ap);
416228753Smm}
417228753Smm
418228753Smm/* Set up a message to display only if next assertion fails. */
419228753Smmstatic char msgbuff[4096];
420228753Smmstatic const char *msg, *nextmsg;
421228753Smmvoid
422228753Smmfailure(const char *fmt, ...)
423228753Smm{
424228753Smm	va_list ap;
425231200Smm	if (fmt == NULL) {
426231200Smm		nextmsg = NULL;
427231200Smm	} else {
428231200Smm		va_start(ap, fmt);
429231200Smm		vsprintf(msgbuff, fmt, ap);
430231200Smm		va_end(ap);
431231200Smm		nextmsg = msgbuff;
432231200Smm	}
433228753Smm}
434228753Smm
435228753Smm/*
436228753Smm * Copy arguments into file-local variables.
437228753Smm * This was added to permit vararg assert() functions without needing
438228753Smm * variadic wrapper macros.  Turns out that the vararg capability is almost
439228753Smm * never used, so almost all of the vararg assertions can be simplified
440228753Smm * by removing the vararg capability and reworking the wrapper macro to
441228753Smm * pass __FILE__, __LINE__ directly into the function instead of using
442228753Smm * this hook.  I suspect this machinery is used so rarely that we
443228753Smm * would be better off just removing it entirely.  That would simplify
444231200Smm * the code here noticeably.
445228753Smm */
446231200Smmstatic const char *skipping_filename;
447231200Smmstatic int skipping_line;
448231200Smmvoid skipping_setup(const char *filename, int line)
449228753Smm{
450231200Smm	skipping_filename = filename;
451231200Smm	skipping_line = line;
452228753Smm}
453228753Smm
454228753Smm/* Called at the beginning of each assert() function. */
455228753Smmstatic void
456228753Smmassertion_count(const char *file, int line)
457228753Smm{
458228753Smm	(void)file; /* UNUSED */
459228753Smm	(void)line; /* UNUSED */
460228753Smm	++assertions;
461228753Smm	/* Proper handling of "failure()" message. */
462228753Smm	msg = nextmsg;
463228753Smm	nextmsg = NULL;
464228753Smm	/* Uncomment to print file:line after every assertion.
465228753Smm	 * Verbose, but occasionally useful in tracking down crashes. */
466228753Smm	/* printf("Checked %s:%d\n", file, line); */
467228753Smm}
468228753Smm
469228753Smm/*
470228753Smm * For each test source file, we remember how many times each
471228753Smm * assertion was reported.  Cleared before each new test,
472228753Smm * used by test_summarize().
473228753Smm */
474228753Smmstatic struct line {
475228753Smm	int count;
476228753Smm	int skip;
477228753Smm}  failed_lines[10000];
478231200Smmconst char *failed_filename;
479228753Smm
480228753Smm/* Count this failure, setup up log destination and handle initial report. */
481358090Smmstatic void __LA_PRINTFLIKE(3, 4)
482228753Smmfailure_start(const char *filename, int line, const char *fmt, ...)
483228753Smm{
484228753Smm	va_list ap;
485228753Smm
486228753Smm	/* Record another failure for this line. */
487228753Smm	++failures;
488231200Smm	failed_filename = filename;
489228753Smm	failed_lines[line].count++;
490228753Smm
491228753Smm	/* Determine whether to log header to console. */
492228753Smm	switch (verbosity) {
493228753Smm	case VERBOSITY_LIGHT_REPORT:
494228753Smm		log_console = (failed_lines[line].count < 2);
495228753Smm		break;
496228753Smm	default:
497228753Smm		log_console = (verbosity >= VERBOSITY_FULL);
498228753Smm	}
499228753Smm
500228753Smm	/* Log file:line header for this failure */
501228753Smm	va_start(ap, fmt);
502228753Smm#if _MSC_VER
503228753Smm	logprintf("%s(%d): ", filename, line);
504228753Smm#else
505228753Smm	logprintf("%s:%d: ", filename, line);
506228753Smm#endif
507228753Smm	vlogprintf(fmt, ap);
508228753Smm	va_end(ap);
509228753Smm	logprintf("\n");
510228753Smm
511228753Smm	if (msg != NULL && msg[0] != '\0') {
512228753Smm		logprintf("   Description: %s\n", msg);
513228753Smm		msg = NULL;
514228753Smm	}
515228753Smm
516228753Smm	/* Determine whether to log details to console. */
517228753Smm	if (verbosity == VERBOSITY_LIGHT_REPORT)
518228753Smm		log_console = 0;
519228753Smm}
520228753Smm
521228753Smm/* Complete reporting of failed tests. */
522228753Smm/*
523228753Smm * The 'extra' hook here is used by libarchive to include libarchive
524228753Smm * error messages with assertion failures.  It could also be used
525228753Smm * to add strerror() output, for example.  Just define the EXTRA_DUMP()
526228753Smm * macro appropriately.
527228753Smm */
528228753Smmstatic void
529228753Smmfailure_finish(void *extra)
530228753Smm{
531228753Smm	(void)extra; /* UNUSED (maybe) */
532228753Smm#ifdef EXTRA_DUMP
533231200Smm	if (extra != NULL) {
534231200Smm		logprintf("    errno: %d\n", EXTRA_ERRNO(extra));
535228753Smm		logprintf("   detail: %s\n", EXTRA_DUMP(extra));
536231200Smm	}
537228753Smm#endif
538228753Smm
539228753Smm	if (dump_on_failure) {
540228753Smm		fprintf(stderr,
541228753Smm		    " *** forcing core dump so failure can be debugged ***\n");
542228753Smm		abort();
543228753Smm	}
544228753Smm}
545228753Smm
546228753Smm/* Inform user that we're skipping some checks. */
547228753Smmvoid
548228753Smmtest_skipping(const char *fmt, ...)
549228753Smm{
550228753Smm	char buff[1024];
551228753Smm	va_list ap;
552228753Smm
553228753Smm	va_start(ap, fmt);
554228753Smm	vsprintf(buff, fmt, ap);
555228753Smm	va_end(ap);
556231200Smm	/* Use failure() message if set. */
557231200Smm	msg = nextmsg;
558231200Smm	nextmsg = NULL;
559228753Smm	/* failure_start() isn't quite right, but is awfully convenient. */
560231200Smm	failure_start(skipping_filename, skipping_line, "SKIPPING: %s", buff);
561228753Smm	--failures; /* Undo failures++ in failure_start() */
562228753Smm	/* Don't failure_finish() here. */
563228753Smm	/* Mark as skip, so doesn't count as failed test. */
564231200Smm	failed_lines[skipping_line].skip = 1;
565228753Smm	++skips;
566228753Smm}
567228753Smm
568228753Smm/*
569228753Smm *
570228753Smm * ASSERTIONS
571228753Smm *
572228753Smm */
573228753Smm
574228753Smm/* Generic assert() just displays the failed condition. */
575228753Smmint
576228753Smmassertion_assert(const char *file, int line, int value,
577228753Smm    const char *condition, void *extra)
578228753Smm{
579228753Smm	assertion_count(file, line);
580228753Smm	if (!value) {
581228753Smm		failure_start(file, line, "Assertion failed: %s", condition);
582228753Smm		failure_finish(extra);
583228753Smm	}
584228753Smm	return (value);
585228753Smm}
586228753Smm
587228753Smm/* chdir() and report any errors */
588228753Smmint
589228753Smmassertion_chdir(const char *file, int line, const char *pathname)
590228753Smm{
591228753Smm	assertion_count(file, line);
592228753Smm	if (chdir(pathname) == 0)
593228753Smm		return (1);
594228753Smm	failure_start(file, line, "chdir(\"%s\")", pathname);
595228753Smm	failure_finish(NULL);
596228753Smm	return (0);
597228753Smm
598228753Smm}
599228753Smm
600368708Smm/* change file/directory permissions and errors if it fails */
601368708Smmint
602368708Smmassertion_chmod(const char *file, int line, const char *pathname, int mode)
603368708Smm{
604368708Smm	assertion_count(file, line);
605368708Smm	if (chmod(pathname, mode) == 0)
606368708Smm		return (1);
607368708Smm	failure_start(file, line, "chmod(\"%s\", %4.o)", pathname, mode);
608368708Smm	failure_finish(NULL);
609368708Smm	return (0);
610368708Smm
611368708Smm}
612368708Smm
613228753Smm/* Verify two integers are equal. */
614228753Smmint
615228753Smmassertion_equal_int(const char *file, int line,
616228753Smm    long long v1, const char *e1, long long v2, const char *e2, void *extra)
617228753Smm{
618228753Smm	assertion_count(file, line);
619228753Smm	if (v1 == v2)
620228753Smm		return (1);
621228753Smm	failure_start(file, line, "%s != %s", e1, e2);
622228753Smm	logprintf("      %s=%lld (0x%llx, 0%llo)\n", e1, v1, v1, v1);
623228753Smm	logprintf("      %s=%lld (0x%llx, 0%llo)\n", e2, v2, v2, v2);
624228753Smm	failure_finish(extra);
625228753Smm	return (0);
626228753Smm}
627228753Smm
628231200Smm/*
629231200Smm * Utility to convert a single UTF-8 sequence.
630231200Smm */
631231200Smmstatic int
632231200Smm_utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
633228753Smm{
634231200Smm	static const char utf8_count[256] = {
635231200Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
636231200Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
637231200Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
638231200Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
639231200Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
640231200Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
641231200Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
642231200Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
643231200Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
644231200Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
645231200Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
646231200Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
647231200Smm		 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
648231200Smm		 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
649231200Smm		 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
650231200Smm		 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
651231200Smm	};
652231200Smm	int ch;
653231200Smm	int cnt;
654231200Smm	uint32_t wc;
655231200Smm
656231200Smm	*pwc = 0;
657231200Smm
658231200Smm	/* Sanity check. */
659231200Smm	if (n == 0)
660231200Smm		return (0);
661231200Smm	/*
662231200Smm	 * Decode 1-4 bytes depending on the value of the first byte.
663231200Smm	 */
664231200Smm	ch = (unsigned char)*s;
665231200Smm	if (ch == 0)
666231200Smm		return (0); /* Standard:  return 0 for end-of-string. */
667231200Smm	cnt = utf8_count[ch];
668231200Smm
669309587Smm	/* Invalid sequence or there are not plenty bytes. */
670231200Smm	if (n < (size_t)cnt)
671231200Smm		return (-1);
672231200Smm
673231200Smm	/* Make a Unicode code point from a single UTF-8 sequence. */
674231200Smm	switch (cnt) {
675231200Smm	case 1:	/* 1 byte sequence. */
676231200Smm		*pwc = ch & 0x7f;
677231200Smm		return (cnt);
678231200Smm	case 2:	/* 2 bytes sequence. */
679231200Smm		if ((s[1] & 0xc0) != 0x80) return (-1);
680231200Smm		*pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
681231200Smm		return (cnt);
682231200Smm	case 3:	/* 3 bytes sequence. */
683231200Smm		if ((s[1] & 0xc0) != 0x80) return (-1);
684231200Smm		if ((s[2] & 0xc0) != 0x80) return (-1);
685231200Smm		wc = ((ch & 0x0f) << 12)
686231200Smm		    | ((s[1] & 0x3f) << 6)
687231200Smm		    | (s[2] & 0x3f);
688231200Smm		if (wc < 0x800)
689231200Smm			return (-1);/* Overlong sequence. */
690231200Smm		break;
691231200Smm	case 4:	/* 4 bytes sequence. */
692231200Smm		if (n < 4)
693231200Smm			return (-1);
694231200Smm		if ((s[1] & 0xc0) != 0x80) return (-1);
695231200Smm		if ((s[2] & 0xc0) != 0x80) return (-1);
696231200Smm		if ((s[3] & 0xc0) != 0x80) return (-1);
697231200Smm		wc = ((ch & 0x07) << 18)
698231200Smm		    | ((s[1] & 0x3f) << 12)
699231200Smm		    | ((s[2] & 0x3f) << 6)
700231200Smm		    | (s[3] & 0x3f);
701231200Smm		if (wc < 0x10000)
702231200Smm			return (-1);/* Overlong sequence. */
703231200Smm		break;
704231200Smm	default:
705231200Smm		return (-1);
706231200Smm	}
707231200Smm
708309587Smm	/* The code point larger than 0x10FFFF is not legal
709231200Smm	 * Unicode values. */
710231200Smm	if (wc > 0x10FFFF)
711231200Smm		return (-1);
712231200Smm	/* Correctly gets a Unicode, returns used bytes. */
713231200Smm	*pwc = wc;
714231200Smm	return (cnt);
715231200Smm}
716231200Smm
717231200Smmstatic void strdump(const char *e, const char *p, int ewidth, int utf8)
718231200Smm{
719228753Smm	const char *q = p;
720228753Smm
721231200Smm	logprintf("      %*s = ", ewidth, e);
722228753Smm	if (p == NULL) {
723231200Smm		logprintf("NULL\n");
724228753Smm		return;
725228753Smm	}
726228753Smm	logprintf("\"");
727228753Smm	while (*p != '\0') {
728228753Smm		unsigned int c = 0xff & *p++;
729228753Smm		switch (c) {
730299425Smm		case '\a': logprintf("\\a"); break;
731299425Smm		case '\b': logprintf("\\b"); break;
732299425Smm		case '\n': logprintf("\\n"); break;
733299425Smm		case '\r': logprintf("\\r"); break;
734228753Smm		default:
735228753Smm			if (c >= 32 && c < 127)
736228753Smm				logprintf("%c", c);
737228753Smm			else
738228753Smm				logprintf("\\x%02X", c);
739228753Smm		}
740228753Smm	}
741228753Smm	logprintf("\"");
742231200Smm	logprintf(" (length %d)", q == NULL ? -1 : (int)strlen(q));
743231200Smm
744231200Smm	/*
745231200Smm	 * If the current string is UTF-8, dump its code points.
746231200Smm	 */
747231200Smm	if (utf8) {
748231200Smm		size_t len;
749231200Smm		uint32_t uc;
750231200Smm		int n;
751231200Smm		int cnt = 0;
752231200Smm
753231200Smm		p = q;
754231200Smm		len = strlen(p);
755231200Smm		logprintf(" [");
756231200Smm		while ((n = _utf8_to_unicode(&uc, p, len)) > 0) {
757231200Smm			if (p != q)
758231200Smm				logprintf(" ");
759231200Smm			logprintf("%04X", uc);
760231200Smm			p += n;
761231200Smm			len -= n;
762231200Smm			cnt++;
763231200Smm		}
764231200Smm		logprintf("]");
765231200Smm		logprintf(" (count %d", cnt);
766231200Smm		if (n < 0) {
767358090Smm			logprintf(",unknown %zu bytes", len);
768231200Smm		}
769231200Smm		logprintf(")");
770231200Smm
771231200Smm	}
772231200Smm	logprintf("\n");
773228753Smm}
774228753Smm
775228753Smm/* Verify two strings are equal, dump them if not. */
776228753Smmint
777228753Smmassertion_equal_string(const char *file, int line,
778228753Smm    const char *v1, const char *e1,
779228753Smm    const char *v2, const char *e2,
780231200Smm    void *extra, int utf8)
781228753Smm{
782231200Smm	int l1, l2;
783231200Smm
784228753Smm	assertion_count(file, line);
785228753Smm	if (v1 == v2 || (v1 != NULL && v2 != NULL && strcmp(v1, v2) == 0))
786228753Smm		return (1);
787228753Smm	failure_start(file, line, "%s != %s", e1, e2);
788248590Smm	l1 = (int)strlen(e1);
789248590Smm	l2 = (int)strlen(e2);
790231200Smm	if (l1 < l2)
791231200Smm		l1 = l2;
792231200Smm	strdump(e1, v1, l1, utf8);
793231200Smm	strdump(e2, v2, l1, utf8);
794228753Smm	failure_finish(extra);
795228753Smm	return (0);
796228753Smm}
797228753Smm
798228753Smmstatic void
799228753Smmwcsdump(const char *e, const wchar_t *w)
800228753Smm{
801228753Smm	logprintf("      %s = ", e);
802228753Smm	if (w == NULL) {
803228753Smm		logprintf("(null)");
804228753Smm		return;
805228753Smm	}
806228753Smm	logprintf("\"");
807228753Smm	while (*w != L'\0') {
808228753Smm		unsigned int c = *w++;
809228753Smm		if (c >= 32 && c < 127)
810228753Smm			logprintf("%c", c);
811228753Smm		else if (c < 256)
812228753Smm			logprintf("\\x%02X", c);
813228753Smm		else if (c < 0x10000)
814228753Smm			logprintf("\\u%04X", c);
815228753Smm		else
816228753Smm			logprintf("\\U%08X", c);
817228753Smm	}
818228753Smm	logprintf("\"\n");
819228753Smm}
820228753Smm
821228753Smm#ifndef HAVE_WCSCMP
822228753Smmstatic int
823228753Smmwcscmp(const wchar_t *s1, const wchar_t *s2)
824228753Smm{
825228753Smm
826228753Smm	while (*s1 == *s2++) {
827228753Smm		if (*s1++ == L'\0')
828228753Smm			return 0;
829228753Smm	}
830228753Smm	if (*s1 > *--s2)
831228753Smm		return 1;
832228753Smm	else
833228753Smm		return -1;
834228753Smm}
835228753Smm#endif
836228753Smm
837228753Smm/* Verify that two wide strings are equal, dump them if not. */
838228753Smmint
839228753Smmassertion_equal_wstring(const char *file, int line,
840228753Smm    const wchar_t *v1, const char *e1,
841228753Smm    const wchar_t *v2, const char *e2,
842228753Smm    void *extra)
843228753Smm{
844228753Smm	assertion_count(file, line);
845231200Smm	if (v1 == v2)
846228753Smm		return (1);
847231200Smm	if (v1 != NULL && v2 != NULL && wcscmp(v1, v2) == 0)
848231200Smm		return (1);
849228753Smm	failure_start(file, line, "%s != %s", e1, e2);
850228753Smm	wcsdump(e1, v1);
851228753Smm	wcsdump(e2, v2);
852228753Smm	failure_finish(extra);
853228753Smm	return (0);
854228753Smm}
855228753Smm
856228753Smm/*
857228753Smm * Pretty standard hexdump routine.  As a bonus, if ref != NULL, then
858228753Smm * any bytes in p that differ from ref will be highlighted with '_'
859228753Smm * before and after the hex value.
860228753Smm */
861228753Smmstatic void
862228753Smmhexdump(const char *p, const char *ref, size_t l, size_t offset)
863228753Smm{
864228753Smm	size_t i, j;
865228753Smm	char sep;
866228753Smm
867228753Smm	if (p == NULL) {
868228753Smm		logprintf("(null)\n");
869228753Smm		return;
870228753Smm	}
871228753Smm	for(i=0; i < l; i+=16) {
872228753Smm		logprintf("%04x", (unsigned)(i + offset));
873228753Smm		sep = ' ';
874228753Smm		for (j = 0; j < 16 && i + j < l; j++) {
875228753Smm			if (ref != NULL && p[i + j] != ref[i + j])
876228753Smm				sep = '_';
877228753Smm			logprintf("%c%02x", sep, 0xff & (int)p[i+j]);
878228753Smm			if (ref != NULL && p[i + j] == ref[i + j])
879228753Smm				sep = ' ';
880228753Smm		}
881228753Smm		for (; j < 16; j++) {
882228753Smm			logprintf("%c  ", sep);
883228753Smm			sep = ' ';
884228753Smm		}
885228753Smm		logprintf("%c", sep);
886228753Smm		for (j=0; j < 16 && i + j < l; j++) {
887228753Smm			int c = p[i + j];
888228753Smm			if (c >= ' ' && c <= 126)
889228753Smm				logprintf("%c", c);
890228753Smm			else
891228753Smm				logprintf(".");
892228753Smm		}
893228753Smm		logprintf("\n");
894228753Smm	}
895228753Smm}
896228753Smm
897228753Smm/* Verify that two blocks of memory are the same, display the first
898228753Smm * block of differences if they're not. */
899228753Smmint
900228753Smmassertion_equal_mem(const char *file, int line,
901228753Smm    const void *_v1, const char *e1,
902228753Smm    const void *_v2, const char *e2,
903228753Smm    size_t l, const char *ld, void *extra)
904228753Smm{
905228753Smm	const char *v1 = (const char *)_v1;
906228753Smm	const char *v2 = (const char *)_v2;
907228753Smm	size_t offset;
908228753Smm
909228753Smm	assertion_count(file, line);
910228753Smm	if (v1 == v2 || (v1 != NULL && v2 != NULL && memcmp(v1, v2, l) == 0))
911228753Smm		return (1);
912248590Smm	if (v1 == NULL || v2 == NULL)
913248590Smm		return (0);
914228753Smm
915228753Smm	failure_start(file, line, "%s != %s", e1, e2);
916228753Smm	logprintf("      size %s = %d\n", ld, (int)l);
917228753Smm	/* Dump 48 bytes (3 lines) so that the first difference is
918228753Smm	 * in the second line. */
919228753Smm	offset = 0;
920228753Smm	while (l > 64 && memcmp(v1, v2, 32) == 0) {
921228753Smm		/* Two lines agree, so step forward one line. */
922228753Smm		v1 += 16;
923228753Smm		v2 += 16;
924228753Smm		l -= 16;
925228753Smm		offset += 16;
926228753Smm	}
927228753Smm	logprintf("      Dump of %s\n", e1);
928231200Smm	hexdump(v1, v2, l < 128 ? l : 128, offset);
929228753Smm	logprintf("      Dump of %s\n", e2);
930231200Smm	hexdump(v2, v1, l < 128 ? l : 128, offset);
931228753Smm	logprintf("\n");
932228753Smm	failure_finish(extra);
933228753Smm	return (0);
934228753Smm}
935228753Smm
936299425Smm/* Verify that a block of memory is filled with the specified byte. */
937299425Smmint
938299425Smmassertion_memory_filled_with(const char *file, int line,
939299425Smm    const void *_v1, const char *vd,
940299425Smm    size_t l, const char *ld,
941299425Smm    char b, const char *bd, void *extra)
942299425Smm{
943299425Smm	const char *v1 = (const char *)_v1;
944299425Smm	size_t c = 0;
945299425Smm	size_t i;
946299425Smm	(void)ld; /* UNUSED */
947299425Smm
948299425Smm	assertion_count(file, line);
949299425Smm
950299425Smm	for (i = 0; i < l; ++i) {
951299425Smm		if (v1[i] == b) {
952299425Smm			++c;
953299425Smm		}
954299425Smm	}
955299425Smm	if (c == l)
956299425Smm		return (1);
957299425Smm
958299425Smm	failure_start(file, line, "%s (size %d) not filled with %s", vd, (int)l, bd);
959299425Smm	logprintf("   Only %d bytes were correct\n", (int)c);
960299425Smm	failure_finish(extra);
961299425Smm	return (0);
962299425Smm}
963299425Smm
964228753Smm/* Verify that the named file exists and is empty. */
965228753Smmint
966231200Smmassertion_empty_file(const char *filename, int line, const char *f1)
967228753Smm{
968228753Smm	char buff[1024];
969228753Smm	struct stat st;
970228753Smm	ssize_t s;
971228753Smm	FILE *f;
972228753Smm
973231200Smm	assertion_count(filename, line);
974228753Smm
975228753Smm	if (stat(f1, &st) != 0) {
976231200Smm		failure_start(filename, line, "Stat failed: %s", f1);
977228753Smm		failure_finish(NULL);
978228753Smm		return (0);
979228753Smm	}
980228753Smm	if (st.st_size == 0)
981228753Smm		return (1);
982228753Smm
983231200Smm	failure_start(filename, line, "File should be empty: %s", f1);
984228753Smm	logprintf("    File size: %d\n", (int)st.st_size);
985228753Smm	logprintf("    Contents:\n");
986228753Smm	f = fopen(f1, "rb");
987228753Smm	if (f == NULL) {
988228753Smm		logprintf("    Unable to open %s\n", f1);
989228753Smm	} else {
990228753Smm		s = ((off_t)sizeof(buff) < st.st_size) ?
991228753Smm		    (ssize_t)sizeof(buff) : (ssize_t)st.st_size;
992228753Smm		s = fread(buff, 1, s, f);
993228753Smm		hexdump(buff, NULL, s, 0);
994228753Smm		fclose(f);
995228753Smm	}
996228753Smm	failure_finish(NULL);
997228753Smm	return (0);
998228753Smm}
999228753Smm
1000228753Smm/* Verify that the named file exists and is not empty. */
1001228753Smmint
1002231200Smmassertion_non_empty_file(const char *filename, int line, const char *f1)
1003228753Smm{
1004228753Smm	struct stat st;
1005228753Smm
1006231200Smm	assertion_count(filename, line);
1007228753Smm
1008228753Smm	if (stat(f1, &st) != 0) {
1009231200Smm		failure_start(filename, line, "Stat failed: %s", f1);
1010228753Smm		failure_finish(NULL);
1011228753Smm		return (0);
1012228753Smm	}
1013228753Smm	if (st.st_size == 0) {
1014231200Smm		failure_start(filename, line, "File empty: %s", f1);
1015228753Smm		failure_finish(NULL);
1016228753Smm		return (0);
1017228753Smm	}
1018228753Smm	return (1);
1019228753Smm}
1020228753Smm
1021228753Smm/* Verify that two files have the same contents. */
1022228753Smm/* TODO: hexdump the first bytes that actually differ. */
1023228753Smmint
1024231200Smmassertion_equal_file(const char *filename, int line, const char *fn1, const char *fn2)
1025228753Smm{
1026228753Smm	char buff1[1024];
1027228753Smm	char buff2[1024];
1028228753Smm	FILE *f1, *f2;
1029228753Smm	int n1, n2;
1030228753Smm
1031231200Smm	assertion_count(filename, line);
1032228753Smm
1033228753Smm	f1 = fopen(fn1, "rb");
1034228753Smm	f2 = fopen(fn2, "rb");
1035248590Smm	if (f1 == NULL || f2 == NULL) {
1036248590Smm		if (f1) fclose(f1);
1037248590Smm		if (f2) fclose(f2);
1038248590Smm		return (0);
1039248590Smm	}
1040228753Smm	for (;;) {
1041248590Smm		n1 = (int)fread(buff1, 1, sizeof(buff1), f1);
1042248590Smm		n2 = (int)fread(buff2, 1, sizeof(buff2), f2);
1043228753Smm		if (n1 != n2)
1044228753Smm			break;
1045228753Smm		if (n1 == 0 && n2 == 0) {
1046228753Smm			fclose(f1);
1047228753Smm			fclose(f2);
1048228753Smm			return (1);
1049228753Smm		}
1050228753Smm		if (memcmp(buff1, buff2, n1) != 0)
1051228753Smm			break;
1052228753Smm	}
1053228753Smm	fclose(f1);
1054228753Smm	fclose(f2);
1055231200Smm	failure_start(filename, line, "Files not identical");
1056228753Smm	logprintf("  file1=\"%s\"\n", fn1);
1057228753Smm	logprintf("  file2=\"%s\"\n", fn2);
1058231200Smm	failure_finish(NULL);
1059228753Smm	return (0);
1060228753Smm}
1061228753Smm
1062228753Smm/* Verify that the named file does exist. */
1063228753Smmint
1064231200Smmassertion_file_exists(const char *filename, int line, const char *f)
1065228753Smm{
1066231200Smm	assertion_count(filename, line);
1067228753Smm
1068228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1069228753Smm	if (!_access(f, 0))
1070228753Smm		return (1);
1071228753Smm#else
1072228753Smm	if (!access(f, F_OK))
1073228753Smm		return (1);
1074228753Smm#endif
1075231200Smm	failure_start(filename, line, "File should exist: %s", f);
1076231200Smm	failure_finish(NULL);
1077228753Smm	return (0);
1078228753Smm}
1079228753Smm
1080228753Smm/* Verify that the named file doesn't exist. */
1081228753Smmint
1082231200Smmassertion_file_not_exists(const char *filename, int line, const char *f)
1083228753Smm{
1084231200Smm	assertion_count(filename, line);
1085228753Smm
1086228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1087228753Smm	if (_access(f, 0))
1088228753Smm		return (1);
1089228753Smm#else
1090228753Smm	if (access(f, F_OK))
1091228753Smm		return (1);
1092228753Smm#endif
1093231200Smm	failure_start(filename, line, "File should not exist: %s", f);
1094231200Smm	failure_finish(NULL);
1095228753Smm	return (0);
1096228753Smm}
1097228753Smm
1098228753Smm/* Compare the contents of a file to a block of memory. */
1099228753Smmint
1100231200Smmassertion_file_contents(const char *filename, int line, const void *buff, int s, const char *fn)
1101228753Smm{
1102228753Smm	char *contents;
1103228753Smm	FILE *f;
1104228753Smm	int n;
1105228753Smm
1106231200Smm	assertion_count(filename, line);
1107228753Smm
1108228753Smm	f = fopen(fn, "rb");
1109228753Smm	if (f == NULL) {
1110231200Smm		failure_start(filename, line,
1111228753Smm		    "File should exist: %s", fn);
1112231200Smm		failure_finish(NULL);
1113228753Smm		return (0);
1114228753Smm	}
1115228753Smm	contents = malloc(s * 2);
1116248590Smm	n = (int)fread(contents, 1, s * 2, f);
1117228753Smm	fclose(f);
1118228753Smm	if (n == s && memcmp(buff, contents, s) == 0) {
1119228753Smm		free(contents);
1120228753Smm		return (1);
1121228753Smm	}
1122231200Smm	failure_start(filename, line, "File contents don't match");
1123228753Smm	logprintf("  file=\"%s\"\n", fn);
1124228753Smm	if (n > 0)
1125228753Smm		hexdump(contents, buff, n > 512 ? 512 : n, 0);
1126228753Smm	else {
1127228753Smm		logprintf("  File empty, contents should be:\n");
1128231200Smm		hexdump(buff, NULL, s > 512 ? 512 : s, 0);
1129228753Smm	}
1130231200Smm	failure_finish(NULL);
1131228753Smm	free(contents);
1132228753Smm	return (0);
1133228753Smm}
1134228753Smm
1135228753Smm/* Check the contents of a text file, being tolerant of line endings. */
1136228753Smmint
1137231200Smmassertion_text_file_contents(const char *filename, int line, const char *buff, const char *fn)
1138228753Smm{
1139228753Smm	char *contents;
1140228753Smm	const char *btxt, *ftxt;
1141228753Smm	FILE *f;
1142228753Smm	int n, s;
1143228753Smm
1144231200Smm	assertion_count(filename, line);
1145228753Smm	f = fopen(fn, "r");
1146231200Smm	if (f == NULL) {
1147231200Smm		failure_start(filename, line,
1148231200Smm		    "File doesn't exist: %s", fn);
1149231200Smm		failure_finish(NULL);
1150231200Smm		return (0);
1151231200Smm	}
1152248590Smm	s = (int)strlen(buff);
1153228753Smm	contents = malloc(s * 2 + 128);
1154248590Smm	n = (int)fread(contents, 1, s * 2 + 128 - 1, f);
1155228753Smm	if (n >= 0)
1156228753Smm		contents[n] = '\0';
1157228753Smm	fclose(f);
1158228753Smm	/* Compare texts. */
1159228753Smm	btxt = buff;
1160228753Smm	ftxt = (const char *)contents;
1161228753Smm	while (*btxt != '\0' && *ftxt != '\0') {
1162228753Smm		if (*btxt == *ftxt) {
1163228753Smm			++btxt;
1164228753Smm			++ftxt;
1165228753Smm			continue;
1166228753Smm		}
1167228753Smm		if (btxt[0] == '\n' && ftxt[0] == '\r' && ftxt[1] == '\n') {
1168228753Smm			/* Pass over different new line characters. */
1169228753Smm			++btxt;
1170228753Smm			ftxt += 2;
1171228753Smm			continue;
1172228753Smm		}
1173228753Smm		break;
1174228753Smm	}
1175228753Smm	if (*btxt == '\0' && *ftxt == '\0') {
1176228753Smm		free(contents);
1177228753Smm		return (1);
1178228753Smm	}
1179231200Smm	failure_start(filename, line, "Contents don't match");
1180228753Smm	logprintf("  file=\"%s\"\n", fn);
1181231200Smm	if (n > 0) {
1182228753Smm		hexdump(contents, buff, n, 0);
1183358090Smm		logprintf("  expected\n");
1184231200Smm		hexdump(buff, contents, s, 0);
1185231200Smm	} else {
1186228753Smm		logprintf("  File empty, contents should be:\n");
1187228753Smm		hexdump(buff, NULL, s, 0);
1188228753Smm	}
1189231200Smm	failure_finish(NULL);
1190228753Smm	free(contents);
1191228753Smm	return (0);
1192228753Smm}
1193228753Smm
1194231200Smm/* Verify that a text file contains the specified lines, regardless of order */
1195231200Smm/* This could be more efficient if we sorted both sets of lines, etc, but
1196231200Smm * since this is used only for testing and only ever deals with a dozen or so
1197231200Smm * lines at a time, this relatively crude approach is just fine. */
1198231200Smmint
1199231200Smmassertion_file_contains_lines_any_order(const char *file, int line,
1200231200Smm    const char *pathname, const char *lines[])
1201231200Smm{
1202231200Smm	char *buff;
1203231200Smm	size_t buff_size;
1204231200Smm	size_t expected_count, actual_count, i, j;
1205248590Smm	char **expected = NULL;
1206248590Smm	char *p, **actual = NULL;
1207231200Smm	char c;
1208231200Smm	int expected_failure = 0, actual_failure = 0;
1209231200Smm
1210231200Smm	assertion_count(file, line);
1211231200Smm
1212231200Smm	buff = slurpfile(&buff_size, "%s", pathname);
1213231200Smm	if (buff == NULL) {
1214231200Smm		failure_start(pathname, line, "Can't read file: %s", pathname);
1215231200Smm		failure_finish(NULL);
1216231200Smm		return (0);
1217231200Smm	}
1218231200Smm
1219248590Smm	/* Make a copy of the provided lines and count up the expected
1220248590Smm	 * file size. */
1221231200Smm	for (i = 0; lines[i] != NULL; ++i) {
1222231200Smm	}
1223231200Smm	expected_count = i;
1224248590Smm	if (expected_count) {
1225248590Smm		expected = malloc(sizeof(char *) * expected_count);
1226248590Smm		if (expected == NULL) {
1227248590Smm			failure_start(pathname, line, "Can't allocate memory");
1228248590Smm			failure_finish(NULL);
1229299425Smm			free(expected);
1230318483Smm			free(buff);
1231248590Smm			return (0);
1232248590Smm		}
1233248590Smm		for (i = 0; lines[i] != NULL; ++i) {
1234248590Smm			expected[i] = strdup(lines[i]);
1235248590Smm		}
1236231200Smm	}
1237231200Smm
1238231200Smm	/* Break the file into lines */
1239231200Smm	actual_count = 0;
1240231200Smm	for (c = '\0', p = buff; p < buff + buff_size; ++p) {
1241231200Smm		if (*p == '\x0d' || *p == '\x0a')
1242231200Smm			*p = '\0';
1243231200Smm		if (c == '\0' && *p != '\0')
1244231200Smm			++actual_count;
1245231200Smm		c = *p;
1246231200Smm	}
1247248590Smm	if (actual_count) {
1248248590Smm		actual = calloc(sizeof(char *), actual_count);
1249248590Smm		if (actual == NULL) {
1250248590Smm			failure_start(pathname, line, "Can't allocate memory");
1251248590Smm			failure_finish(NULL);
1252248590Smm			free(expected);
1253318483Smm			free(buff);
1254248590Smm			return (0);
1255231200Smm		}
1256248590Smm		for (j = 0, p = buff; p < buff + buff_size;
1257248590Smm		    p += 1 + strlen(p)) {
1258248590Smm			if (*p != '\0') {
1259248590Smm				actual[j] = p;
1260248590Smm				++j;
1261248590Smm			}
1262248590Smm		}
1263231200Smm	}
1264231200Smm
1265231200Smm	/* Erase matching lines from both lists */
1266231200Smm	for (i = 0; i < expected_count; ++i) {
1267231200Smm		if (expected[i] == NULL)
1268231200Smm			continue;
1269231200Smm		for (j = 0; j < actual_count; ++j) {
1270231200Smm			if (actual[j] == NULL)
1271231200Smm				continue;
1272231200Smm			if (strcmp(expected[i], actual[j]) == 0) {
1273231200Smm				free(expected[i]);
1274231200Smm				expected[i] = NULL;
1275231200Smm				actual[j] = NULL;
1276231200Smm				break;
1277231200Smm			}
1278231200Smm		}
1279231200Smm	}
1280231200Smm
1281231200Smm	/* If there's anything left, it's a failure */
1282231200Smm	for (i = 0; i < expected_count; ++i) {
1283231200Smm		if (expected[i] != NULL)
1284231200Smm			++expected_failure;
1285231200Smm	}
1286231200Smm	for (j = 0; j < actual_count; ++j) {
1287231200Smm		if (actual[j] != NULL)
1288231200Smm			++actual_failure;
1289231200Smm	}
1290231200Smm	if (expected_failure == 0 && actual_failure == 0) {
1291231200Smm		free(buff);
1292231200Smm		free(expected);
1293231200Smm		free(actual);
1294231200Smm		return (1);
1295231200Smm	}
1296231200Smm	failure_start(file, line, "File doesn't match: %s", pathname);
1297231200Smm	for (i = 0; i < expected_count; ++i) {
1298231200Smm		if (expected[i] != NULL) {
1299231200Smm			logprintf("  Expected but not present: %s\n", expected[i]);
1300231200Smm			free(expected[i]);
1301231200Smm		}
1302231200Smm	}
1303231200Smm	for (j = 0; j < actual_count; ++j) {
1304231200Smm		if (actual[j] != NULL)
1305231200Smm			logprintf("  Present but not expected: %s\n", actual[j]);
1306231200Smm	}
1307231200Smm	failure_finish(NULL);
1308231200Smm	free(buff);
1309231200Smm	free(expected);
1310231200Smm	free(actual);
1311231200Smm	return (0);
1312231200Smm}
1313231200Smm
1314307859Smm/* Verify that a text file does not contains the specified strings */
1315307859Smmint
1316307859Smmassertion_file_contains_no_invalid_strings(const char *file, int line,
1317307859Smm    const char *pathname, const char *strings[])
1318307859Smm{
1319307859Smm	char *buff;
1320307859Smm	int i;
1321307859Smm
1322307859Smm	buff = slurpfile(NULL, "%s", pathname);
1323307859Smm	if (buff == NULL) {
1324307859Smm		failure_start(file, line, "Can't read file: %s", pathname);
1325307859Smm		failure_finish(NULL);
1326307859Smm		return (0);
1327307859Smm	}
1328307859Smm
1329307859Smm	for (i = 0; strings[i] != NULL; ++i) {
1330307859Smm		if (strstr(buff, strings[i]) != NULL) {
1331307859Smm			failure_start(file, line, "Invalid string in %s: %s", pathname,
1332307859Smm			    strings[i]);
1333307859Smm			failure_finish(NULL);
1334307859Smm			free(buff);
1335307859Smm			return(0);
1336307859Smm		}
1337307859Smm	}
1338307859Smm
1339307859Smm	free(buff);
1340307859Smm	return (0);
1341307859Smm}
1342307859Smm
1343228753Smm/* Test that two paths point to the same file. */
1344228753Smm/* As a side-effect, asserts that both files exist. */
1345228753Smmstatic int
1346228753Smmis_hardlink(const char *file, int line,
1347228753Smm    const char *path1, const char *path2)
1348228753Smm{
1349228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1350228753Smm	BY_HANDLE_FILE_INFORMATION bhfi1, bhfi2;
1351228753Smm	int r;
1352228753Smm
1353228753Smm	assertion_count(file, line);
1354228753Smm	r = my_GetFileInformationByName(path1, &bhfi1);
1355228753Smm	if (r == 0) {
1356228753Smm		failure_start(file, line, "File %s can't be inspected?", path1);
1357228753Smm		failure_finish(NULL);
1358228753Smm		return (0);
1359228753Smm	}
1360228753Smm	r = my_GetFileInformationByName(path2, &bhfi2);
1361228753Smm	if (r == 0) {
1362228753Smm		failure_start(file, line, "File %s can't be inspected?", path2);
1363228753Smm		failure_finish(NULL);
1364228753Smm		return (0);
1365228753Smm	}
1366228753Smm	return (bhfi1.dwVolumeSerialNumber == bhfi2.dwVolumeSerialNumber
1367228753Smm		&& bhfi1.nFileIndexHigh == bhfi2.nFileIndexHigh
1368228753Smm		&& bhfi1.nFileIndexLow == bhfi2.nFileIndexLow);
1369228753Smm#else
1370228753Smm	struct stat st1, st2;
1371228753Smm	int r;
1372228753Smm
1373228753Smm	assertion_count(file, line);
1374228753Smm	r = lstat(path1, &st1);
1375228753Smm	if (r != 0) {
1376228753Smm		failure_start(file, line, "File should exist: %s", path1);
1377228753Smm		failure_finish(NULL);
1378228753Smm		return (0);
1379228753Smm	}
1380228753Smm	r = lstat(path2, &st2);
1381228753Smm	if (r != 0) {
1382228753Smm		failure_start(file, line, "File should exist: %s", path2);
1383228753Smm		failure_finish(NULL);
1384228753Smm		return (0);
1385228753Smm	}
1386228753Smm	return (st1.st_ino == st2.st_ino && st1.st_dev == st2.st_dev);
1387228753Smm#endif
1388228753Smm}
1389228753Smm
1390228753Smmint
1391228753Smmassertion_is_hardlink(const char *file, int line,
1392228753Smm    const char *path1, const char *path2)
1393228753Smm{
1394228753Smm	if (is_hardlink(file, line, path1, path2))
1395228753Smm		return (1);
1396228753Smm	failure_start(file, line,
1397228753Smm	    "Files %s and %s are not hardlinked", path1, path2);
1398228753Smm	failure_finish(NULL);
1399228753Smm	return (0);
1400228753Smm}
1401228753Smm
1402228753Smmint
1403228753Smmassertion_is_not_hardlink(const char *file, int line,
1404228753Smm    const char *path1, const char *path2)
1405228753Smm{
1406228753Smm	if (!is_hardlink(file, line, path1, path2))
1407228753Smm		return (1);
1408228753Smm	failure_start(file, line,
1409228753Smm	    "Files %s and %s should not be hardlinked", path1, path2);
1410228753Smm	failure_finish(NULL);
1411228753Smm	return (0);
1412228753Smm}
1413228753Smm
1414228753Smm/* Verify a/b/mtime of 'pathname'. */
1415228753Smm/* If 'recent', verify that it's within last 10 seconds. */
1416228753Smmstatic int
1417228753Smmassertion_file_time(const char *file, int line,
1418228753Smm    const char *pathname, long t, long nsec, char type, int recent)
1419228753Smm{
1420228753Smm	long long filet, filet_nsec;
1421228753Smm	int r;
1422228753Smm
1423228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1424228753Smm#define EPOC_TIME	(116444736000000000ULL)
1425248590Smm	FILETIME fxtime, fbirthtime, fatime, fmtime;
1426228753Smm	ULARGE_INTEGER wintm;
1427228753Smm	HANDLE h;
1428248590Smm	fxtime.dwLowDateTime = 0;
1429248590Smm	fxtime.dwHighDateTime = 0;
1430228753Smm
1431228753Smm	assertion_count(file, line);
1432231200Smm	/* Note: FILE_FLAG_BACKUP_SEMANTICS applies to open
1433231200Smm	 * a directory file. If not, CreateFile() will fail when
1434231200Smm	 * the pathname is a directory. */
1435228753Smm	h = CreateFile(pathname, FILE_READ_ATTRIBUTES, 0, NULL,
1436231200Smm	    OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1437228753Smm	if (h == INVALID_HANDLE_VALUE) {
1438228753Smm		failure_start(file, line, "Can't access %s\n", pathname);
1439228753Smm		failure_finish(NULL);
1440228753Smm		return (0);
1441228753Smm	}
1442228753Smm	r = GetFileTime(h, &fbirthtime, &fatime, &fmtime);
1443228753Smm	switch (type) {
1444248590Smm	case 'a': fxtime = fatime; break;
1445248590Smm	case 'b': fxtime = fbirthtime; break;
1446248590Smm	case 'm': fxtime = fmtime; break;
1447228753Smm	}
1448228753Smm	CloseHandle(h);
1449228753Smm	if (r == 0) {
1450228753Smm		failure_start(file, line, "Can't GetFileTime %s\n", pathname);
1451228753Smm		failure_finish(NULL);
1452228753Smm		return (0);
1453228753Smm	}
1454248590Smm	wintm.LowPart = fxtime.dwLowDateTime;
1455248590Smm	wintm.HighPart = fxtime.dwHighDateTime;
1456228753Smm	filet = (wintm.QuadPart - EPOC_TIME) / 10000000;
1457228753Smm	filet_nsec = ((wintm.QuadPart - EPOC_TIME) % 10000000) * 100;
1458228753Smm	nsec = (nsec / 100) * 100; /* Round the request */
1459228753Smm#else
1460228753Smm	struct stat st;
1461228753Smm
1462228753Smm	assertion_count(file, line);
1463228753Smm	r = lstat(pathname, &st);
1464228753Smm	if (r != 0) {
1465228753Smm		failure_start(file, line, "Can't stat %s\n", pathname);
1466228753Smm		failure_finish(NULL);
1467228753Smm		return (0);
1468228753Smm	}
1469228753Smm	switch (type) {
1470228753Smm	case 'a': filet = st.st_atime; break;
1471228753Smm	case 'm': filet = st.st_mtime; break;
1472228753Smm	case 'b': filet = 0; break;
1473228753Smm	default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);
1474228753Smm		exit(1);
1475228753Smm	}
1476228753Smm#if defined(__FreeBSD__)
1477228753Smm	switch (type) {
1478228753Smm	case 'a': filet_nsec = st.st_atimespec.tv_nsec; break;
1479228753Smm	case 'b': filet = st.st_birthtime;
1480302264Smm		/* FreeBSD filesystems that don't support birthtime
1481302264Smm		 * (e.g., UFS1) always return -1 here. */
1482302264Smm		if (filet == -1) {
1483302264Smm			return (1);
1484302264Smm		}
1485228753Smm		filet_nsec = st.st_birthtimespec.tv_nsec; break;
1486228753Smm	case 'm': filet_nsec = st.st_mtimespec.tv_nsec; break;
1487228753Smm	default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);
1488228753Smm		exit(1);
1489228753Smm	}
1490228753Smm	/* FreeBSD generally only stores to microsecond res, so round. */
1491228753Smm	filet_nsec = (filet_nsec / 1000) * 1000;
1492228753Smm	nsec = (nsec / 1000) * 1000;
1493228753Smm#else
1494228753Smm	filet_nsec = nsec = 0;	/* Generic POSIX only has whole seconds. */
1495228753Smm	if (type == 'b') return (1); /* Generic POSIX doesn't have birthtime */
1496228753Smm#if defined(__HAIKU__)
1497228753Smm	if (type == 'a') return (1); /* Haiku doesn't have atime. */
1498228753Smm#endif
1499228753Smm#endif
1500228753Smm#endif
1501228753Smm	if (recent) {
1502228753Smm		/* Check that requested time is up-to-date. */
1503228753Smm		time_t now = time(NULL);
1504228753Smm		if (filet < now - 10 || filet > now + 1) {
1505228753Smm			failure_start(file, line,
1506231200Smm			    "File %s has %ctime %lld, %lld seconds ago\n",
1507228753Smm			    pathname, type, filet, now - filet);
1508228753Smm			failure_finish(NULL);
1509228753Smm			return (0);
1510228753Smm		}
1511228753Smm	} else if (filet != t || filet_nsec != nsec) {
1512228753Smm		failure_start(file, line,
1513358090Smm		    "File %s has %ctime %lld.%09lld, expected %ld.%09ld",
1514228753Smm		    pathname, type, filet, filet_nsec, t, nsec);
1515228753Smm		failure_finish(NULL);
1516228753Smm		return (0);
1517228753Smm	}
1518228753Smm	return (1);
1519228753Smm}
1520228753Smm
1521228753Smm/* Verify atime of 'pathname'. */
1522228753Smmint
1523228753Smmassertion_file_atime(const char *file, int line,
1524228753Smm    const char *pathname, long t, long nsec)
1525228753Smm{
1526228753Smm	return assertion_file_time(file, line, pathname, t, nsec, 'a', 0);
1527228753Smm}
1528228753Smm
1529228753Smm/* Verify atime of 'pathname' is up-to-date. */
1530228753Smmint
1531228753Smmassertion_file_atime_recent(const char *file, int line, const char *pathname)
1532228753Smm{
1533228753Smm	return assertion_file_time(file, line, pathname, 0, 0, 'a', 1);
1534228753Smm}
1535228753Smm
1536228753Smm/* Verify birthtime of 'pathname'. */
1537228753Smmint
1538228753Smmassertion_file_birthtime(const char *file, int line,
1539228753Smm    const char *pathname, long t, long nsec)
1540228753Smm{
1541228753Smm	return assertion_file_time(file, line, pathname, t, nsec, 'b', 0);
1542228753Smm}
1543228753Smm
1544228753Smm/* Verify birthtime of 'pathname' is up-to-date. */
1545228753Smmint
1546228753Smmassertion_file_birthtime_recent(const char *file, int line,
1547228753Smm    const char *pathname)
1548228753Smm{
1549228753Smm	return assertion_file_time(file, line, pathname, 0, 0, 'b', 1);
1550228753Smm}
1551228753Smm
1552307214Smm/* Verify mode of 'pathname'. */
1553307214Smmint
1554307214Smmassertion_file_mode(const char *file, int line, const char *pathname, int expected_mode)
1555307214Smm{
1556307214Smm	int mode;
1557307214Smm	int r;
1558307214Smm
1559307214Smm	assertion_count(file, line);
1560307214Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1561307214Smm	failure_start(file, line, "assertFileMode not yet implemented for Windows");
1562307859Smm	(void)mode; /* UNUSED */
1563307859Smm	(void)r; /* UNUSED */
1564313071Smm	(void)pathname; /* UNUSED */
1565313071Smm	(void)expected_mode; /* UNUSED */
1566307214Smm#else
1567307214Smm	{
1568307214Smm		struct stat st;
1569307214Smm		r = lstat(pathname, &st);
1570307214Smm		mode = (int)(st.st_mode & 0777);
1571307214Smm	}
1572307214Smm	if (r == 0 && mode == expected_mode)
1573307214Smm			return (1);
1574307214Smm	failure_start(file, line, "File %s has mode %o, expected %o",
1575307214Smm	    pathname, mode, expected_mode);
1576307214Smm#endif
1577307214Smm	failure_finish(NULL);
1578307214Smm	return (0);
1579307214Smm}
1580307214Smm
1581228753Smm/* Verify mtime of 'pathname'. */
1582228753Smmint
1583228753Smmassertion_file_mtime(const char *file, int line,
1584228753Smm    const char *pathname, long t, long nsec)
1585228753Smm{
1586228753Smm	return assertion_file_time(file, line, pathname, t, nsec, 'm', 0);
1587228753Smm}
1588228753Smm
1589228753Smm/* Verify mtime of 'pathname' is up-to-date. */
1590228753Smmint
1591228753Smmassertion_file_mtime_recent(const char *file, int line, const char *pathname)
1592228753Smm{
1593228753Smm	return assertion_file_time(file, line, pathname, 0, 0, 'm', 1);
1594228753Smm}
1595228753Smm
1596228753Smm/* Verify number of links to 'pathname'. */
1597228753Smmint
1598228753Smmassertion_file_nlinks(const char *file, int line,
1599228753Smm    const char *pathname, int nlinks)
1600228753Smm{
1601228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1602228753Smm	BY_HANDLE_FILE_INFORMATION bhfi;
1603228753Smm	int r;
1604228753Smm
1605228753Smm	assertion_count(file, line);
1606228753Smm	r = my_GetFileInformationByName(pathname, &bhfi);
1607228753Smm	if (r != 0 && bhfi.nNumberOfLinks == (DWORD)nlinks)
1608228753Smm		return (1);
1609358090Smm	failure_start(file, line, "File %s has %jd links, expected %d",
1610358090Smm	    pathname, (intmax_t)bhfi.nNumberOfLinks, nlinks);
1611228753Smm	failure_finish(NULL);
1612228753Smm	return (0);
1613228753Smm#else
1614228753Smm	struct stat st;
1615228753Smm	int r;
1616228753Smm
1617228753Smm	assertion_count(file, line);
1618228753Smm	r = lstat(pathname, &st);
1619231297Smm	if (r == 0 && (int)st.st_nlink == nlinks)
1620307214Smm		return (1);
1621358090Smm	failure_start(file, line, "File %s has %jd links, expected %d",
1622358090Smm	    pathname, (intmax_t)st.st_nlink, nlinks);
1623228753Smm	failure_finish(NULL);
1624228753Smm	return (0);
1625228753Smm#endif
1626228753Smm}
1627228753Smm
1628228753Smm/* Verify size of 'pathname'. */
1629228753Smmint
1630228753Smmassertion_file_size(const char *file, int line, const char *pathname, long size)
1631228753Smm{
1632228753Smm	int64_t filesize;
1633228753Smm	int r;
1634228753Smm
1635228753Smm	assertion_count(file, line);
1636228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1637228753Smm	{
1638228753Smm		BY_HANDLE_FILE_INFORMATION bhfi;
1639228753Smm		r = !my_GetFileInformationByName(pathname, &bhfi);
1640228753Smm		filesize = ((int64_t)bhfi.nFileSizeHigh << 32) + bhfi.nFileSizeLow;
1641228753Smm	}
1642228753Smm#else
1643228753Smm	{
1644228753Smm		struct stat st;
1645228753Smm		r = lstat(pathname, &st);
1646228753Smm		filesize = st.st_size;
1647228753Smm	}
1648228753Smm#endif
1649228753Smm	if (r == 0 && filesize == size)
1650228753Smm			return (1);
1651228753Smm	failure_start(file, line, "File %s has size %ld, expected %ld",
1652228753Smm	    pathname, (long)filesize, (long)size);
1653228753Smm	failure_finish(NULL);
1654228753Smm	return (0);
1655228753Smm}
1656228753Smm
1657228753Smm/* Assert that 'pathname' is a dir.  If mode >= 0, verify that too. */
1658228753Smmint
1659228753Smmassertion_is_dir(const char *file, int line, const char *pathname, int mode)
1660228753Smm{
1661228753Smm	struct stat st;
1662228753Smm	int r;
1663228753Smm
1664228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1665228753Smm	(void)mode; /* UNUSED */
1666228753Smm#endif
1667228753Smm	assertion_count(file, line);
1668228753Smm	r = lstat(pathname, &st);
1669228753Smm	if (r != 0) {
1670228753Smm		failure_start(file, line, "Dir should exist: %s", pathname);
1671228753Smm		failure_finish(NULL);
1672228753Smm		return (0);
1673228753Smm	}
1674228753Smm	if (!S_ISDIR(st.st_mode)) {
1675228753Smm		failure_start(file, line, "%s is not a dir", pathname);
1676228753Smm		failure_finish(NULL);
1677228753Smm		return (0);
1678228753Smm	}
1679228753Smm#if !defined(_WIN32) || defined(__CYGWIN__)
1680228753Smm	/* Windows doesn't handle permissions the same way as POSIX,
1681228753Smm	 * so just ignore the mode tests. */
1682228753Smm	/* TODO: Can we do better here? */
1683231297Smm	if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {
1684228753Smm		failure_start(file, line, "Dir %s has wrong mode", pathname);
1685228753Smm		logprintf("  Expected: 0%3o\n", mode);
1686228753Smm		logprintf("  Found: 0%3o\n", st.st_mode & 07777);
1687228753Smm		failure_finish(NULL);
1688228753Smm		return (0);
1689228753Smm	}
1690228753Smm#endif
1691228753Smm	return (1);
1692228753Smm}
1693228753Smm
1694228753Smm/* Verify that 'pathname' is a regular file.  If 'mode' is >= 0,
1695228753Smm * verify that too. */
1696228753Smmint
1697228753Smmassertion_is_reg(const char *file, int line, const char *pathname, int mode)
1698228753Smm{
1699228753Smm	struct stat st;
1700228753Smm	int r;
1701228753Smm
1702228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1703228753Smm	(void)mode; /* UNUSED */
1704228753Smm#endif
1705228753Smm	assertion_count(file, line);
1706228753Smm	r = lstat(pathname, &st);
1707228753Smm	if (r != 0 || !S_ISREG(st.st_mode)) {
1708228753Smm		failure_start(file, line, "File should exist: %s", pathname);
1709228753Smm		failure_finish(NULL);
1710228753Smm		return (0);
1711228753Smm	}
1712228753Smm#if !defined(_WIN32) || defined(__CYGWIN__)
1713228753Smm	/* Windows doesn't handle permissions the same way as POSIX,
1714228753Smm	 * so just ignore the mode tests. */
1715228753Smm	/* TODO: Can we do better here? */
1716231297Smm	if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {
1717228753Smm		failure_start(file, line, "File %s has wrong mode", pathname);
1718228753Smm		logprintf("  Expected: 0%3o\n", mode);
1719228753Smm		logprintf("  Found: 0%3o\n", st.st_mode & 07777);
1720228753Smm		failure_finish(NULL);
1721228753Smm		return (0);
1722228753Smm	}
1723228753Smm#endif
1724228753Smm	return (1);
1725228753Smm}
1726228753Smm
1727348608Smm/*
1728348608Smm * Check whether 'pathname' is a symbolic link.  If 'contents' is
1729348608Smm * non-NULL, verify that the symlink has those contents.
1730348608Smm *
1731348608Smm * On platforms with directory symlinks, set isdir to 0 to test for a file
1732348608Smm * symlink and to 1 to test for a directory symlink. On other platforms
1733348608Smm * the variable is ignored.
1734348608Smm */
1735228753Smmstatic int
1736228753Smmis_symlink(const char *file, int line,
1737348608Smm    const char *pathname, const char *contents, int isdir)
1738228753Smm{
1739228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1740348608Smm	HANDLE h;
1741348608Smm	DWORD inbytes;
1742348608Smm	REPARSE_DATA_BUFFER *buf;
1743348608Smm	BY_HANDLE_FILE_INFORMATION st;
1744348608Smm	size_t len, len2;
1745348608Smm	wchar_t *linknamew, *contentsw;
1746348608Smm	const char *p;
1747348608Smm	char *s, *pn;
1748348608Smm	int ret = 0;
1749348608Smm	BYTE *indata;
1750348608Smm	const DWORD flag = FILE_FLAG_BACKUP_SEMANTICS |
1751348608Smm	    FILE_FLAG_OPEN_REPARSE_POINT;
1752348608Smm
1753348608Smm	/* Replace slashes with backslashes in pathname */
1754348608Smm	pn = malloc((strlen(pathname) + 1) * sizeof(char));
1755348608Smm	p = pathname;
1756348608Smm	s = pn;
1757348608Smm	while(*p != '\0') {
1758348608Smm		if(*p == '/')
1759348608Smm			*s = '\\';
1760348608Smm		else
1761348608Smm			*s = *p;
1762348608Smm		p++;
1763348608Smm		s++;
1764348608Smm	}
1765348608Smm	*s = '\0';
1766348608Smm
1767348608Smm	h = CreateFileA(pn, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1768348608Smm	    flag, NULL);
1769348608Smm	free(pn);
1770348608Smm	if (h == INVALID_HANDLE_VALUE) {
1771348608Smm		failure_start(file, line, "Can't access %s\n", pathname);
1772348608Smm		failure_finish(NULL);
1773348608Smm		return (0);
1774348608Smm	}
1775348608Smm	ret = GetFileInformationByHandle(h, &st);
1776348608Smm	if (ret == 0) {
1777348608Smm		failure_start(file, line,
1778348608Smm		    "Can't stat: %s", pathname);
1779348608Smm		failure_finish(NULL);
1780348608Smm	} else if ((st.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) {
1781348608Smm		failure_start(file, line,
1782348608Smm		    "Not a symlink: %s", pathname);
1783348608Smm		failure_finish(NULL);
1784348608Smm		ret = 0;
1785348608Smm	}
1786348608Smm	if (isdir && ((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) {
1787348608Smm		failure_start(file, line,
1788348608Smm		    "Not a directory symlink: %s", pathname);
1789348608Smm		failure_finish(NULL);
1790348608Smm		ret = 0;
1791348608Smm	}
1792348608Smm	if (!isdir &&
1793348608Smm	    ((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
1794348608Smm		failure_start(file, line,
1795348608Smm		    "Not a file symlink: %s", pathname);
1796348608Smm		failure_finish(NULL);
1797348608Smm		ret = 0;
1798348608Smm	}
1799348608Smm	if (ret == 0) {
1800348608Smm		CloseHandle(h);
1801348608Smm		return (0);
1802348608Smm	}
1803348608Smm
1804348608Smm	indata = malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
1805348608Smm	ret = DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, NULL, 0, indata,
1806348608Smm	    1024, &inbytes, NULL);
1807348608Smm	CloseHandle(h);
1808348608Smm	if (ret == 0) {
1809348608Smm		free(indata);
1810348608Smm		failure_start(file, line,
1811348608Smm		    "Could not retrieve symlink target: %s", pathname);
1812348608Smm		failure_finish(NULL);
1813348608Smm		return (0);
1814348608Smm	}
1815348608Smm
1816348608Smm	buf = (REPARSE_DATA_BUFFER *) indata;
1817348608Smm	if (buf->ReparseTag != IO_REPARSE_TAG_SYMLINK) {
1818348608Smm		free(indata);
1819348608Smm		/* File is not a symbolic link */
1820348608Smm		failure_start(file, line,
1821348608Smm		    "Not a symlink: %s", pathname);
1822348608Smm		failure_finish(NULL);
1823348608Smm		return (0);
1824348608Smm	}
1825348608Smm
1826348608Smm	if (contents == NULL) {
1827348608Smm		free(indata);
1828348608Smm		return (1);
1829348608Smm	}
1830348608Smm
1831348608Smm	len = buf->SymbolicLinkReparseBuffer.SubstituteNameLength;
1832348608Smm
1833348608Smm	linknamew = malloc(len + sizeof(wchar_t));
1834348608Smm	if (linknamew == NULL) {
1835348608Smm		free(indata);
1836348608Smm		return (0);
1837348608Smm	}
1838348608Smm
1839348608Smm	memcpy(linknamew, &((BYTE *)buf->SymbolicLinkReparseBuffer.PathBuffer)
1840348608Smm	    [buf->SymbolicLinkReparseBuffer.SubstituteNameOffset], len);
1841348608Smm	free(indata);
1842348608Smm
1843348608Smm	linknamew[len / sizeof(wchar_t)] = L'\0';
1844348608Smm
1845348608Smm	contentsw = malloc(len + sizeof(wchar_t));
1846348608Smm	if (contentsw == NULL) {
1847348608Smm		free(linknamew);
1848348608Smm		return (0);
1849348608Smm	}
1850348608Smm
1851348608Smm	len2 = mbsrtowcs(contentsw, &contents, (len + sizeof(wchar_t)
1852348608Smm	    / sizeof(wchar_t)), NULL);
1853348608Smm
1854348608Smm	if (len2 > 0 && wcscmp(linknamew, contentsw) != 0)
1855348608Smm		ret = 1;
1856348608Smm
1857348608Smm	free(linknamew);
1858348608Smm	free(contentsw);
1859348608Smm	return (ret);
1860228753Smm#else
1861228753Smm	char buff[300];
1862228753Smm	struct stat st;
1863228753Smm	ssize_t linklen;
1864228753Smm	int r;
1865228753Smm
1866348608Smm	(void)isdir; /* UNUSED */
1867228753Smm	assertion_count(file, line);
1868228753Smm	r = lstat(pathname, &st);
1869228753Smm	if (r != 0) {
1870228753Smm		failure_start(file, line,
1871228753Smm		    "Symlink should exist: %s", pathname);
1872228753Smm		failure_finish(NULL);
1873228753Smm		return (0);
1874228753Smm	}
1875228753Smm	if (!S_ISLNK(st.st_mode))
1876228753Smm		return (0);
1877228753Smm	if (contents == NULL)
1878228753Smm		return (1);
1879358090Smm	linklen = readlink(pathname, buff, sizeof(buff) - 1);
1880228753Smm	if (linklen < 0) {
1881228753Smm		failure_start(file, line, "Can't read symlink %s", pathname);
1882228753Smm		failure_finish(NULL);
1883228753Smm		return (0);
1884228753Smm	}
1885228753Smm	buff[linklen] = '\0';
1886228753Smm	if (strcmp(buff, contents) != 0)
1887228753Smm		return (0);
1888228753Smm	return (1);
1889228753Smm#endif
1890228753Smm}
1891228753Smm
1892228753Smm/* Assert that path is a symlink that (optionally) contains contents. */
1893228753Smmint
1894228753Smmassertion_is_symlink(const char *file, int line,
1895348608Smm    const char *path, const char *contents, int isdir)
1896228753Smm{
1897348608Smm	if (is_symlink(file, line, path, contents, isdir))
1898228753Smm		return (1);
1899228753Smm	if (contents)
1900228753Smm		failure_start(file, line, "File %s is not a symlink to %s",
1901228753Smm		    path, contents);
1902228753Smm	else
1903228753Smm		failure_start(file, line, "File %s is not a symlink", path);
1904228753Smm	failure_finish(NULL);
1905228753Smm	return (0);
1906228753Smm}
1907228753Smm
1908228753Smm
1909228753Smm/* Create a directory and report any errors. */
1910228753Smmint
1911228753Smmassertion_make_dir(const char *file, int line, const char *dirname, int mode)
1912228753Smm{
1913228753Smm	assertion_count(file, line);
1914228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1915228753Smm	(void)mode; /* UNUSED */
1916228753Smm	if (0 == _mkdir(dirname))
1917228753Smm		return (1);
1918228753Smm#else
1919306669Smm	if (0 == mkdir(dirname, mode)) {
1920306669Smm		if (0 == chmod(dirname, mode)) {
1921306669Smm			assertion_file_mode(file, line, dirname, mode);
1922306669Smm			return (1);
1923306669Smm		}
1924306669Smm	}
1925228753Smm#endif
1926228753Smm	failure_start(file, line, "Could not create directory %s", dirname);
1927228753Smm	failure_finish(NULL);
1928228753Smm	return(0);
1929228753Smm}
1930228753Smm
1931228753Smm/* Create a file with the specified contents and report any failures. */
1932228753Smmint
1933228753Smmassertion_make_file(const char *file, int line,
1934238825Smm    const char *path, int mode, int csize, const void *contents)
1935228753Smm{
1936228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1937228753Smm	/* TODO: Rework this to set file mode as well. */
1938228753Smm	FILE *f;
1939228753Smm	(void)mode; /* UNUSED */
1940228753Smm	assertion_count(file, line);
1941228753Smm	f = fopen(path, "wb");
1942228753Smm	if (f == NULL) {
1943228753Smm		failure_start(file, line, "Could not create file %s", path);
1944228753Smm		failure_finish(NULL);
1945228753Smm		return (0);
1946228753Smm	}
1947228753Smm	if (contents != NULL) {
1948238825Smm		size_t wsize;
1949238825Smm
1950238825Smm		if (csize < 0)
1951238825Smm			wsize = strlen(contents);
1952238825Smm		else
1953238825Smm			wsize = (size_t)csize;
1954238825Smm		if (wsize != fwrite(contents, 1, wsize, f)) {
1955228753Smm			fclose(f);
1956228753Smm			failure_start(file, line,
1957228753Smm			    "Could not write file %s", path);
1958228753Smm			failure_finish(NULL);
1959228753Smm			return (0);
1960228753Smm		}
1961228753Smm	}
1962228753Smm	fclose(f);
1963228753Smm	return (1);
1964228753Smm#else
1965228753Smm	int fd;
1966228753Smm	assertion_count(file, line);
1967228753Smm	fd = open(path, O_CREAT | O_WRONLY, mode >= 0 ? mode : 0644);
1968228753Smm	if (fd < 0) {
1969228753Smm		failure_start(file, line, "Could not create %s", path);
1970228753Smm		failure_finish(NULL);
1971228753Smm		return (0);
1972228753Smm	}
1973306669Smm	if (0 != chmod(path, mode)) {
1974306669Smm		failure_start(file, line, "Could not chmod %s", path);
1975306669Smm		failure_finish(NULL);
1976307214Smm		close(fd);
1977306669Smm		return (0);
1978306669Smm	}
1979228753Smm	if (contents != NULL) {
1980238825Smm		ssize_t wsize;
1981238825Smm
1982238825Smm		if (csize < 0)
1983238825Smm			wsize = (ssize_t)strlen(contents);
1984238825Smm		else
1985238825Smm			wsize = (ssize_t)csize;
1986238825Smm		if (wsize != write(fd, contents, wsize)) {
1987228753Smm			close(fd);
1988238825Smm			failure_start(file, line,
1989238825Smm			    "Could not write to %s", path);
1990228753Smm			failure_finish(NULL);
1991307214Smm			close(fd);
1992228753Smm			return (0);
1993228753Smm		}
1994228753Smm	}
1995228753Smm	close(fd);
1996306669Smm	assertion_file_mode(file, line, path, mode);
1997228753Smm	return (1);
1998228753Smm#endif
1999228753Smm}
2000228753Smm
2001228753Smm/* Create a hardlink and report any failures. */
2002228753Smmint
2003228753Smmassertion_make_hardlink(const char *file, int line,
2004228753Smm    const char *newpath, const char *linkto)
2005228753Smm{
2006228753Smm	int succeeded;
2007228753Smm
2008228753Smm	assertion_count(file, line);
2009228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
2010228753Smm	succeeded = my_CreateHardLinkA(newpath, linkto);
2011228753Smm#elif HAVE_LINK
2012228753Smm	succeeded = !link(linkto, newpath);
2013228753Smm#else
2014228753Smm	succeeded = 0;
2015228753Smm#endif
2016228753Smm	if (succeeded)
2017228753Smm		return (1);
2018228753Smm	failure_start(file, line, "Could not create hardlink");
2019228753Smm	logprintf("   New link: %s\n", newpath);
2020228753Smm	logprintf("   Old name: %s\n", linkto);
2021228753Smm	failure_finish(NULL);
2022228753Smm	return(0);
2023228753Smm}
2024228753Smm
2025348608Smm/*
2026348608Smm * Create a symlink and report any failures.
2027348608Smm *
2028348608Smm * Windows symlinks need to know if the target is a directory.
2029348608Smm */
2030228753Smmint
2031228753Smmassertion_make_symlink(const char *file, int line,
2032348608Smm    const char *newpath, const char *linkto, int targetIsDir)
2033228753Smm{
2034228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
2035228753Smm	assertion_count(file, line);
2036228753Smm	if (my_CreateSymbolicLinkA(newpath, linkto, targetIsDir))
2037228753Smm		return (1);
2038228753Smm#elif HAVE_SYMLINK
2039348608Smm	(void)targetIsDir; /* UNUSED */
2040228753Smm	assertion_count(file, line);
2041228753Smm	if (0 == symlink(linkto, newpath))
2042228753Smm		return (1);
2043348608Smm#else
2044348608Smm	(void)targetIsDir; /* UNUSED */
2045228753Smm#endif
2046228753Smm	failure_start(file, line, "Could not create symlink");
2047228753Smm	logprintf("   New link: %s\n", newpath);
2048228753Smm	logprintf("   Old name: %s\n", linkto);
2049228753Smm	failure_finish(NULL);
2050228753Smm	return(0);
2051228753Smm}
2052228753Smm
2053228753Smm/* Set umask, report failures. */
2054228753Smmint
2055228753Smmassertion_umask(const char *file, int line, int mask)
2056228753Smm{
2057228753Smm	assertion_count(file, line);
2058228753Smm	(void)file; /* UNUSED */
2059228753Smm	(void)line; /* UNUSED */
2060228753Smm	umask(mask);
2061228753Smm	return (1);
2062228753Smm}
2063228753Smm
2064231200Smm/* Set times, report failures. */
2065231200Smmint
2066231200Smmassertion_utimes(const char *file, int line,
2067231200Smm    const char *pathname, long at, long at_nsec, long mt, long mt_nsec)
2068231200Smm{
2069231200Smm	int r;
2070231200Smm
2071231200Smm#if defined(_WIN32) && !defined(__CYGWIN__)
2072231200Smm#define WINTIME(sec, nsec) ((Int32x32To64(sec, 10000000) + EPOC_TIME)\
2073231200Smm	 + (((nsec)/1000)*10))
2074231200Smm	HANDLE h;
2075231200Smm	ULARGE_INTEGER wintm;
2076231200Smm	FILETIME fatime, fmtime;
2077231200Smm	FILETIME *pat, *pmt;
2078231200Smm
2079231200Smm	assertion_count(file, line);
2080231200Smm	h = CreateFileA(pathname,GENERIC_READ | GENERIC_WRITE,
2081231200Smm		    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
2082231200Smm		    FILE_FLAG_BACKUP_SEMANTICS, NULL);
2083231200Smm	if (h == INVALID_HANDLE_VALUE) {
2084231200Smm		failure_start(file, line, "Can't access %s\n", pathname);
2085231200Smm		failure_finish(NULL);
2086231200Smm		return (0);
2087231200Smm	}
2088231200Smm
2089231200Smm	if (at > 0 || at_nsec > 0) {
2090231200Smm		wintm.QuadPart = WINTIME(at, at_nsec);
2091231200Smm		fatime.dwLowDateTime = wintm.LowPart;
2092231200Smm		fatime.dwHighDateTime = wintm.HighPart;
2093231200Smm		pat = &fatime;
2094231200Smm	} else
2095231200Smm		pat = NULL;
2096231200Smm	if (mt > 0 || mt_nsec > 0) {
2097231200Smm		wintm.QuadPart = WINTIME(mt, mt_nsec);
2098231200Smm		fmtime.dwLowDateTime = wintm.LowPart;
2099231200Smm		fmtime.dwHighDateTime = wintm.HighPart;
2100231200Smm		pmt = &fmtime;
2101231200Smm	} else
2102231200Smm		pmt = NULL;
2103231200Smm	if (pat != NULL || pmt != NULL)
2104231200Smm		r = SetFileTime(h, NULL, pat, pmt);
2105231200Smm	else
2106231200Smm		r = 1;
2107231200Smm	CloseHandle(h);
2108231200Smm	if (r == 0) {
2109231200Smm		failure_start(file, line, "Can't SetFileTime %s\n", pathname);
2110231200Smm		failure_finish(NULL);
2111231200Smm		return (0);
2112231200Smm	}
2113231200Smm	return (1);
2114231200Smm#else /* defined(_WIN32) && !defined(__CYGWIN__) */
2115231200Smm	struct stat st;
2116231200Smm	struct timeval times[2];
2117231200Smm
2118231200Smm#if !defined(__FreeBSD__)
2119231200Smm	mt_nsec = at_nsec = 0;	/* Generic POSIX only has whole seconds. */
2120231200Smm#endif
2121231200Smm	if (mt == 0 && mt_nsec == 0 && at == 0 && at_nsec == 0)
2122231200Smm		return (1);
2123231200Smm
2124231200Smm	r = lstat(pathname, &st);
2125231200Smm	if (r < 0) {
2126231200Smm		failure_start(file, line, "Can't stat %s\n", pathname);
2127231200Smm		failure_finish(NULL);
2128231200Smm		return (0);
2129231200Smm	}
2130231200Smm
2131231200Smm	if (mt == 0 && mt_nsec == 0) {
2132231200Smm		mt = st.st_mtime;
2133231200Smm#if defined(__FreeBSD__)
2134231200Smm		mt_nsec = st.st_mtimespec.tv_nsec;
2135231200Smm		/* FreeBSD generally only stores to microsecond res, so round. */
2136231200Smm		mt_nsec = (mt_nsec / 1000) * 1000;
2137231200Smm#endif
2138231200Smm	}
2139231200Smm	if (at == 0 && at_nsec == 0) {
2140231200Smm		at = st.st_atime;
2141231200Smm#if defined(__FreeBSD__)
2142231200Smm		at_nsec = st.st_atimespec.tv_nsec;
2143231200Smm		/* FreeBSD generally only stores to microsecond res, so round. */
2144231200Smm		at_nsec = (at_nsec / 1000) * 1000;
2145231200Smm#endif
2146231200Smm	}
2147231200Smm
2148231200Smm	times[1].tv_sec = mt;
2149231200Smm	times[1].tv_usec = mt_nsec / 1000;
2150231200Smm
2151231200Smm	times[0].tv_sec = at;
2152231200Smm	times[0].tv_usec = at_nsec / 1000;
2153231200Smm
2154231200Smm#ifdef HAVE_LUTIMES
2155231200Smm	r = lutimes(pathname, times);
2156231200Smm#else
2157231200Smm	r = utimes(pathname, times);
2158231200Smm#endif
2159231200Smm	if (r < 0) {
2160231200Smm		failure_start(file, line, "Can't utimes %s\n", pathname);
2161231200Smm		failure_finish(NULL);
2162231200Smm		return (0);
2163231200Smm	}
2164231200Smm	return (1);
2165231200Smm#endif /* defined(_WIN32) && !defined(__CYGWIN__) */
2166231200Smm}
2167231200Smm
2168314571Smm/* Compare file flags */
2169314571Smmint
2170314571Smmassertion_compare_fflags(const char *file, int line, const char *patha,
2171314571Smm    const char *pathb, int nomatch)
2172314571Smm{
2173314571Smm#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2174314571Smm	struct stat sa, sb;
2175314571Smm
2176314571Smm	assertion_count(file, line);
2177314571Smm
2178314571Smm	if (stat(patha, &sa) < 0)
2179314571Smm		return (0);
2180314571Smm	if (stat(pathb, &sb) < 0)
2181314571Smm		return (0);
2182314571Smm	if (!nomatch && sa.st_flags != sb.st_flags) {
2183314571Smm		failure_start(file, line, "File flags should be identical: "
2184314571Smm		    "%s=%#010x %s=%#010x", patha, sa.st_flags, pathb,
2185314571Smm		    sb.st_flags);
2186314571Smm		failure_finish(NULL);
2187314571Smm		return (0);
2188314571Smm	}
2189314571Smm	if (nomatch && sa.st_flags == sb.st_flags) {
2190314571Smm		failure_start(file, line, "File flags should be different: "
2191314571Smm		    "%s=%#010x %s=%#010x", patha, sa.st_flags, pathb,
2192314571Smm		    sb.st_flags);
2193314571Smm		failure_finish(NULL);
2194314571Smm		return (0);
2195314571Smm	}
2196314571Smm#elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) && \
2197314571Smm       defined(FS_NODUMP_FL)) || \
2198314571Smm      (defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \
2199314571Smm         && defined(EXT2_NODUMP_FL))
2200314571Smm	int fd, r, flagsa, flagsb;
2201314571Smm
2202314571Smm	assertion_count(file, line);
2203314571Smm	fd = open(patha, O_RDONLY | O_NONBLOCK);
2204314571Smm	if (fd < 0) {
2205314571Smm		failure_start(file, line, "Can't open %s\n", patha);
2206314571Smm		failure_finish(NULL);
2207314571Smm		return (0);
2208314571Smm	}
2209314571Smm	r = ioctl(fd,
2210314571Smm#ifdef FS_IOC_GETFLAGS
2211314571Smm	    FS_IOC_GETFLAGS,
2212314571Smm#else
2213314571Smm	    EXT2_IOC_GETFLAGS,
2214314571Smm#endif
2215314571Smm	    &flagsa);
2216314571Smm	close(fd);
2217314571Smm	if (r < 0) {
2218314571Smm		failure_start(file, line, "Can't get flags %s\n", patha);
2219314571Smm		failure_finish(NULL);
2220314571Smm		return (0);
2221314571Smm	}
2222314571Smm	fd = open(pathb, O_RDONLY | O_NONBLOCK);
2223314571Smm	if (fd < 0) {
2224314571Smm		failure_start(file, line, "Can't open %s\n", pathb);
2225314571Smm		failure_finish(NULL);
2226314571Smm		return (0);
2227314571Smm	}
2228314571Smm	r = ioctl(fd,
2229314571Smm#ifdef FS_IOC_GETFLAGS
2230314571Smm	    FS_IOC_GETFLAGS,
2231314571Smm#else
2232314571Smm	    EXT2_IOC_GETFLAGS,
2233314571Smm#endif
2234314571Smm	    &flagsb);
2235314571Smm	close(fd);
2236314571Smm	if (r < 0) {
2237314571Smm		failure_start(file, line, "Can't get flags %s\n", pathb);
2238314571Smm		failure_finish(NULL);
2239314571Smm		return (0);
2240314571Smm	}
2241314571Smm	if (!nomatch && flagsa != flagsb) {
2242314571Smm		failure_start(file, line, "File flags should be identical: "
2243314571Smm		    "%s=%#010x %s=%#010x", patha, flagsa, pathb, flagsb);
2244314571Smm		failure_finish(NULL);
2245314571Smm		return (0);
2246314571Smm	}
2247314571Smm	if (nomatch && flagsa == flagsb) {
2248314571Smm		failure_start(file, line, "File flags should be different: "
2249314571Smm		    "%s=%#010x %s=%#010x", patha, flagsa, pathb, flagsb);
2250314571Smm		failure_finish(NULL);
2251314571Smm		return (0);
2252314571Smm	}
2253314571Smm#else
2254314571Smm	(void)patha; /* UNUSED */
2255314571Smm	(void)pathb; /* UNUSED */
2256314571Smm	(void)nomatch; /* UNUSED */
2257314571Smm	assertion_count(file, line);
2258314571Smm#endif
2259314571Smm	return (1);
2260314571Smm}
2261314571Smm
2262238825Smm/* Set nodump, report failures. */
2263238825Smmint
2264314571Smmassertion_set_nodump(const char *file, int line, const char *pathname)
2265238825Smm{
2266238825Smm#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2267238825Smm	int r;
2268238825Smm
2269238825Smm	assertion_count(file, line);
2270238825Smm	r = chflags(pathname, UF_NODUMP);
2271238825Smm	if (r < 0) {
2272238825Smm		failure_start(file, line, "Can't set nodump %s\n", pathname);
2273238825Smm		failure_finish(NULL);
2274238825Smm		return (0);
2275238825Smm	}
2276314565Smm#elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) && \
2277314565Smm       defined(FS_NODUMP_FL)) || \
2278314565Smm      (defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \
2279314565Smm	 && defined(EXT2_NODUMP_FL))
2280238825Smm	int fd, r, flags;
2281238825Smm
2282238825Smm	assertion_count(file, line);
2283238825Smm	fd = open(pathname, O_RDONLY | O_NONBLOCK);
2284238825Smm	if (fd < 0) {
2285238825Smm		failure_start(file, line, "Can't open %s\n", pathname);
2286238825Smm		failure_finish(NULL);
2287238825Smm		return (0);
2288238825Smm	}
2289314565Smm	r = ioctl(fd,
2290314565Smm#ifdef FS_IOC_GETFLAGS
2291314565Smm	    FS_IOC_GETFLAGS,
2292314565Smm#else
2293314565Smm	    EXT2_IOC_GETFLAGS,
2294314565Smm#endif
2295314565Smm	    &flags);
2296238825Smm	if (r < 0) {
2297238825Smm		failure_start(file, line, "Can't get flags %s\n", pathname);
2298238825Smm		failure_finish(NULL);
2299238825Smm		return (0);
2300238825Smm	}
2301314565Smm#ifdef FS_NODUMP_FL
2302314565Smm	flags |= FS_NODUMP_FL;
2303314565Smm#else
2304238825Smm	flags |= EXT2_NODUMP_FL;
2305314565Smm#endif
2306314565Smm
2307314565Smm	 r = ioctl(fd,
2308314565Smm#ifdef FS_IOC_SETFLAGS
2309314565Smm	    FS_IOC_SETFLAGS,
2310314565Smm#else
2311314565Smm	    EXT2_IOC_SETFLAGS,
2312314565Smm#endif
2313314565Smm	    &flags);
2314238825Smm	if (r < 0) {
2315238825Smm		failure_start(file, line, "Can't set nodump %s\n", pathname);
2316238825Smm		failure_finish(NULL);
2317238825Smm		return (0);
2318238825Smm	}
2319238825Smm	close(fd);
2320238825Smm#else
2321238825Smm	(void)pathname; /* UNUSED */
2322238825Smm	assertion_count(file, line);
2323238825Smm#endif
2324238825Smm	return (1);
2325238825Smm}
2326238825Smm
2327314565Smm#ifdef PROGRAM
2328314565Smmstatic void assert_version_id(char **qq, size_t *ss)
2329314565Smm{
2330314565Smm	char *q = *qq;
2331314565Smm	size_t s = *ss;
2332314565Smm
2333314565Smm	/* Version number is a series of digits and periods. */
2334314565Smm	while (s > 0 && (*q == '.' || (*q >= '0' && *q <= '9'))) {
2335314565Smm		++q;
2336314565Smm		--s;
2337314565Smm	}
2338314565Smm
2339314565Smm	if (q[0] == 'd' && q[1] == 'e' && q[2] == 'v') {
2340314565Smm		q += 3;
2341314565Smm		s -= 3;
2342314565Smm	}
2343314565Smm
2344314565Smm	/* Skip a single trailing a,b,c, or d. */
2345314565Smm	if (*q == 'a' || *q == 'b' || *q == 'c' || *q == 'd')
2346314565Smm		++q;
2347314565Smm
2348314565Smm	/* Version number terminated by space. */
2349314565Smm	failure("No space after version: ``%s''", q);
2350314565Smm	assert(s > 1);
2351314565Smm	failure("No space after version: ``%s''", q);
2352314565Smm	assert(*q == ' ');
2353314565Smm
2354314565Smm	++q; --s;
2355314565Smm
2356314565Smm	*qq = q;
2357314565Smm	*ss = s;
2358314565Smm}
2359314565Smm
2360314565Smm
2361228753Smm/*
2362314565Smm * Check program version
2363314565Smm */
2364314565Smmvoid assertVersion(const char *prog, const char *base)
2365314565Smm{
2366314565Smm	int r;
2367314565Smm	char *p, *q;
2368314565Smm	size_t s;
2369337352Smm	size_t prog_len = strlen(base);
2370314565Smm
2371314565Smm	r = systemf("%s --version >version.stdout 2>version.stderr", prog);
2372314565Smm	if (r != 0)
2373314565Smm		r = systemf("%s -W version >version.stdout 2>version.stderr",
2374314565Smm		    prog);
2375314565Smm
2376314565Smm	failure("Unable to run either %s --version or %s -W version",
2377314565Smm		prog, prog);
2378314565Smm	if (!assert(r == 0))
2379314565Smm		return;
2380314565Smm
2381314565Smm	/* --version should generate nothing to stdout. */
2382314565Smm	assertEmptyFile("version.stderr");
2383314565Smm
2384314565Smm	/* Verify format of version message. */
2385314565Smm	q = p = slurpfile(&s, "version.stdout");
2386314565Smm
2387314565Smm	/* Version message should start with name of program, then space. */
2388314565Smm	assert(s > prog_len + 1);
2389314565Smm
2390314565Smm	failure("Version must start with '%s': ``%s''", base, p);
2391314565Smm	if (!assertEqualMem(q, base, prog_len)) {
2392314565Smm		free(p);
2393314565Smm		return;
2394314565Smm	}
2395314565Smm
2396314565Smm	q += prog_len; s -= prog_len;
2397314565Smm
2398314565Smm	assert(*q == ' ');
2399314565Smm	q++; s--;
2400314565Smm
2401314565Smm	assert_version_id(&q, &s);
2402314565Smm
2403314565Smm	/* Separator. */
2404314565Smm	failure("No `-' between program name and versions: ``%s''", p);
2405314565Smm	assertEqualMem(q, "- ", 2);
2406314565Smm	q += 2; s -= 2;
2407314565Smm
2408314565Smm	failure("Not long enough for libarchive version: ``%s''", p);
2409314565Smm	assert(s > 11);
2410314565Smm
2411314565Smm	failure("Libarchive version must start with `libarchive': ``%s''", p);
2412314565Smm	assertEqualMem(q, "libarchive ", 11);
2413314565Smm
2414314565Smm	q += 11; s -= 11;
2415314565Smm
2416314565Smm	assert_version_id(&q, &s);
2417314565Smm
2418314565Smm	/* Skip arbitrary third-party version numbers. */
2419314565Smm	while (s > 0 && (*q == ' ' || *q == '-' || *q == '/' || *q == '.' ||
2420339006Smm	    isalnum((unsigned char)*q))) {
2421314565Smm		++q;
2422314565Smm		--s;
2423314565Smm	}
2424314565Smm
2425314565Smm	/* All terminated by end-of-line. */
2426314565Smm	assert(s >= 1);
2427314565Smm
2428314565Smm	/* Skip an optional CR character (e.g., Windows) */
2429314565Smm	failure("Version output must end with \\n or \\r\\n");
2430314565Smm
2431314565Smm	if (*q == '\r') { ++q; --s; }
2432314565Smm	assertEqualMem(q, "\n", 1);
2433314565Smm
2434314565Smm	free(p);
2435314565Smm}
2436314565Smm#endif	/* PROGRAM */
2437314565Smm
2438314565Smm/*
2439228753Smm *
2440228753Smm *  UTILITIES for use by tests.
2441228753Smm *
2442228753Smm */
2443228753Smm
2444228753Smm/*
2445228753Smm * Check whether platform supports symlinks.  This is intended
2446228753Smm * for tests to use in deciding whether to bother testing symlink
2447228753Smm * support; if the platform doesn't support symlinks, there's no point
2448228753Smm * in checking whether the program being tested can create them.
2449228753Smm *
2450228753Smm * Note that the first time this test is called, we actually go out to
2451228753Smm * disk to create and verify a symlink.  This is necessary because
2452228753Smm * symlink support is actually a property of a particular filesystem
2453228753Smm * and can thus vary between directories on a single system.  After
2454228753Smm * the first call, this returns the cached result from memory, so it's
2455228753Smm * safe to call it as often as you wish.
2456228753Smm */
2457228753Smmint
2458228753SmmcanSymlink(void)
2459228753Smm{
2460228753Smm	/* Remember the test result */
2461228753Smm	static int value = 0, tested = 0;
2462228753Smm	if (tested)
2463228753Smm		return (value);
2464228753Smm
2465228753Smm	++tested;
2466238825Smm	assertion_make_file(__FILE__, __LINE__, "canSymlink.0", 0644, 1, "a");
2467228753Smm	/* Note: Cygwin has its own symlink() emulation that does not
2468228753Smm	 * use the Win32 CreateSymbolicLink() function. */
2469228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
2470228753Smm	value = my_CreateSymbolicLinkA("canSymlink.1", "canSymlink.0", 0)
2471348608Smm	    && is_symlink(__FILE__, __LINE__, "canSymlink.1", "canSymlink.0",
2472348608Smm	    0);
2473228753Smm#elif HAVE_SYMLINK
2474228753Smm	value = (0 == symlink("canSymlink.0", "canSymlink.1"))
2475348608Smm	    && is_symlink(__FILE__, __LINE__, "canSymlink.1","canSymlink.0",
2476348608Smm	    0);
2477228753Smm#endif
2478228753Smm	return (value);
2479228753Smm}
2480228753Smm
2481228753Smm/* Platform-dependent options for hiding the output of a subcommand. */
2482228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
2483228753Smmstatic const char *redirectArgs = ">NUL 2>NUL"; /* Win32 cmd.exe */
2484228753Smm#else
2485228753Smmstatic const char *redirectArgs = ">/dev/null 2>/dev/null"; /* POSIX 'sh' */
2486228753Smm#endif
2487248590Smm/*
2488248590Smm * Can this platform run the bzip2 program?
2489248590Smm */
2490228753Smmint
2491248590SmmcanBzip2(void)
2492248590Smm{
2493248590Smm	static int tested = 0, value = 0;
2494248590Smm	if (!tested) {
2495248590Smm		tested = 1;
2496358090Smm		if (systemf("bzip2 --help %s", redirectArgs) == 0)
2497248590Smm			value = 1;
2498248590Smm	}
2499248590Smm	return (value);
2500248590Smm}
2501248590Smm
2502248590Smm/*
2503248590Smm * Can this platform run the grzip program?
2504248590Smm */
2505248590Smmint
2506248590SmmcanGrzip(void)
2507248590Smm{
2508248590Smm	static int tested = 0, value = 0;
2509248590Smm	if (!tested) {
2510248590Smm		tested = 1;
2511248590Smm		if (systemf("grzip -V %s", redirectArgs) == 0)
2512248590Smm			value = 1;
2513248590Smm	}
2514248590Smm	return (value);
2515248590Smm}
2516248590Smm
2517248590Smm/*
2518248590Smm * Can this platform run the gzip program?
2519248590Smm */
2520248590Smmint
2521228753SmmcanGzip(void)
2522228753Smm{
2523228753Smm	static int tested = 0, value = 0;
2524228753Smm	if (!tested) {
2525228753Smm		tested = 1;
2526358090Smm		if (systemf("gzip --help %s", redirectArgs) == 0)
2527228753Smm			value = 1;
2528228753Smm	}
2529228753Smm	return (value);
2530228753Smm}
2531228753Smm
2532228753Smm/*
2533248590Smm * Can this platform run the lrzip program?
2534228753Smm */
2535228753Smmint
2536248590SmmcanRunCommand(const char *cmd)
2537228753Smm{
2538248590Smm  static int tested = 0, value = 0;
2539248590Smm  if (!tested) {
2540248590Smm    tested = 1;
2541248590Smm    if (systemf("%s %s", cmd, redirectArgs) == 0)
2542248590Smm      value = 1;
2543248590Smm  }
2544248590Smm  return (value);
2545248590Smm}
2546248590Smm
2547248590Smmint
2548248590SmmcanLrzip(void)
2549248590Smm{
2550228753Smm	static int tested = 0, value = 0;
2551228753Smm	if (!tested) {
2552228753Smm		tested = 1;
2553248590Smm		if (systemf("lrzip -V %s", redirectArgs) == 0)
2554228753Smm			value = 1;
2555228753Smm	}
2556228753Smm	return (value);
2557228753Smm}
2558228753Smm
2559228753Smm/*
2560299425Smm * Can this platform run the lz4 program?
2561299425Smm */
2562299425Smmint
2563299425SmmcanLz4(void)
2564299425Smm{
2565299425Smm	static int tested = 0, value = 0;
2566299425Smm	if (!tested) {
2567299425Smm		tested = 1;
2568358090Smm		if (systemf("lz4 --help %s", redirectArgs) == 0)
2569299425Smm			value = 1;
2570299425Smm	}
2571299425Smm	return (value);
2572299425Smm}
2573299425Smm
2574299425Smm/*
2575324418Smm * Can this platform run the zstd program?
2576324418Smm */
2577324418Smmint
2578324418SmmcanZstd(void)
2579324418Smm{
2580324418Smm	static int tested = 0, value = 0;
2581324418Smm	if (!tested) {
2582324418Smm		tested = 1;
2583358090Smm		if (systemf("zstd --help %s", redirectArgs) == 0)
2584324418Smm			value = 1;
2585324418Smm	}
2586324418Smm	return (value);
2587324418Smm}
2588324418Smm
2589324418Smm/*
2590248590Smm * Can this platform run the lzip program?
2591248590Smm */
2592248590Smmint
2593248590SmmcanLzip(void)
2594248590Smm{
2595248590Smm	static int tested = 0, value = 0;
2596248590Smm	if (!tested) {
2597248590Smm		tested = 1;
2598358090Smm		if (systemf("lzip --help %s", redirectArgs) == 0)
2599248590Smm			value = 1;
2600248590Smm	}
2601248590Smm	return (value);
2602248590Smm}
2603248590Smm
2604248590Smm/*
2605248590Smm * Can this platform run the lzma program?
2606248590Smm */
2607248590Smmint
2608248590SmmcanLzma(void)
2609248590Smm{
2610248590Smm	static int tested = 0, value = 0;
2611248590Smm	if (!tested) {
2612248590Smm		tested = 1;
2613358090Smm		if (systemf("lzma %s", redirectArgs) == 0)
2614248590Smm			value = 1;
2615248590Smm	}
2616248590Smm	return (value);
2617248590Smm}
2618248590Smm
2619248590Smm/*
2620248590Smm * Can this platform run the lzop program?
2621248590Smm */
2622248590Smmint
2623248590SmmcanLzop(void)
2624248590Smm{
2625248590Smm	static int tested = 0, value = 0;
2626248590Smm	if (!tested) {
2627248590Smm		tested = 1;
2628358090Smm		if (systemf("lzop --help %s", redirectArgs) == 0)
2629248590Smm			value = 1;
2630248590Smm	}
2631248590Smm	return (value);
2632248590Smm}
2633248590Smm
2634248590Smm/*
2635248590Smm * Can this platform run the xz program?
2636248590Smm */
2637248590Smmint
2638248590SmmcanXz(void)
2639248590Smm{
2640248590Smm	static int tested = 0, value = 0;
2641248590Smm	if (!tested) {
2642248590Smm		tested = 1;
2643358090Smm		if (systemf("xz --help %s", redirectArgs) == 0)
2644248590Smm			value = 1;
2645248590Smm	}
2646248590Smm	return (value);
2647248590Smm}
2648248590Smm
2649248590Smm/*
2650238825Smm * Can this filesystem handle nodump flags.
2651238825Smm */
2652238825Smmint
2653238825SmmcanNodump(void)
2654238825Smm{
2655314571Smm#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2656238825Smm	const char *path = "cannodumptest";
2657238825Smm	struct stat sb;
2658238825Smm
2659238825Smm	assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);
2660238825Smm	if (chflags(path, UF_NODUMP) < 0)
2661238825Smm		return (0);
2662238825Smm	if (stat(path, &sb) < 0)
2663238825Smm		return (0);
2664238825Smm	if (sb.st_flags & UF_NODUMP)
2665238825Smm		return (1);
2666314565Smm#elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) \
2667314565Smm	 && defined(FS_NODUMP_FL)) || \
2668314565Smm      (defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \
2669314565Smm	 && defined(EXT2_NODUMP_FL))
2670238825Smm	const char *path = "cannodumptest";
2671238825Smm	int fd, r, flags;
2672238825Smm
2673238825Smm	assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);
2674238825Smm	fd = open(path, O_RDONLY | O_NONBLOCK);
2675238825Smm	if (fd < 0)
2676238825Smm		return (0);
2677314565Smm	r = ioctl(fd,
2678314565Smm#ifdef FS_IOC_GETFLAGS
2679314565Smm	    FS_IOC_GETFLAGS,
2680314565Smm#else
2681314565Smm	    EXT2_IOC_GETFLAGS,
2682314565Smm#endif
2683314565Smm	    &flags);
2684238825Smm	if (r < 0)
2685238825Smm		return (0);
2686314565Smm#ifdef FS_NODUMP_FL
2687314565Smm	flags |= FS_NODUMP_FL;
2688314565Smm#else
2689238825Smm	flags |= EXT2_NODUMP_FL;
2690314565Smm#endif
2691314565Smm	r = ioctl(fd,
2692314565Smm#ifdef FS_IOC_SETFLAGS
2693314565Smm	    FS_IOC_SETFLAGS,
2694314565Smm#else
2695314565Smm	    EXT2_IOC_SETFLAGS,
2696314565Smm#endif
2697314565Smm	   &flags);
2698238825Smm	if (r < 0)
2699238825Smm		return (0);
2700238825Smm	close(fd);
2701238825Smm	fd = open(path, O_RDONLY | O_NONBLOCK);
2702238825Smm	if (fd < 0)
2703238825Smm		return (0);
2704314565Smm	r = ioctl(fd,
2705314565Smm#ifdef FS_IOC_GETFLAGS
2706314565Smm	    FS_IOC_GETFLAGS,
2707314565Smm#else
2708314565Smm	    EXT2_IOC_GETFLAGS,
2709314565Smm#endif
2710314565Smm	    &flags);
2711238825Smm	if (r < 0)
2712238825Smm		return (0);
2713238825Smm	close(fd);
2714314565Smm#ifdef FS_NODUMP_FL
2715314565Smm	if (flags & FS_NODUMP_FL)
2716314565Smm#else
2717238825Smm	if (flags & EXT2_NODUMP_FL)
2718314565Smm#endif
2719238825Smm		return (1);
2720314571Smm#endif
2721238825Smm	return (0);
2722238825Smm}
2723238825Smm
2724353377Smm/* Get extended attribute value from a path */
2725353377Smmvoid *
2726316338SmmgetXattr(const char *path, const char *name, size_t *sizep)
2727316338Smm{
2728316338Smm	void *value = NULL;
2729316338Smm#if ARCHIVE_XATTR_SUPPORT
2730316338Smm	ssize_t size;
2731316338Smm#if ARCHIVE_XATTR_LINUX
2732316338Smm	size = lgetxattr(path, name, NULL, 0);
2733316338Smm#elif ARCHIVE_XATTR_DARWIN
2734316338Smm	size = getxattr(path, name, NULL, 0, 0, XATTR_NOFOLLOW);
2735316338Smm#elif ARCHIVE_XATTR_AIX
2736316338Smm	size = lgetea(path, name, NULL, 0);
2737316338Smm#elif ARCHIVE_XATTR_FREEBSD
2738316338Smm	size = extattr_get_link(path, EXTATTR_NAMESPACE_USER, name + 5,
2739316338Smm	    NULL, 0);
2740316338Smm#endif
2741316338Smm
2742316338Smm	if (size >= 0) {
2743316338Smm		value = malloc(size);
2744316338Smm#if ARCHIVE_XATTR_LINUX
2745316338Smm		size = lgetxattr(path, name, value, size);
2746316338Smm#elif ARCHIVE_XATTR_DARWIN
2747316338Smm		size = getxattr(path, name, value, size, 0, XATTR_NOFOLLOW);
2748316338Smm#elif ARCHIVE_XATTR_AIX
2749316338Smm		size = lgetea(path, name, value, size);
2750316338Smm#elif ARCHIVE_XATTR_FREEBSD
2751316338Smm		size = extattr_get_link(path, EXTATTR_NAMESPACE_USER, name + 5,
2752316338Smm		    value, size);
2753316338Smm#endif
2754316338Smm		if (size < 0) {
2755316338Smm			free(value);
2756316338Smm			value = NULL;
2757316338Smm		}
2758316338Smm	}
2759316338Smm	if (size < 0)
2760316338Smm		*sizep = 0;
2761316338Smm	else
2762316338Smm		*sizep = (size_t)size;
2763316338Smm#else	/* !ARCHIVE_XATTR_SUPPORT */
2764316338Smm	(void)path;	/* UNUSED */
2765316338Smm	(void)name;	/* UNUSED */
2766316338Smm	*sizep = 0;
2767316338Smm#endif 	/* !ARCHIVE_XATTR_SUPPORT */
2768316338Smm	return (value);
2769316338Smm}
2770316338Smm
2771316338Smm/*
2772316338Smm * Set extended attribute on a path
2773316338Smm * Returns 0 on error, 1 on success
2774316338Smm */
2775316338Smmint
2776316338SmmsetXattr(const char *path, const char *name, const void *value, size_t size)
2777316338Smm{
2778316338Smm#if ARCHIVE_XATTR_SUPPORT
2779316338Smm#if ARCHIVE_XATTR_LINUX
2780316338Smm	if (lsetxattr(path, name, value, size, 0) == 0)
2781316338Smm#elif ARCHIVE_XATTR_DARWIN
2782316338Smm	if (setxattr(path, name, value, size, 0, XATTR_NOFOLLOW) == 0)
2783316338Smm#elif ARCHIVE_XATTR_AIX
2784316338Smm	if (lsetea(path, name, value, size, 0) == 0)
2785316338Smm#elif ARCHIVE_XATTR_FREEBSD
2786316338Smm	if (extattr_set_link(path, EXTATTR_NAMESPACE_USER, name + 5, value,
2787316338Smm	    size) > -1)
2788316338Smm#else
2789316338Smm	if (0)
2790316338Smm#endif
2791316338Smm		return (1);
2792316338Smm#else	/* !ARCHIVE_XATTR_SUPPORT */
2793316338Smm	(void)path;     /* UNUSED */
2794316338Smm	(void)name;	/* UNUSED */
2795316338Smm	(void)value;	/* UNUSED */
2796316338Smm	(void)size;	/* UNUSED */
2797316338Smm#endif	/* !ARCHIVE_XATTR_SUPPORT */
2798316338Smm	return (0);
2799316338Smm}
2800316338Smm
2801316338Smm#if ARCHIVE_ACL_SUNOS
2802314571Smm/* Fetch ACLs on Solaris using acl() or facl() */
2803314571Smmvoid *
2804314571Smmsunacl_get(int cmd, int *aclcnt, int fd, const char *path)
2805314571Smm{
2806314571Smm	int cnt, cntcmd;
2807314571Smm	size_t size;
2808314571Smm	void *aclp;
2809238825Smm
2810314571Smm	if (cmd == GETACL) {
2811314571Smm		cntcmd = GETACLCNT;
2812314571Smm		size = sizeof(aclent_t);
2813314571Smm	}
2814316338Smm#if ARCHIVE_ACL_SUNOS_NFS4
2815314571Smm	else if (cmd == ACE_GETACL) {
2816314571Smm		cntcmd = ACE_GETACLCNT;
2817314571Smm		size = sizeof(ace_t);
2818314571Smm	}
2819314571Smm#endif
2820314571Smm	else {
2821314571Smm		errno = EINVAL;
2822314571Smm		*aclcnt = -1;
2823314571Smm		return (NULL);
2824314571Smm	}
2825314571Smm
2826314571Smm	aclp = NULL;
2827314571Smm	cnt = -2;
2828314571Smm	while (cnt == -2 || (cnt == -1 && errno == ENOSPC)) {
2829314571Smm		if (path != NULL)
2830314571Smm			cnt = acl(path, cntcmd, 0, NULL);
2831314571Smm		else
2832314571Smm			cnt = facl(fd, cntcmd, 0, NULL);
2833314571Smm
2834314571Smm		if (cnt > 0) {
2835314571Smm			if (aclp == NULL)
2836314571Smm				aclp = malloc(cnt * size);
2837314571Smm			else
2838314571Smm				aclp = realloc(NULL, cnt * size);
2839314571Smm			if (aclp != NULL) {
2840314571Smm				if (path != NULL)
2841314571Smm					cnt = acl(path, cmd, cnt, aclp);
2842314571Smm				else
2843314571Smm					cnt = facl(fd, cmd, cnt, aclp);
2844314571Smm			}
2845314571Smm		} else {
2846344674Smm			free(aclp);
2847344674Smm			aclp = NULL;
2848314571Smm			break;
2849314571Smm		}
2850314571Smm	}
2851314571Smm
2852314571Smm	*aclcnt = cnt;
2853314571Smm	return (aclp);
2854314571Smm}
2855316338Smm#endif /* ARCHIVE_ACL_SUNOS */
2856314571Smm
2857314571Smm/*
2858314571Smm * Set test ACLs on a path
2859314571Smm * Return values:
2860314571Smm * 0: error setting ACLs
2861314571Smm * ARCHIVE_TEST_ACL_TYPE_POSIX1E: POSIX.1E ACLs have been set
2862314571Smm * ARCHIVE_TEST_ACL_TYPE_NFS4: NFSv4 or extended ACLs have been set
2863314571Smm */
2864238825Smmint
2865314571SmmsetTestAcl(const char *path)
2866238825Smm{
2867316338Smm#if ARCHIVE_ACL_SUPPORT
2868314571Smm	int r = 1;
2869316338Smm#if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_DARWIN
2870314571Smm	acl_t acl;
2871314571Smm#endif
2872316338Smm#if ARCHIVE_ACL_LIBRICHACL
2873316338Smm	struct richacl *richacl;
2874316338Smm#endif
2875316338Smm#if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_FREEBSD
2876314571Smm	const char *acltext_posix1e = "user:1:rw-,"
2877314571Smm	    "group:15:r-x,"
2878314571Smm	    "user::rwx,"
2879314571Smm	    "group::rwx,"
2880314571Smm	    "other::r-x,"
2881314571Smm	    "mask::rwx";
2882316338Smm#elif ARCHIVE_ACL_SUNOS /* Solaris POSIX.1e */
2883314571Smm	aclent_t aclp_posix1e[] = {
2884314571Smm	    { USER_OBJ, -1, 4 | 2 | 1 },
2885314571Smm	    { USER, 1, 4 | 2 },
2886314571Smm	    { GROUP_OBJ, -1, 4 | 2 | 1 },
2887314571Smm	    { GROUP, 15, 4 | 1 },
2888314571Smm	    { CLASS_OBJ, -1, 4 | 2 | 1 },
2889314571Smm	    { OTHER_OBJ, -1, 4 | 2 | 1 }
2890314571Smm	};
2891314571Smm#endif
2892316338Smm#if ARCHIVE_ACL_FREEBSD /* FreeBSD NFS4 */
2893314571Smm	const char *acltext_nfs4 = "user:1:rwpaRcs::allow:1,"
2894314571Smm	    "group:15:rxaRcs::allow:15,"
2895314571Smm	    "owner@:rwpxaARWcCos::allow,"
2896314571Smm	    "group@:rwpxaRcs::allow,"
2897314571Smm	    "everyone@:rxaRcs::allow";
2898316338Smm#elif ARCHIVE_ACL_LIBRICHACL
2899316338Smm	const char *acltext_nfs4 = "owner:rwpxaARWcCoS::mask,"
2900316338Smm	    "group:rwpxaRcS::mask,"
2901316338Smm	    "other:rxaRcS::mask,"
2902316338Smm	    "user:1:rwpaRcS::allow,"
2903316338Smm	    "group:15:rxaRcS::allow,"
2904316338Smm	    "owner@:rwpxaARWcCoS::allow,"
2905316338Smm	    "group@:rwpxaRcS::allow,"
2906316338Smm	    "everyone@:rxaRcS::allow";
2907316338Smm#elif ARCHIVE_ACL_SUNOS_NFS4 /* Solaris NFS4 */
2908314571Smm	ace_t aclp_nfs4[] = {
2909314571Smm	    { 1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |
2910314571Smm	      ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS | ACE_READ_ACL |
2911314571Smm	      ACE_SYNCHRONIZE, 0, ACE_ACCESS_ALLOWED_ACE_TYPE },
2912314571Smm	    { 15, ACE_READ_DATA | ACE_EXECUTE | ACE_READ_ATTRIBUTES |
2913314571Smm	      ACE_READ_NAMED_ATTRS | ACE_READ_ACL | ACE_SYNCHRONIZE,
2914314571Smm	      ACE_IDENTIFIER_GROUP, ACE_ACCESS_ALLOWED_ACE_TYPE },
2915314571Smm	    { -1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |
2916314571Smm	      ACE_EXECUTE | ACE_READ_ATTRIBUTES | ACE_WRITE_ATTRIBUTES |
2917314571Smm	      ACE_READ_NAMED_ATTRS | ACE_WRITE_NAMED_ATTRS |
2918314571Smm	      ACE_READ_ACL | ACE_WRITE_ACL | ACE_WRITE_OWNER | ACE_SYNCHRONIZE,
2919314571Smm	      ACE_OWNER, ACE_ACCESS_ALLOWED_ACE_TYPE },
2920314571Smm	    { -1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |
2921314571Smm	      ACE_EXECUTE | ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS |
2922314571Smm	      ACE_READ_ACL | ACE_SYNCHRONIZE, ACE_GROUP | ACE_IDENTIFIER_GROUP,
2923314571Smm	      ACE_ACCESS_ALLOWED_ACE_TYPE },
2924314571Smm	    { -1, ACE_READ_DATA | ACE_EXECUTE | ACE_READ_ATTRIBUTES |
2925314571Smm	      ACE_READ_NAMED_ATTRS | ACE_READ_ACL | ACE_SYNCHRONIZE,
2926314571Smm	      ACE_EVERYONE, ACE_ACCESS_ALLOWED_ACE_TYPE }
2927314571Smm	};
2928316338Smm#elif ARCHIVE_ACL_DARWIN /* Mac OS X */
2929314571Smm	acl_entry_t aclent;
2930314571Smm	acl_permset_t permset;
2931314571Smm	const uid_t uid = 1;
2932314571Smm	uuid_t uuid;
2933314571Smm	int i;
2934314571Smm	const acl_perm_t acl_perms[] = {
2935314571Smm		ACL_READ_DATA,
2936314571Smm		ACL_WRITE_DATA,
2937314571Smm		ACL_APPEND_DATA,
2938314571Smm		ACL_EXECUTE,
2939314571Smm		ACL_READ_ATTRIBUTES,
2940314571Smm		ACL_READ_EXTATTRIBUTES,
2941314571Smm		ACL_READ_SECURITY,
2942314571Smm#if HAVE_DECL_ACL_SYNCHRONIZE
2943314571Smm		ACL_SYNCHRONIZE
2944314571Smm#endif
2945314571Smm	};
2946316338Smm#endif /* ARCHIVE_ACL_DARWIN */
2947314571Smm
2948316338Smm#if ARCHIVE_ACL_FREEBSD
2949314571Smm	acl = acl_from_text(acltext_nfs4);
2950314571Smm	failure("acl_from_text() error: %s", strerror(errno));
2951314571Smm	if (assert(acl != NULL) == 0)
2952314571Smm		return (0);
2953316338Smm#elif ARCHIVE_ACL_LIBRICHACL
2954316338Smm	richacl = richacl_from_text(acltext_nfs4, NULL, NULL);
2955316338Smm	failure("richacl_from_text() error: %s", strerror(errno));
2956316338Smm	if (assert(richacl != NULL) == 0)
2957316338Smm		return (0);
2958316338Smm#elif ARCHIVE_ACL_DARWIN
2959314571Smm	acl = acl_init(1);
2960314571Smm	failure("acl_init() error: %s", strerror(errno));
2961314571Smm	if (assert(acl != NULL) == 0)
2962314571Smm		return (0);
2963314571Smm	r = acl_create_entry(&acl, &aclent);
2964314571Smm	failure("acl_create_entry() error: %s", strerror(errno));
2965314571Smm	if (assertEqualInt(r, 0) == 0)
2966314571Smm		goto testacl_free;
2967314571Smm	r = acl_set_tag_type(aclent, ACL_EXTENDED_ALLOW);
2968314571Smm	failure("acl_set_tag_type() error: %s", strerror(errno));
2969314571Smm	if (assertEqualInt(r, 0) == 0)
2970314571Smm		goto testacl_free;
2971314571Smm	r = acl_get_permset(aclent, &permset);
2972314571Smm	failure("acl_get_permset() error: %s", strerror(errno));
2973314571Smm	if (assertEqualInt(r, 0) == 0)
2974314571Smm		goto testacl_free;
2975314571Smm	for (i = 0; i < (int)(sizeof(acl_perms) / sizeof(acl_perms[0])); i++) {
2976314571Smm		r = acl_add_perm(permset, acl_perms[i]);
2977314571Smm		failure("acl_add_perm() error: %s", strerror(errno));
2978314571Smm		if (assertEqualInt(r, 0) == 0)
2979314571Smm			goto testacl_free;
2980314571Smm	}
2981314571Smm	r = acl_set_permset(aclent, permset);
2982314571Smm	failure("acl_set_permset() error: %s", strerror(errno));
2983314571Smm	if (assertEqualInt(r, 0) == 0)
2984314571Smm		goto testacl_free;
2985316338Smm	r = mbr_uid_to_uuid(uid, uuid);
2986316338Smm	failure("mbr_uid_to_uuid() error: %s", strerror(errno));
2987314571Smm	if (assertEqualInt(r, 0) == 0)
2988314571Smm		goto testacl_free;
2989314571Smm	r = acl_set_qualifier(aclent, uuid);
2990314571Smm	failure("acl_set_qualifier() error: %s", strerror(errno));
2991314571Smm	if (assertEqualInt(r, 0) == 0)
2992314571Smm		goto testacl_free;
2993316338Smm#endif /* ARCHIVE_ACL_DARWIN */
2994314571Smm
2995316338Smm#if ARCHIVE_ACL_NFS4
2996316338Smm#if ARCHIVE_ACL_FREEBSD
2997314571Smm	r = acl_set_file(path, ACL_TYPE_NFS4, acl);
2998314571Smm	acl_free(acl);
2999316338Smm#elif ARCHIVE_ACL_LIBRICHACL
3000316338Smm	r = richacl_set_file(path, richacl);
3001316338Smm	richacl_free(richacl);
3002316338Smm#elif ARCHIVE_ACL_SUNOS_NFS4
3003314571Smm	r = acl(path, ACE_SETACL,
3004314571Smm	    (int)(sizeof(aclp_nfs4)/sizeof(aclp_nfs4[0])), aclp_nfs4);
3005316338Smm#elif ARCHIVE_ACL_DARWIN
3006314571Smm	r = acl_set_file(path, ACL_TYPE_EXTENDED, acl);
3007314571Smm	acl_free(acl);
3008314571Smm#endif
3009314571Smm	if (r == 0)
3010314571Smm		return (ARCHIVE_TEST_ACL_TYPE_NFS4);
3011316338Smm#endif	/* ARCHIVE_ACL_NFS4 */
3012314571Smm
3013316338Smm#if ARCHIVE_ACL_POSIX1E
3014316338Smm#if ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_LIBACL
3015314571Smm	acl = acl_from_text(acltext_posix1e);
3016314571Smm	failure("acl_from_text() error: %s", strerror(errno));
3017314571Smm	if (assert(acl != NULL) == 0)
3018314571Smm		return (0);
3019314571Smm
3020314571Smm	r = acl_set_file(path, ACL_TYPE_ACCESS, acl);
3021314571Smm	acl_free(acl);
3022316338Smm#elif ARCHIVE_ACL_SUNOS
3023314571Smm	r = acl(path, SETACL,
3024314571Smm	    (int)(sizeof(aclp_posix1e)/sizeof(aclp_posix1e[0])), aclp_posix1e);
3025314571Smm#endif
3026314571Smm	if (r == 0)
3027314571Smm		return (ARCHIVE_TEST_ACL_TYPE_POSIX1E);
3028314571Smm	else
3029314571Smm		return (0);
3030316338Smm#endif /* ARCHIVE_ACL_POSIX1E */
3031316338Smm#if ARCHIVE_ACL_DARWIN
3032314571Smmtestacl_free:
3033314571Smm	acl_free(acl);
3034314571Smm#endif
3035316338Smm#endif /* ARCHIVE_ACL_SUPPORT */
3036314571Smm	(void)path;	/* UNUSED */
3037238825Smm	return (0);
3038238825Smm}
3039238825Smm
3040238825Smm/*
3041228753Smm * Sleep as needed; useful for verifying disk timestamp changes by
3042228753Smm * ensuring that the wall-clock time has actually changed before we
3043228753Smm * go back to re-read something from disk.
3044228753Smm */
3045228753Smmvoid
3046228753SmmsleepUntilAfter(time_t t)
3047228753Smm{
3048228753Smm	while (t >= time(NULL))
3049228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
3050228753Smm		Sleep(500);
3051228753Smm#else
3052228753Smm		sleep(1);
3053228753Smm#endif
3054228753Smm}
3055228753Smm
3056228753Smm/*
3057228753Smm * Call standard system() call, but build up the command line using
3058228753Smm * sprintf() conventions.
3059228753Smm */
3060228753Smmint
3061228753Smmsystemf(const char *fmt, ...)
3062228753Smm{
3063228753Smm	char buff[8192];
3064228753Smm	va_list ap;
3065228753Smm	int r;
3066228753Smm
3067228753Smm	va_start(ap, fmt);
3068228753Smm	vsprintf(buff, fmt, ap);
3069228753Smm	if (verbosity > VERBOSITY_FULL)
3070228753Smm		logprintf("Cmd: %s\n", buff);
3071228753Smm	r = system(buff);
3072228753Smm	va_end(ap);
3073228753Smm	return (r);
3074228753Smm}
3075228753Smm
3076228753Smm/*
3077228753Smm * Slurp a file into memory for ease of comparison and testing.
3078228753Smm * Returns size of file in 'sizep' if non-NULL, null-terminates
3079228753Smm * data in memory for ease of use.
3080228753Smm */
3081228753Smmchar *
3082228753Smmslurpfile(size_t * sizep, const char *fmt, ...)
3083228753Smm{
3084228753Smm	char filename[8192];
3085228753Smm	struct stat st;
3086228753Smm	va_list ap;
3087228753Smm	char *p;
3088228753Smm	ssize_t bytes_read;
3089228753Smm	FILE *f;
3090228753Smm	int r;
3091228753Smm
3092228753Smm	va_start(ap, fmt);
3093228753Smm	vsprintf(filename, fmt, ap);
3094228753Smm	va_end(ap);
3095228753Smm
3096228753Smm	f = fopen(filename, "rb");
3097228753Smm	if (f == NULL) {
3098228753Smm		/* Note: No error; non-existent file is okay here. */
3099228753Smm		return (NULL);
3100228753Smm	}
3101228753Smm	r = fstat(fileno(f), &st);
3102228753Smm	if (r != 0) {
3103228753Smm		logprintf("Can't stat file %s\n", filename);
3104228753Smm		fclose(f);
3105228753Smm		return (NULL);
3106228753Smm	}
3107228753Smm	p = malloc((size_t)st.st_size + 1);
3108228753Smm	if (p == NULL) {
3109228753Smm		logprintf("Can't allocate %ld bytes of memory to read file %s\n",
3110228753Smm		    (long int)st.st_size, filename);
3111228753Smm		fclose(f);
3112228753Smm		return (NULL);
3113228753Smm	}
3114228753Smm	bytes_read = fread(p, 1, (size_t)st.st_size, f);
3115228753Smm	if (bytes_read < st.st_size) {
3116228753Smm		logprintf("Can't read file %s\n", filename);
3117228753Smm		fclose(f);
3118228753Smm		free(p);
3119228753Smm		return (NULL);
3120228753Smm	}
3121228753Smm	p[st.st_size] = '\0';
3122228753Smm	if (sizep != NULL)
3123228753Smm		*sizep = (size_t)st.st_size;
3124228753Smm	fclose(f);
3125228753Smm	return (p);
3126228753Smm}
3127228753Smm
3128299425Smm/*
3129299425Smm * Slurp a file into memory for ease of comparison and testing.
3130299425Smm * Returns size of file in 'sizep' if non-NULL, null-terminates
3131299425Smm * data in memory for ease of use.
3132299425Smm */
3133299425Smmvoid
3134299425Smmdumpfile(const char *filename, void *data, size_t len)
3135299425Smm{
3136299425Smm	ssize_t bytes_written;
3137299425Smm	FILE *f;
3138299425Smm
3139299425Smm	f = fopen(filename, "wb");
3140299425Smm	if (f == NULL) {
3141299425Smm		logprintf("Can't open file %s for writing\n", filename);
3142299425Smm		return;
3143299425Smm	}
3144299425Smm	bytes_written = fwrite(data, 1, len, f);
3145299425Smm	if (bytes_written < (ssize_t)len)
3146299425Smm		logprintf("Can't write file %s\n", filename);
3147299425Smm	fclose(f);
3148299425Smm}
3149299425Smm
3150228753Smm/* Read a uuencoded file from the reference directory, decode, and
3151228753Smm * write the result into the current directory. */
3152299425Smm#define VALID_UUDECODE(c) (c >= 32 && c <= 96)
3153228753Smm#define	UUDECODE(c) (((c) - 0x20) & 0x3f)
3154228753Smmvoid
3155228753Smmextract_reference_file(const char *name)
3156228753Smm{
3157228753Smm	char buff[1024];
3158228753Smm	FILE *in, *out;
3159228753Smm
3160228753Smm	sprintf(buff, "%s/%s.uu", refdir, name);
3161228753Smm	in = fopen(buff, "r");
3162228753Smm	failure("Couldn't open reference file %s", buff);
3163228753Smm	assert(in != NULL);
3164228753Smm	if (in == NULL)
3165228753Smm		return;
3166228753Smm	/* Read up to and including the 'begin' line. */
3167228753Smm	for (;;) {
3168228753Smm		if (fgets(buff, sizeof(buff), in) == NULL) {
3169228753Smm			/* TODO: This is a failure. */
3170228753Smm			return;
3171228753Smm		}
3172228753Smm		if (memcmp(buff, "begin ", 6) == 0)
3173228753Smm			break;
3174228753Smm	}
3175228753Smm	/* Now, decode the rest and write it. */
3176228753Smm	out = fopen(name, "wb");
3177228753Smm	while (fgets(buff, sizeof(buff), in) != NULL) {
3178228753Smm		char *p = buff;
3179228753Smm		int bytes;
3180228753Smm
3181228753Smm		if (memcmp(buff, "end", 3) == 0)
3182228753Smm			break;
3183228753Smm
3184228753Smm		bytes = UUDECODE(*p++);
3185228753Smm		while (bytes > 0) {
3186228753Smm			int n = 0;
3187228753Smm			/* Write out 1-3 bytes from that. */
3188228753Smm			if (bytes > 0) {
3189299425Smm				assert(VALID_UUDECODE(p[0]));
3190299425Smm				assert(VALID_UUDECODE(p[1]));
3191228753Smm				n = UUDECODE(*p++) << 18;
3192228753Smm				n |= UUDECODE(*p++) << 12;
3193228753Smm				fputc(n >> 16, out);
3194228753Smm				--bytes;
3195228753Smm			}
3196228753Smm			if (bytes > 0) {
3197299425Smm				assert(VALID_UUDECODE(p[0]));
3198228753Smm				n |= UUDECODE(*p++) << 6;
3199228753Smm				fputc((n >> 8) & 0xFF, out);
3200228753Smm				--bytes;
3201228753Smm			}
3202228753Smm			if (bytes > 0) {
3203299425Smm				assert(VALID_UUDECODE(p[0]));
3204228753Smm				n |= UUDECODE(*p++);
3205228753Smm				fputc(n & 0xFF, out);
3206228753Smm				--bytes;
3207228753Smm			}
3208228753Smm		}
3209228753Smm	}
3210228753Smm	fclose(out);
3211228753Smm	fclose(in);
3212228753Smm}
3213228753Smm
3214299425Smmvoid
3215299425Smmcopy_reference_file(const char *name)
3216299425Smm{
3217299425Smm	char buff[1024];
3218299425Smm	FILE *in, *out;
3219299425Smm	size_t rbytes;
3220299425Smm
3221299425Smm	sprintf(buff, "%s/%s", refdir, name);
3222299425Smm	in = fopen(buff, "rb");
3223299425Smm	failure("Couldn't open reference file %s", buff);
3224299425Smm	assert(in != NULL);
3225299425Smm	if (in == NULL)
3226299425Smm		return;
3227299425Smm	/* Now, decode the rest and write it. */
3228299425Smm	/* Not a lot of error checking here; the input better be right. */
3229299425Smm	out = fopen(name, "wb");
3230299425Smm	while ((rbytes = fread(buff, 1, sizeof(buff), in)) > 0) {
3231299425Smm		if (fwrite(buff, 1, rbytes, out) != rbytes) {
3232299425Smm			logprintf("Error: fwrite\n");
3233299425Smm			break;
3234299425Smm		}
3235299425Smm	}
3236299425Smm	fclose(out);
3237299425Smm	fclose(in);
3238299425Smm}
3239299425Smm
3240231200Smmint
3241231200Smmis_LargeInode(const char *file)
3242231200Smm{
3243231200Smm#if defined(_WIN32) && !defined(__CYGWIN__)
3244231200Smm	BY_HANDLE_FILE_INFORMATION bhfi;
3245231200Smm	int r;
3246231200Smm
3247231200Smm	r = my_GetFileInformationByName(file, &bhfi);
3248231200Smm	if (r != 0)
3249231200Smm		return (0);
3250231200Smm	return (bhfi.nFileIndexHigh & 0x0000FFFFUL);
3251231200Smm#else
3252231200Smm	struct stat st;
3253231200Smm	int64_t ino;
3254231200Smm
3255231200Smm	if (stat(file, &st) < 0)
3256231200Smm		return (0);
3257231200Smm	ino = (int64_t)st.st_ino;
3258231200Smm	return (ino > 0xffffffff);
3259231200Smm#endif
3260231200Smm}
3261248590Smm
3262248590Smmvoid
3263248590Smmextract_reference_files(const char **names)
3264248590Smm{
3265248590Smm	while (names && *names)
3266248590Smm		extract_reference_file(*names++);
3267248590Smm}
3268248590Smm
3269314565Smm#ifndef PROGRAM
3270310796Smm/* Set ACLs */
3271314565Smmint
3272314565Smmassertion_entry_set_acls(const char *file, int line, struct archive_entry *ae,
3273310796Smm    struct archive_test_acl_t *acls, int n)
3274310796Smm{
3275314565Smm	int i, r, ret;
3276310796Smm
3277314565Smm	assertion_count(file, line);
3278314565Smm
3279314565Smm	ret = 0;
3280310796Smm	archive_entry_acl_clear(ae);
3281310796Smm	for (i = 0; i < n; i++) {
3282314565Smm		r = archive_entry_acl_add_entry(ae,
3283310796Smm		    acls[i].type, acls[i].permset, acls[i].tag,
3284310796Smm		    acls[i].qual, acls[i].name);
3285314565Smm		if (r != 0) {
3286314565Smm			ret = 1;
3287358090Smm			failure_start(file, line, "type=%#010x, "
3288314565Smm			    "permset=%#010x, tag=%d, qual=%d name=%s",
3289314565Smm			    acls[i].type, acls[i].permset, acls[i].tag,
3290314565Smm			    acls[i].qual, acls[i].name);
3291314565Smm			failure_finish(NULL);
3292314565Smm		}
3293310796Smm	}
3294314565Smm
3295314565Smm	return (ret);
3296310796Smm}
3297310796Smm
3298310796Smmstatic int
3299310796Smmarchive_test_acl_match(struct archive_test_acl_t *acl, int type, int permset,
3300310796Smm    int tag, int qual, const char *name)
3301310796Smm{
3302310796Smm	if (type != acl->type)
3303310796Smm		return (0);
3304310796Smm	if (permset != acl->permset)
3305310796Smm		return (0);
3306310796Smm	if (tag != acl->tag)
3307310796Smm		return (0);
3308310796Smm	if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ)
3309310796Smm		return (1);
3310310796Smm	if (tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ)
3311310796Smm		return (1);
3312310796Smm	if (tag == ARCHIVE_ENTRY_ACL_EVERYONE)
3313310796Smm		return (1);
3314310796Smm	if (tag == ARCHIVE_ENTRY_ACL_OTHER)
3315310796Smm		return (1);
3316310796Smm	if (qual != acl->qual)
3317310796Smm		return (0);
3318310796Smm	if (name == NULL) {
3319310796Smm		if (acl->name == NULL || acl->name[0] == '\0')
3320310796Smm			return (1);
3321310796Smm		return (0);
3322310796Smm	}
3323310796Smm	if (acl->name == NULL) {
3324310796Smm		if (name[0] == '\0')
3325310796Smm			return (1);
3326310796Smm		return (0);
3327310796Smm	}
3328310796Smm	return (0 == strcmp(name, acl->name));
3329310796Smm}
3330310796Smm
3331310796Smm/* Compare ACLs */
3332314565Smmint
3333314565Smmassertion_entry_compare_acls(const char *file, int line,
3334314565Smm    struct archive_entry *ae, struct archive_test_acl_t *acls, int cnt,
3335314565Smm    int want_type, int mode)
3336310796Smm{
3337310796Smm	int *marker;
3338314565Smm	int i, r, n, ret;
3339310796Smm	int type, permset, tag, qual;
3340310796Smm	int matched;
3341310796Smm	const char *name;
3342310796Smm
3343314565Smm	assertion_count(file, line);
3344314565Smm
3345314565Smm	ret = 0;
3346310796Smm	n = 0;
3347310796Smm	marker = malloc(sizeof(marker[0]) * cnt);
3348310796Smm
3349310796Smm	for (i = 0; i < cnt; i++) {
3350310796Smm		if ((acls[i].type & want_type) != 0) {
3351310796Smm			marker[n] = i;
3352310796Smm			n++;
3353310796Smm		}
3354310796Smm	}
3355310796Smm
3356314565Smm	if (n == 0) {
3357314565Smm		failure_start(file, line, "No ACL's to compare, type mask: %d",
3358314565Smm		    want_type);
3359314565Smm		return (1);
3360314565Smm	}
3361310796Smm
3362310796Smm	while (0 == (r = archive_entry_acl_next(ae, want_type,
3363310796Smm			 &type, &permset, &tag, &qual, &name))) {
3364310796Smm		for (i = 0, matched = 0; i < n && !matched; i++) {
3365310796Smm			if (archive_test_acl_match(&acls[marker[i]], type,
3366310796Smm			    permset, tag, qual, name)) {
3367310796Smm				/* We found a match; remove it. */
3368310796Smm				marker[i] = marker[n - 1];
3369310796Smm				n--;
3370310796Smm				matched = 1;
3371310796Smm			}
3372310796Smm		}
3373310796Smm		if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS
3374310796Smm		    && tag == ARCHIVE_ENTRY_ACL_USER_OBJ) {
3375314565Smm			if (!matched) {
3376314565Smm				failure_start(file, line, "No match for "
3377314565Smm				    "user_obj perm");
3378314565Smm				failure_finish(NULL);
3379314565Smm				ret = 1;
3380314565Smm			}
3381314565Smm			if ((permset << 6) != (mode & 0700)) {
3382314565Smm				failure_start(file, line, "USER_OBJ permset "
3383314565Smm				    "(%02o) != user mode (%02o)", permset,
3384314565Smm				    07 & (mode >> 6));
3385314565Smm				failure_finish(NULL);
3386314565Smm				ret = 1;
3387314565Smm			}
3388310796Smm		} else if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS
3389310796Smm		    && tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ) {
3390314565Smm			if (!matched) {
3391314565Smm				failure_start(file, line, "No match for "
3392314565Smm				    "group_obj perm");
3393314565Smm				failure_finish(NULL);
3394314565Smm				ret = 1;
3395314565Smm			}
3396314565Smm			if ((permset << 3) != (mode & 0070)) {
3397314565Smm				failure_start(file, line, "GROUP_OBJ permset "
3398314565Smm				    "(%02o) != group mode (%02o)", permset,
3399314565Smm				    07 & (mode >> 3));
3400314565Smm				failure_finish(NULL);
3401314565Smm				ret = 1;
3402314565Smm			}
3403310796Smm		} else if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS
3404310796Smm		    && tag == ARCHIVE_ENTRY_ACL_OTHER) {
3405314565Smm			if (!matched) {
3406314565Smm				failure_start(file, line, "No match for "
3407314565Smm				    "other perm");
3408314565Smm				failure_finish(NULL);
3409314565Smm				ret = 1;
3410314565Smm			}
3411314565Smm			if ((permset << 0) != (mode & 0007)) {
3412314565Smm				failure_start(file, line, "OTHER permset "
3413314565Smm				    "(%02o) != other mode (%02o)", permset,
3414314565Smm				    mode & 07);
3415314565Smm				failure_finish(NULL);
3416314565Smm				ret = 1;
3417314565Smm			}
3418314565Smm		} else if (matched != 1) {
3419314565Smm			failure_start(file, line, "Could not find match for "
3420314565Smm			    "ACL (type=%#010x,permset=%#010x,tag=%d,qual=%d,"
3421310796Smm			    "name=``%s'')", type, permset, tag, qual, name);
3422314565Smm			failure_finish(NULL);
3423314565Smm			ret = 1;
3424310796Smm		}
3425310796Smm	}
3426314565Smm	if (r != ARCHIVE_EOF) {
3427314565Smm		failure_start(file, line, "Should not exit before EOF");
3428314565Smm		failure_finish(NULL);
3429314565Smm		ret = 1;
3430314565Smm	}
3431314565Smm	if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0 &&
3432314565Smm	    (mode_t)(mode & 0777) != (archive_entry_mode(ae) & 0777)) {
3433314565Smm		failure_start(file, line, "Mode (%02o) and entry mode (%02o) "
3434314565Smm		    "mismatch", mode, archive_entry_mode(ae));
3435314565Smm		failure_finish(NULL);
3436314565Smm		ret = 1;
3437314565Smm	}
3438314565Smm	if (n != 0) {
3439314565Smm		failure_start(file, line, "Could not find match for ACL "
3440314565Smm		    "(type=%#010x,permset=%#010x,tag=%d,qual=%d,name=``%s'')",
3441314565Smm		    acls[marker[0]].type, acls[marker[0]].permset,
3442314565Smm		    acls[marker[0]].tag, acls[marker[0]].qual,
3443314565Smm		    acls[marker[0]].name);
3444314565Smm		failure_finish(NULL);
3445314565Smm		ret = 1;
3446314565Smm		/* Number of ACLs not matched should == 0 */
3447314565Smm	}
3448310796Smm	free(marker);
3449314565Smm	return (ret);
3450310796Smm}
3451314565Smm#endif	/* !defined(PROGRAM) */
3452310796Smm
3453228753Smm/*
3454228753Smm *
3455228753Smm * TEST management
3456228753Smm *
3457228753Smm */
3458228753Smm
3459228753Smm/*
3460228753Smm * "list.h" is simply created by "grep DEFINE_TEST test_*.c"; it has
3461228753Smm * a line like
3462228753Smm *      DEFINE_TEST(test_function)
3463228753Smm * for each test.
3464228753Smm */
3465228753Smm
3466228753Smm/* Use "list.h" to declare all of the test functions. */
3467228753Smm#undef DEFINE_TEST
3468228753Smm#define	DEFINE_TEST(name) void name(void);
3469228753Smm#include "list.h"
3470228753Smm
3471228753Smm/* Use "list.h" to create a list of all tests (functions and names). */
3472228753Smm#undef DEFINE_TEST
3473228753Smm#define	DEFINE_TEST(n) { n, #n, 0 },
3474248590Smmstruct test_list_t tests[] = {
3475228753Smm	#include "list.h"
3476228753Smm};
3477228753Smm
3478228753Smm/*
3479228753Smm * Summarize repeated failures in the just-completed test.
3480228753Smm */
3481228753Smmstatic void
3482299425Smmtest_summarize(int failed, int skips_num)
3483228753Smm{
3484228753Smm	unsigned int i;
3485228753Smm
3486228753Smm	switch (verbosity) {
3487228753Smm	case VERBOSITY_SUMMARY_ONLY:
3488228753Smm		printf(failed ? "E" : ".");
3489228753Smm		fflush(stdout);
3490228753Smm		break;
3491228753Smm	case VERBOSITY_PASSFAIL:
3492299425Smm		printf(failed ? "FAIL\n" : skips_num ? "ok (S)\n" : "ok\n");
3493228753Smm		break;
3494228753Smm	}
3495228753Smm
3496228753Smm	log_console = (verbosity == VERBOSITY_LIGHT_REPORT);
3497228753Smm
3498228753Smm	for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {
3499228753Smm		if (failed_lines[i].count > 1 && !failed_lines[i].skip)
3500228753Smm			logprintf("%s:%d: Summary: Failed %d times\n",
3501231200Smm			    failed_filename, i, failed_lines[i].count);
3502228753Smm	}
3503228753Smm	/* Clear the failure history for the next file. */
3504231200Smm	failed_filename = NULL;
3505228753Smm	memset(failed_lines, 0, sizeof(failed_lines));
3506228753Smm}
3507228753Smm
3508228753Smm/*
3509228753Smm * Actually run a single test, with appropriate setup and cleanup.
3510228753Smm */
3511228753Smmstatic int
3512228753Smmtest_run(int i, const char *tmpdir)
3513228753Smm{
3514342361Smm#ifdef PATH_MAX
3515358090Smm	char workdir[PATH_MAX * 2];
3516342361Smm#else
3517358090Smm	char workdir[1024 * 2];
3518342361Smm#endif
3519228753Smm	char logfilename[64];
3520228753Smm	int failures_before = failures;
3521299425Smm	int skips_before = skips;
3522228753Smm	int oldumask;
3523228753Smm
3524228753Smm	switch (verbosity) {
3525228753Smm	case VERBOSITY_SUMMARY_ONLY: /* No per-test reports at all */
3526228753Smm		break;
3527228753Smm	case VERBOSITY_PASSFAIL: /* rest of line will include ok/FAIL marker */
3528299425Smm		printf("%3d: %-64s", i, tests[i].name);
3529228753Smm		fflush(stdout);
3530228753Smm		break;
3531228753Smm	default: /* Title of test, details will follow */
3532228753Smm		printf("%3d: %s\n", i, tests[i].name);
3533228753Smm	}
3534228753Smm
3535228753Smm	/* Chdir to the top-level work directory. */
3536228753Smm	if (!assertChdir(tmpdir)) {
3537228753Smm		fprintf(stderr,
3538228753Smm		    "ERROR: Can't chdir to top work dir %s\n", tmpdir);
3539228753Smm		exit(1);
3540228753Smm	}
3541228753Smm	/* Create a log file for this test. */
3542228753Smm	sprintf(logfilename, "%s.log", tests[i].name);
3543228753Smm	logfile = fopen(logfilename, "w");
3544228753Smm	fprintf(logfile, "%s\n\n", tests[i].name);
3545228753Smm	/* Chdir() to a work dir for this specific test. */
3546231200Smm	snprintf(workdir, sizeof(workdir), "%s/%s", tmpdir, tests[i].name);
3547231200Smm	testworkdir = workdir;
3548231200Smm	if (!assertMakeDir(testworkdir, 0755)
3549231200Smm	    || !assertChdir(testworkdir)) {
3550228753Smm		fprintf(stderr,
3551231200Smm		    "ERROR: Can't chdir to work dir %s\n", testworkdir);
3552228753Smm		exit(1);
3553228753Smm	}
3554228753Smm	/* Explicitly reset the locale before each test. */
3555228753Smm	setlocale(LC_ALL, "C");
3556228753Smm	/* Record the umask before we run the test. */
3557228753Smm	umask(oldumask = umask(0));
3558228753Smm	/*
3559228753Smm	 * Run the actual test.
3560228753Smm	 */
3561228753Smm	(*tests[i].func)();
3562228753Smm	/*
3563228753Smm	 * Clean up and report afterwards.
3564228753Smm	 */
3565231200Smm	testworkdir = NULL;
3566228753Smm	/* Restore umask */
3567228753Smm	umask(oldumask);
3568228753Smm	/* Reset locale. */
3569228753Smm	setlocale(LC_ALL, "C");
3570228753Smm	/* Reset directory. */
3571228753Smm	if (!assertChdir(tmpdir)) {
3572228753Smm		fprintf(stderr, "ERROR: Couldn't chdir to temp dir %s\n",
3573228753Smm		    tmpdir);
3574228753Smm		exit(1);
3575228753Smm	}
3576228753Smm	/* Report per-test summaries. */
3577228753Smm	tests[i].failures = failures - failures_before;
3578299425Smm	test_summarize(tests[i].failures, skips - skips_before);
3579228753Smm	/* Close the per-test log file. */
3580228753Smm	fclose(logfile);
3581228753Smm	logfile = NULL;
3582228753Smm	/* If there were no failures, we can remove the work dir and logfile. */
3583228753Smm	if (tests[i].failures == 0) {
3584228753Smm		if (!keep_temp_files && assertChdir(tmpdir)) {
3585228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
3586228753Smm			/* Make sure not to leave empty directories.
3587228753Smm			 * Sometimes a processing of closing files used by tests
3588228753Smm			 * is not done, then rmdir will be failed and it will
3589228753Smm			 * leave a empty test directory. So we should wait a few
3590228753Smm			 * seconds and retry rmdir. */
3591228753Smm			int r, t;
3592228753Smm			for (t = 0; t < 10; t++) {
3593228753Smm				if (t > 0)
3594228753Smm					Sleep(1000);
3595228753Smm				r = systemf("rmdir /S /Q %s", tests[i].name);
3596228753Smm				if (r == 0)
3597228753Smm					break;
3598228753Smm			}
3599228753Smm			systemf("del %s", logfilename);
3600228753Smm#else
3601228753Smm			systemf("rm -rf %s", tests[i].name);
3602228753Smm			systemf("rm %s", logfilename);
3603228753Smm#endif
3604228753Smm		}
3605228753Smm	}
3606228753Smm	/* Return appropriate status. */
3607228753Smm	return (tests[i].failures);
3608228753Smm}
3609228753Smm
3610228753Smm/*
3611228753Smm *
3612228753Smm *
3613228753Smm * MAIN and support routines.
3614228753Smm *
3615228753Smm *
3616228753Smm */
3617228753Smm
3618228753Smmstatic void
3619228753Smmusage(const char *program)
3620228753Smm{
3621228753Smm	static const int limit = sizeof(tests) / sizeof(tests[0]);
3622228753Smm	int i;
3623228753Smm
3624228753Smm	printf("Usage: %s [options] <test> <test> ...\n", program);
3625228753Smm	printf("Default is to run all tests.\n");
3626228753Smm	printf("Otherwise, specify the numbers of the tests you wish to run.\n");
3627228753Smm	printf("Options:\n");
3628228753Smm	printf("  -d  Dump core after any failure, for debugging.\n");
3629228753Smm	printf("  -k  Keep all temp files.\n");
3630228753Smm	printf("      Default: temp files for successful tests deleted.\n");
3631228753Smm#ifdef PROGRAM
3632228753Smm	printf("  -p <path>  Path to executable to be tested.\n");
3633228753Smm	printf("      Default: path taken from " ENVBASE " environment variable.\n");
3634228753Smm#endif
3635228753Smm	printf("  -q  Quiet.\n");
3636228753Smm	printf("  -r <dir>   Path to dir containing reference files.\n");
3637228753Smm	printf("      Default: Current directory.\n");
3638231200Smm	printf("  -u  Keep running specifies tests until one fails.\n");
3639228753Smm	printf("  -v  Verbose.\n");
3640228753Smm	printf("Available tests:\n");
3641228753Smm	for (i = 0; i < limit; i++)
3642228753Smm		printf("  %d: %s\n", i, tests[i].name);
3643228753Smm	exit(1);
3644228753Smm}
3645228753Smm
3646228753Smmstatic char *
3647228753Smmget_refdir(const char *d)
3648228753Smm{
3649302003Smm	size_t tried_size, buff_size;
3650302003Smm	char *buff, *tried, *pwd = NULL, *p = NULL;
3651228753Smm
3652302003Smm#ifdef PATH_MAX
3653302003Smm	buff_size = PATH_MAX;
3654302003Smm#else
3655302003Smm	buff_size = 8192;
3656302003Smm#endif
3657302003Smm	buff = calloc(buff_size, 1);
3658302003Smm	if (buff == NULL) {
3659302003Smm		fprintf(stderr, "Unable to allocate memory\n");
3660302003Smm		exit(1);
3661302003Smm	}
3662302003Smm
3663302003Smm	/* Allocate a buffer to hold the various directories we checked. */
3664302003Smm	tried_size = buff_size * 2;
3665302003Smm	tried = calloc(tried_size, 1);
3666302003Smm	if (tried == NULL) {
3667302003Smm		fprintf(stderr, "Unable to allocate memory\n");
3668302003Smm		exit(1);
3669302003Smm	}
3670302003Smm
3671228753Smm	/* If a dir was specified, try that */
3672228753Smm	if (d != NULL) {
3673228753Smm		pwd = NULL;
3674302003Smm		snprintf(buff, buff_size, "%s", d);
3675228753Smm		p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3676228753Smm		if (p != NULL) goto success;
3677302003Smm		strncat(tried, buff, tried_size - strlen(tried) - 1);
3678302003Smm		strncat(tried, "\n", tried_size - strlen(tried) - 1);
3679228753Smm		goto failure;
3680228753Smm	}
3681228753Smm
3682228753Smm	/* Get the current dir. */
3683231200Smm#ifdef PATH_MAX
3684231200Smm	pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */
3685231200Smm#else
3686228753Smm	pwd = getcwd(NULL, 0);
3687231200Smm#endif
3688228753Smm	while (pwd[strlen(pwd) - 1] == '\n')
3689228753Smm		pwd[strlen(pwd) - 1] = '\0';
3690228753Smm
3691228753Smm	/* Look for a known file. */
3692302003Smm	snprintf(buff, buff_size, "%s", pwd);
3693228753Smm	p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3694228753Smm	if (p != NULL) goto success;
3695302003Smm	strncat(tried, buff, tried_size - strlen(tried) - 1);
3696302003Smm	strncat(tried, "\n", tried_size - strlen(tried) - 1);
3697228753Smm
3698302003Smm	snprintf(buff, buff_size, "%s/test", pwd);
3699228753Smm	p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3700228753Smm	if (p != NULL) goto success;
3701302003Smm	strncat(tried, buff, tried_size - strlen(tried) - 1);
3702302003Smm	strncat(tried, "\n", tried_size - strlen(tried) - 1);
3703228753Smm
3704228753Smm#if defined(LIBRARY)
3705302003Smm	snprintf(buff, buff_size, "%s/%s/test", pwd, LIBRARY);
3706228753Smm#else
3707302003Smm	snprintf(buff, buff_size, "%s/%s/test", pwd, PROGRAM);
3708228753Smm#endif
3709228753Smm	p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3710228753Smm	if (p != NULL) goto success;
3711302003Smm	strncat(tried, buff, tried_size - strlen(tried) - 1);
3712302003Smm	strncat(tried, "\n", tried_size - strlen(tried) - 1);
3713228753Smm
3714231200Smm#if defined(PROGRAM_ALIAS)
3715302003Smm	snprintf(buff, buff_size, "%s/%s/test", pwd, PROGRAM_ALIAS);
3716231200Smm	p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3717231200Smm	if (p != NULL) goto success;
3718302003Smm	strncat(tried, buff, tried_size - strlen(tried) - 1);
3719302003Smm	strncat(tried, "\n", tried_size - strlen(tried) - 1);
3720231200Smm#endif
3721231200Smm
3722228753Smm	if (memcmp(pwd, "/usr/obj", 8) == 0) {
3723302003Smm		snprintf(buff, buff_size, "%s", pwd + 8);
3724228753Smm		p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3725228753Smm		if (p != NULL) goto success;
3726302003Smm		strncat(tried, buff, tried_size - strlen(tried) - 1);
3727302003Smm		strncat(tried, "\n", tried_size - strlen(tried) - 1);
3728228753Smm
3729302003Smm		snprintf(buff, buff_size, "%s/test", pwd + 8);
3730228753Smm		p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3731228753Smm		if (p != NULL) goto success;
3732302003Smm		strncat(tried, buff, tried_size - strlen(tried) - 1);
3733302003Smm		strncat(tried, "\n", tried_size - strlen(tried) - 1);
3734228753Smm	}
3735228753Smm
3736228753Smmfailure:
3737228753Smm	printf("Unable to locate known reference file %s\n", KNOWNREF);
3738228753Smm	printf("  Checked following directories:\n%s\n", tried);
3739299425Smm	printf("Use -r option to specify full path to reference directory\n");
3740228753Smm#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
3741228753Smm	DebugBreak();
3742228753Smm#endif
3743228753Smm	exit(1);
3744228753Smm
3745228753Smmsuccess:
3746228753Smm	free(p);
3747228753Smm	free(pwd);
3748302003Smm	free(tried);
3749302003Smm
3750302003Smm	/* Copy result into a fresh buffer to reduce memory usage. */
3751302003Smm	p = strdup(buff);
3752302003Smm	free(buff);
3753302003Smm	return p;
3754228753Smm}
3755228753Smm
3756228753Smmint
3757228753Smmmain(int argc, char **argv)
3758228753Smm{
3759228753Smm	static const int limit = sizeof(tests) / sizeof(tests[0]);
3760238825Smm	int test_set[sizeof(tests) / sizeof(tests[0])];
3761238825Smm	int i = 0, j = 0, tests_run = 0, tests_failed = 0, option;
3762228753Smm	time_t now;
3763228753Smm	char *refdir_alloc = NULL;
3764228753Smm	const char *progname;
3765231200Smm	char **saved_argv;
3766228753Smm	const char *tmp, *option_arg, *p;
3767342361Smm#ifdef PATH_MAX
3768342361Smm	char tmpdir[PATH_MAX];
3769342361Smm#else
3770342361Smm	char tmpdir[256];
3771342361Smm#endif
3772342361Smm	char *pwd, *testprogdir, *tmp2 = NULL, *vlevel = NULL;
3773342361Smm	char tmpdir_timestamp[32];
3774228753Smm
3775228753Smm	(void)argc; /* UNUSED */
3776228753Smm
3777231200Smm	/* Get the current dir. */
3778231200Smm#ifdef PATH_MAX
3779231200Smm	pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */
3780231200Smm#else
3781231200Smm	pwd = getcwd(NULL, 0);
3782231200Smm#endif
3783231200Smm	while (pwd[strlen(pwd) - 1] == '\n')
3784231200Smm		pwd[strlen(pwd) - 1] = '\0';
3785231200Smm
3786299425Smm#if defined(HAVE__CrtSetReportMode) && !defined(__WATCOMC__)
3787228753Smm	/* To stop to run the default invalid parameter handler. */
3788228753Smm	_set_invalid_parameter_handler(invalid_parameter_handler);
3789228753Smm	/* Disable annoying assertion message box. */
3790228753Smm	_CrtSetReportMode(_CRT_ASSERT, 0);
3791228753Smm#endif
3792228753Smm
3793228753Smm	/*
3794228753Smm	 * Name of this program, used to build root of our temp directory
3795228753Smm	 * tree.
3796228753Smm	 */
3797228753Smm	progname = p = argv[0];
3798231200Smm	if ((testprogdir = (char *)malloc(strlen(progname) + 1)) == NULL)
3799231200Smm	{
3800231200Smm		fprintf(stderr, "ERROR: Out of memory.");
3801231200Smm		exit(1);
3802231200Smm	}
3803231200Smm	strcpy(testprogdir, progname);
3804228753Smm	while (*p != '\0') {
3805228753Smm		/* Support \ or / dir separators for Windows compat. */
3806228753Smm		if (*p == '/' || *p == '\\')
3807231200Smm		{
3808228753Smm			progname = p + 1;
3809231200Smm			i = j;
3810231200Smm		}
3811228753Smm		++p;
3812231200Smm		j++;
3813228753Smm	}
3814231200Smm	testprogdir[i] = '\0';
3815232133Smm#if defined(_WIN32) && !defined(__CYGWIN__)
3816232133Smm	if (testprogdir[0] != '/' && testprogdir[0] != '\\' &&
3817232133Smm	    !(((testprogdir[0] >= 'a' && testprogdir[0] <= 'z') ||
3818232133Smm	       (testprogdir[0] >= 'A' && testprogdir[0] <= 'Z')) &&
3819232133Smm		testprogdir[1] == ':' &&
3820232133Smm		(testprogdir[2] == '/' || testprogdir[2] == '\\')))
3821232133Smm#else
3822231200Smm	if (testprogdir[0] != '/')
3823232133Smm#endif
3824231200Smm	{
3825231200Smm		/* Fixup path for relative directories. */
3826231200Smm		if ((testprogdir = (char *)realloc(testprogdir,
3827231200Smm			strlen(pwd) + 1 + strlen(testprogdir) + 1)) == NULL)
3828231200Smm		{
3829231200Smm			fprintf(stderr, "ERROR: Out of memory.");
3830231200Smm			exit(1);
3831231200Smm		}
3832232133Smm		memmove(testprogdir + strlen(pwd) + 1, testprogdir,
3833299425Smm		    strlen(testprogdir) + 1);
3834232133Smm		memcpy(testprogdir, pwd, strlen(pwd));
3835231200Smm		testprogdir[strlen(pwd)] = '/';
3836231200Smm	}
3837228753Smm
3838228753Smm#ifdef PROGRAM
3839228753Smm	/* Get the target program from environment, if available. */
3840228753Smm	testprogfile = getenv(ENVBASE);
3841228753Smm#endif
3842228753Smm
3843228753Smm	if (getenv("TMPDIR") != NULL)
3844228753Smm		tmp = getenv("TMPDIR");
3845228753Smm	else if (getenv("TMP") != NULL)
3846228753Smm		tmp = getenv("TMP");
3847228753Smm	else if (getenv("TEMP") != NULL)
3848228753Smm		tmp = getenv("TEMP");
3849228753Smm	else if (getenv("TEMPDIR") != NULL)
3850228753Smm		tmp = getenv("TEMPDIR");
3851228753Smm	else
3852228753Smm		tmp = "/tmp";
3853228753Smm
3854228753Smm	/* Allow -d to be controlled through the environment. */
3855228753Smm	if (getenv(ENVBASE "_DEBUG") != NULL)
3856228753Smm		dump_on_failure = 1;
3857228753Smm
3858238825Smm	/* Allow -v to be controlled through the environment. */
3859238825Smm	if (getenv("_VERBOSITY_LEVEL") != NULL)
3860238825Smm	{
3861238825Smm		vlevel = getenv("_VERBOSITY_LEVEL");
3862238825Smm		verbosity = atoi(vlevel);
3863238825Smm		if (verbosity < VERBOSITY_SUMMARY_ONLY || verbosity > VERBOSITY_FULL)
3864238825Smm		{
3865238825Smm			/* Unsupported verbosity levels are silently ignored */
3866238825Smm			vlevel = NULL;
3867238825Smm			verbosity = VERBOSITY_PASSFAIL;
3868238825Smm		}
3869238825Smm	}
3870238825Smm
3871228753Smm	/* Get the directory holding test files from environment. */
3872228753Smm	refdir = getenv(ENVBASE "_TEST_FILES");
3873228753Smm
3874228753Smm	/*
3875228753Smm	 * Parse options, without using getopt(), which isn't available
3876228753Smm	 * on all platforms.
3877228753Smm	 */
3878228753Smm	++argv; /* Skip program name */
3879228753Smm	while (*argv != NULL) {
3880228753Smm		if (**argv != '-')
3881228753Smm			break;
3882228753Smm		p = *argv++;
3883228753Smm		++p; /* Skip '-' */
3884228753Smm		while (*p != '\0') {
3885228753Smm			option = *p++;
3886228753Smm			option_arg = NULL;
3887228753Smm			/* If 'opt' takes an argument, parse that. */
3888228753Smm			if (option == 'p' || option == 'r') {
3889228753Smm				if (*p != '\0')
3890228753Smm					option_arg = p;
3891228753Smm				else if (*argv == NULL) {
3892228753Smm					fprintf(stderr,
3893228753Smm					    "Option -%c requires argument.\n",
3894228753Smm					    option);
3895228753Smm					usage(progname);
3896228753Smm				} else
3897228753Smm					option_arg = *argv++;
3898228753Smm				p = ""; /* End of this option word. */
3899228753Smm			}
3900228753Smm
3901228753Smm			/* Now, handle the option. */
3902228753Smm			switch (option) {
3903228753Smm			case 'd':
3904228753Smm				dump_on_failure = 1;
3905228753Smm				break;
3906228753Smm			case 'k':
3907228753Smm				keep_temp_files = 1;
3908228753Smm				break;
3909228753Smm			case 'p':
3910228753Smm#ifdef PROGRAM
3911228753Smm				testprogfile = option_arg;
3912228753Smm#else
3913231200Smm				fprintf(stderr, "-p option not permitted\n");
3914228753Smm				usage(progname);
3915228753Smm#endif
3916228753Smm				break;
3917228753Smm			case 'q':
3918238825Smm				if (!vlevel)
3919238825Smm					verbosity--;
3920228753Smm				break;
3921228753Smm			case 'r':
3922228753Smm				refdir = option_arg;
3923228753Smm				break;
3924231200Smm			case 'u':
3925231200Smm				until_failure++;
3926231200Smm				break;
3927228753Smm			case 'v':
3928238825Smm				if (!vlevel)
3929238825Smm					verbosity++;
3930228753Smm				break;
3931228753Smm			default:
3932231200Smm				fprintf(stderr, "Unrecognized option '%c'\n",
3933231200Smm				    option);
3934228753Smm				usage(progname);
3935228753Smm			}
3936228753Smm		}
3937228753Smm	}
3938228753Smm
3939228753Smm	/*
3940228753Smm	 * Sanity-check that our options make sense.
3941228753Smm	 */
3942228753Smm#ifdef PROGRAM
3943228753Smm	if (testprogfile == NULL)
3944228753Smm	{
3945231200Smm		if ((tmp2 = (char *)malloc(strlen(testprogdir) + 1 +
3946231200Smm			strlen(PROGRAM) + 1)) == NULL)
3947231200Smm		{
3948231200Smm			fprintf(stderr, "ERROR: Out of memory.");
3949231200Smm			exit(1);
3950231200Smm		}
3951231200Smm		strcpy(tmp2, testprogdir);
3952231200Smm		strcat(tmp2, "/");
3953231200Smm		strcat(tmp2, PROGRAM);
3954231200Smm		testprogfile = tmp2;
3955231200Smm	}
3956231200Smm
3957231200Smm	{
3958228753Smm		char *testprg;
3959228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
3960228753Smm		/* Command.com sometimes rejects '/' separators. */
3961228753Smm		testprg = strdup(testprogfile);
3962228753Smm		for (i = 0; testprg[i] != '\0'; i++) {
3963228753Smm			if (testprg[i] == '/')
3964228753Smm				testprg[i] = '\\';
3965228753Smm		}
3966228753Smm		testprogfile = testprg;
3967228753Smm#endif
3968228753Smm		/* Quote the name that gets put into shell command lines. */
3969228753Smm		testprg = malloc(strlen(testprogfile) + 3);
3970228753Smm		strcpy(testprg, "\"");
3971228753Smm		strcat(testprg, testprogfile);
3972228753Smm		strcat(testprg, "\"");
3973228753Smm		testprog = testprg;
3974228753Smm	}
3975228753Smm#endif
3976228753Smm
3977231200Smm#if !defined(_WIN32) && defined(SIGPIPE)
3978231200Smm	{   /* Ignore SIGPIPE signals */
3979231200Smm		struct sigaction sa;
3980231200Smm		sa.sa_handler = SIG_IGN;
3981231200Smm		sigemptyset(&sa.sa_mask);
3982231200Smm		sa.sa_flags = 0;
3983231200Smm		sigaction(SIGPIPE, &sa, NULL);
3984231200Smm	}
3985231200Smm#endif
3986231200Smm
3987228753Smm	/*
3988228753Smm	 * Create a temp directory for the following tests.
3989228753Smm	 * Include the time the tests started as part of the name,
3990228753Smm	 * to make it easier to track the results of multiple tests.
3991228753Smm	 */
3992228753Smm	now = time(NULL);
3993228753Smm	for (i = 0; ; i++) {
3994228753Smm		strftime(tmpdir_timestamp, sizeof(tmpdir_timestamp),
3995228753Smm		    "%Y-%m-%dT%H.%M.%S",
3996228753Smm		    localtime(&now));
3997342361Smm		if ((strlen(tmp) + 1 + strlen(progname) + 1 +
3998342361Smm		    strlen(tmpdir_timestamp) + 1 + 3) >
3999342361Smm		    (sizeof(tmpdir) / sizeof(char))) {
4000342361Smm			fprintf(stderr,
4001342361Smm			    "ERROR: Temp directory pathname too long\n");
4002342361Smm			exit(1);
4003342361Smm		}
4004342361Smm		snprintf(tmpdir, sizeof(tmpdir), "%s/%s.%s-%03d", tmp,
4005342361Smm		    progname, tmpdir_timestamp, i);
4006228753Smm		if (assertMakeDir(tmpdir,0755))
4007228753Smm			break;
4008228753Smm		if (i >= 999) {
4009228753Smm			fprintf(stderr,
4010228753Smm			    "ERROR: Unable to create temp directory %s\n",
4011228753Smm			    tmpdir);
4012228753Smm			exit(1);
4013228753Smm		}
4014228753Smm	}
4015228753Smm
4016228753Smm	/*
4017228753Smm	 * If the user didn't specify a directory for locating
4018228753Smm	 * reference files, try to find the reference files in
4019228753Smm	 * the "usual places."
4020228753Smm	 */
4021228753Smm	refdir = refdir_alloc = get_refdir(refdir);
4022228753Smm
4023228753Smm	/*
4024228753Smm	 * Banner with basic information.
4025228753Smm	 */
4026228753Smm	printf("\n");
4027228753Smm	printf("If tests fail or crash, details will be in:\n");
4028228753Smm	printf("   %s\n", tmpdir);
4029228753Smm	printf("\n");
4030228753Smm	if (verbosity > VERBOSITY_SUMMARY_ONLY) {
4031228753Smm		printf("Reference files will be read from: %s\n", refdir);
4032228753Smm#ifdef PROGRAM
4033228753Smm		printf("Running tests on: %s\n", testprog);
4034228753Smm#endif
4035228753Smm		printf("Exercising: ");
4036228753Smm		fflush(stdout);
4037228753Smm		printf("%s\n", EXTRA_VERSION);
4038228753Smm	} else {
4039228753Smm		printf("Running ");
4040228753Smm		fflush(stdout);
4041228753Smm	}
4042228753Smm
4043228753Smm	/*
4044228753Smm	 * Run some or all of the individual tests.
4045228753Smm	 */
4046231200Smm	saved_argv = argv;
4047231200Smm	do {
4048231200Smm		argv = saved_argv;
4049238825Smm		do {
4050238825Smm			int test_num;
4051238825Smm
4052248590Smm			test_num = get_test_set(test_set, limit, *argv, tests);
4053238825Smm			if (test_num < 0) {
4054238825Smm				printf("*** INVALID Test %s\n", *argv);
4055238825Smm				free(refdir_alloc);
4056248590Smm				free(testprogdir);
4057238825Smm				usage(progname);
4058238825Smm				return (1);
4059238825Smm			}
4060238825Smm			for (i = 0; i < test_num; i++) {
4061231200Smm				tests_run++;
4062238825Smm				if (test_run(test_set[i], tmpdir)) {
4063231200Smm					tests_failed++;
4064231200Smm					if (until_failure)
4065231200Smm						goto finish;
4066228753Smm				}
4067231200Smm			}
4068238825Smm			if (*argv != NULL)
4069231200Smm				argv++;
4070238825Smm		} while (*argv != NULL);
4071231200Smm	} while (until_failure);
4072228753Smm
4073231200Smmfinish:
4074231200Smm	/* Must be freed after all tests run */
4075231200Smm	free(tmp2);
4076231200Smm	free(testprogdir);
4077231200Smm	free(pwd);
4078231200Smm
4079228753Smm	/*
4080228753Smm	 * Report summary statistics.
4081228753Smm	 */
4082228753Smm	if (verbosity > VERBOSITY_SUMMARY_ONLY) {
4083228753Smm		printf("\n");
4084228753Smm		printf("Totals:\n");
4085228753Smm		printf("  Tests run:         %8d\n", tests_run);
4086228753Smm		printf("  Tests failed:      %8d\n", tests_failed);
4087228753Smm		printf("  Assertions checked:%8d\n", assertions);
4088228753Smm		printf("  Assertions failed: %8d\n", failures);
4089228753Smm		printf("  Skips reported:    %8d\n", skips);
4090228753Smm	}
4091228753Smm	if (failures) {
4092228753Smm		printf("\n");
4093228753Smm		printf("Failing tests:\n");
4094228753Smm		for (i = 0; i < limit; ++i) {
4095228753Smm			if (tests[i].failures)
4096228753Smm				printf("  %d: %s (%d failures)\n", i,
4097228753Smm				    tests[i].name, tests[i].failures);
4098228753Smm		}
4099228753Smm		printf("\n");
4100228753Smm		printf("Details for failing tests: %s\n", tmpdir);
4101228753Smm		printf("\n");
4102228753Smm	} else {
4103228753Smm		if (verbosity == VERBOSITY_SUMMARY_ONLY)
4104228753Smm			printf("\n");
4105228753Smm		printf("%d tests passed, no failures\n", tests_run);
4106228753Smm	}
4107228753Smm
4108228753Smm	free(refdir_alloc);
4109228753Smm
4110228753Smm	/* If the final tmpdir is empty, we can remove it. */
4111228753Smm	/* This should be the usual case when all tests succeed. */
4112228753Smm	assertChdir("..");
4113228753Smm	rmdir(tmpdir);
4114228753Smm
4115228753Smm	return (tests_failed ? 1 : 0);
4116228753Smm}
4117