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