1 /*
2 * Copyright (c) 2003-2009 Tim Kientzle
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26 #include "test.h"
27 #include "test_utils.h"
28 #ifdef HAVE_SYS_IOCTL_H
29 #include <sys/ioctl.h>
30 #endif
31 #ifdef HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34 #include <errno.h>
35 #ifdef HAVE_ICONV_H
36 #include <iconv.h>
37 #endif
38 /*
39 * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
40 * As the include guards don't agree, the order of include is important.
41 */
42 #ifdef HAVE_LINUX_EXT2_FS_H
43 #include <linux/ext2_fs.h> /* for Linux file flags */
44 #endif
45 #if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
46 #include <ext2fs/ext2_fs.h> /* Linux file flags, broken on Cygwin */
47 #endif
48 #ifdef HAVE_LINUX_FS_H
49 #include <linux/fs.h>
50 #endif
51 #include <limits.h>
52 #include <locale.h>
53 #ifdef HAVE_SIGNAL_H
54 #include <signal.h>
55 #endif
56 #include <stdarg.h>
57 #include <time.h>
58
59 #ifdef HAVE_SIGNAL_H
60 #endif
61 #ifdef HAVE_ACL_LIBACL_H
62 #include <acl/libacl.h>
63 #endif
64 #ifdef HAVE_SYS_TYPES_H
65 #include <sys/types.h>
66 #endif
67 #ifdef HAVE_SYS_ACL_H
68 #include <sys/acl.h>
69 #endif
70 #ifdef HAVE_SYS_EA_H
71 #include <sys/ea.h>
72 #endif
73 #ifdef HAVE_SYS_EXTATTR_H
74 #include <sys/extattr.h>
75 #endif
76 #if HAVE_SYS_XATTR_H
77 #include <sys/xattr.h>
78 #elif HAVE_ATTR_XATTR_H
79 #include <attr/xattr.h>
80 #endif
81 #ifdef HAVE_SYS_RICHACL_H
82 #include <sys/richacl.h>
83 #endif
84 #if HAVE_MEMBERSHIP_H
85 #include <membership.h>
86 #endif
87 #if !defined(_WIN32) || defined(__CYGWIN__)
88 # if HAVE_POSIX_SPAWN
89 # if HAVE_SYS_WAIT_H
90 # include <sys/wait.h>
91 # endif
92 # if HAVE_SPAWN_H
93 # include <spawn.h>
94 # endif
95 extern char **environ;
96 # define USE_POSIX_SPAWN 1
97 # endif
98 #endif
99 #if !defined(_WIN32)
100 # if HAVE_PWD_H && HAVE_GETEUID && HAVE_GETEGID
101 # include <pwd.h>
102 # define RUN_TEST_UNPRIV 1
103 # endif
104 #endif
105
106 #ifndef nitems
107 #define nitems(arr) (sizeof(arr) / sizeof((arr)[0]))
108 #endif
109
110 /*
111 *
112 * Windows support routines
113 *
114 * Note: Configuration is a tricky issue. Using HAVE_* feature macros
115 * in the test harness is dangerous because they cover up
116 * configuration errors. The classic example of this is omitting a
117 * configure check. If libarchive and libarchive_test both look for
118 * the same feature macro, such errors are hard to detect. Platform
119 * macros (e.g., _WIN32 or __GNUC__) are a little better, but can
120 * easily lead to very messy code. It's best to limit yourself
121 * to only the most generic programming techniques in the test harness
122 * and thus avoid conditionals altogether. Where that's not possible,
123 * try to minimize conditionals by grouping platform-specific tests in
124 * one place (e.g., test_acl_freebsd) or by adding new assert()
125 * functions (e.g., assertMakeHardlink()) to cover up platform
126 * differences. Platform-specific coding in libarchive_test is often
127 * a symptom that some capability is missing from libarchive itself.
128 */
129 #if defined(_WIN32) && !defined(__CYGWIN__)
130 #include <io.h>
131 #include <direct.h>
132 #include <windows.h>
133 #ifndef F_OK
134 #define F_OK (0)
135 #endif
136 #ifndef S_ISDIR
137 #define S_ISDIR(m) ((m) & _S_IFDIR)
138 #endif
139 #ifndef S_ISREG
140 #define S_ISREG(m) ((m) & _S_IFREG)
141 #endif
142 #if !defined(__BORLANDC__)
143 #define access _access
144 #undef chdir
145 #define chdir _chdir
146 #undef chmod
147 #define chmod _chmod
148 #endif
149 #ifndef fileno
150 #define fileno _fileno
151 #endif
152 /*#define fstat _fstat64*/
153 #if !defined(__BORLANDC__)
154 #define getcwd _getcwd
155 #endif
156 #define rmdir _rmdir
157 #if !defined(__BORLANDC__)
158 #define strdup _strdup
159 #define umask _umask
160 #endif
161 #define int64_t __int64
162 #endif
163
164 #if defined(HAVE__CrtSetReportMode)
165 # include <crtdbg.h>
166 #endif
167
umasked(mode_t expected_mode)168 mode_t umasked(mode_t expected_mode)
169 {
170 mode_t mode = umask(0);
171 umask(mode);
172 return expected_mode & ~mode;
173 }
174
175 /* Path to working directory for current test */
176 const char *testworkdir;
177 #ifdef PROGRAM
178 /* Pathname of exe to be tested. */
179 const char *testprogfile;
180 /* Name of exe to use in printf-formatted command strings. */
181 /* On Windows, this includes leading/trailing quotes. */
182 const char *testprog;
183 #endif
184
185 #ifdef RUN_TEST_UNPRIV
186 /* Unprivileged user to run as */
187 static const char *tuser = "nobody";
188 /* Original and test credentials */
189 static uid_t ouid, tuid;
190 static uid_t ogid, tgid;
191 #endif
192
193 #if defined(_WIN32) && !defined(__CYGWIN__)
194 static void *GetFunctionKernel32(const char *);
195 static int my_CreateSymbolicLinkA(const char *, const char *, int);
196 static int my_CreateHardLinkA(const char *, const char *);
197 static int my_GetFileInformationByName(const char *,
198 BY_HANDLE_FILE_INFORMATION *);
199
200 typedef struct _REPARSE_DATA_BUFFER {
201 ULONG ReparseTag;
202 USHORT ReparseDataLength;
203 USHORT Reserved;
204 union {
205 struct {
206 USHORT SubstituteNameOffset;
207 USHORT SubstituteNameLength;
208 USHORT PrintNameOffset;
209 USHORT PrintNameLength;
210 ULONG Flags;
211 WCHAR PathBuffer[1];
212 } SymbolicLinkReparseBuffer;
213 struct {
214 USHORT SubstituteNameOffset;
215 USHORT SubstituteNameLength;
216 USHORT PrintNameOffset;
217 USHORT PrintNameLength;
218 WCHAR PathBuffer[1];
219 } MountPointReparseBuffer;
220 struct {
221 UCHAR DataBuffer[1];
222 } GenericReparseBuffer;
223 } DUMMYUNIONNAME;
224 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
225
226 static void *
GetFunctionKernel32(const char * name)227 GetFunctionKernel32(const char *name)
228 {
229 static HINSTANCE lib;
230 static int set;
231 if (!set) {
232 set = 1;
233 lib = LoadLibrary("kernel32.dll");
234 }
235 if (lib == NULL) {
236 fprintf(stderr, "Can't load kernel32.dll?!\n");
237 exit(1);
238 }
239 return (void *)GetProcAddress(lib, name);
240 }
241
242 static int
my_CreateSymbolicLinkA(const char * linkname,const char * target,int targetIsDir)243 my_CreateSymbolicLinkA(const char *linkname, const char *target,
244 int targetIsDir)
245 {
246 static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, DWORD);
247 DWORD attrs;
248 static int set;
249 int ret, tmpflags;
250 size_t llen, tlen;
251 int flags = 0;
252 char *src, *tgt, *p;
253 if (!set) {
254 set = 1;
255 f = GetFunctionKernel32("CreateSymbolicLinkA");
256 }
257 if (f == NULL)
258 return (0);
259
260 tlen = strlen(target);
261 llen = strlen(linkname);
262
263 if (tlen == 0 || llen == 0)
264 return (0);
265
266 tgt = malloc(tlen + 1);
267 if (tgt == NULL)
268 return (0);
269 src = malloc(llen + 1);
270 if (src == NULL) {
271 free(tgt);
272 return (0);
273 }
274
275 /*
276 * Translate slashes to backslashes
277 */
278 p = src;
279 while(*linkname != '\0') {
280 if (*linkname == '/')
281 *p = '\\';
282 else
283 *p = *linkname;
284 linkname++;
285 p++;
286 }
287 *p = '\0';
288
289 p = tgt;
290 while(*target != '\0') {
291 if (*target == '/')
292 *p = '\\';
293 else
294 *p = *target;
295 target++;
296 p++;
297 }
298 *p = '\0';
299
300 /*
301 * Each test has to specify if a file or a directory symlink
302 * should be created.
303 */
304 if (targetIsDir) {
305 #if defined(SYMBOLIC_LINK_FLAG_DIRECTORY)
306 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
307 #else
308 flags |= 0x1;
309 #endif
310 }
311
312 #if defined(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)
313 tmpflags = flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
314 #else
315 tmpflags = flags | 0x2;
316 #endif
317 /*
318 * Windows won't overwrite existing links
319 */
320 attrs = GetFileAttributesA(linkname);
321 if (attrs != INVALID_FILE_ATTRIBUTES) {
322 if (attrs & FILE_ATTRIBUTE_DIRECTORY)
323 RemoveDirectoryA(linkname);
324 else
325 DeleteFileA(linkname);
326 }
327
328 ret = (*f)(src, tgt, tmpflags);
329 /*
330 * Prior to Windows 10 the SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
331 * is not understood
332 */
333 if (!ret)
334 ret = (*f)(src, tgt, flags);
335
336 free(src);
337 free(tgt);
338 return (ret);
339 }
340
341 static int
my_CreateHardLinkA(const char * linkname,const char * target)342 my_CreateHardLinkA(const char *linkname, const char *target)
343 {
344 static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, LPSECURITY_ATTRIBUTES);
345 static int set;
346 if (!set) {
347 set = 1;
348 f = GetFunctionKernel32("CreateHardLinkA");
349 }
350 return f == NULL ? 0 : (*f)(linkname, target, NULL);
351 }
352
353 static int
my_GetFileInformationByName(const char * path,BY_HANDLE_FILE_INFORMATION * bhfi)354 my_GetFileInformationByName(const char *path, BY_HANDLE_FILE_INFORMATION *bhfi)
355 {
356 HANDLE h;
357 int r;
358 const char *p;
359 char *s, *pn;
360
361 /* Replace slashes with backslashes in path */
362 pn = malloc(strlen(path) + 1);
363 if (pn == NULL) {
364 return (0);
365 }
366
367 for (p = path, s = pn; *p != '\0'; p++, s++) {
368 if (*p == '/')
369 *s = '\\';
370 else
371 *s = *p;
372 }
373 *s = '\0';
374
375 memset(bhfi, 0, sizeof(*bhfi));
376 h = CreateFileA(pn, FILE_READ_ATTRIBUTES, 0, NULL,
377 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
378 FILE_FLAG_OPEN_REPARSE_POINT, NULL);
379 free(pn);
380 if (h == INVALID_HANDLE_VALUE)
381 return (0);
382 r = GetFileInformationByHandle(h, bhfi);
383 CloseHandle(h);
384 return (r);
385 }
386 #endif
387
388 #if defined(HAVE__CrtSetReportMode) && !defined(__WATCOMC__)
389 static void
invalid_parameter_handler(const wchar_t * expression,const wchar_t * function,const wchar_t * file,unsigned int line,uintptr_t pReserved)390 invalid_parameter_handler(const wchar_t * expression,
391 const wchar_t * function, const wchar_t * file,
392 unsigned int line, uintptr_t pReserved)
393 {
394 /* nop */
395 // Silence unused-parameter compiler warnings.
396 (void)expression;
397 (void)function;
398 (void)file;
399 (void)line;
400 (void)pReserved;
401 }
402 #endif
403
404 /*
405 *
406 * OPTIONS FLAGS
407 *
408 */
409
410 /* Enable core dump on failure. */
411 static int dump_on_failure = 0;
412 /* Default is to remove temp dirs and log data for successful tests. */
413 static int keep_temp_files = 0;
414 /* Default is to only return a failure code (1) if there were test failures. If enabled, exit with code 2 if there were no failures, but some tests were skipped. */
415 static int fail_if_tests_skipped = 0;
416 /* Default is to run the specified tests once and report errors. */
417 static int until_failure = 0;
418 /* Default is to just report pass/fail for each test. */
419 static int verbosity = 0;
420 #define VERBOSITY_SUMMARY_ONLY -1 /* -q */
421 #define VERBOSITY_PASSFAIL 0 /* Default */
422 #define VERBOSITY_LIGHT_REPORT 1 /* -v */
423 #define VERBOSITY_FULL 2 /* -vv */
424 /* A few places generate even more output for verbosity > VERBOSITY_FULL,
425 * mostly for debugging the test harness itself. */
426 /* Cumulative count of assertion failures. */
427 static int failures = 0;
428 /* Cumulative count of reported skips. */
429 static int skips = 0;
430 /* Cumulative count of assertions checked. */
431 static int assertions = 0;
432
433 /* Directory where uuencoded reference files can be found. */
434 static const char *refdir;
435
436 /*
437 * Report log information selectively to console and/or disk log.
438 */
439 static int log_console = 0;
440 static FILE *logfile;
441 static void __LA_PRINTFLIKE(1, 0)
vlogprintf(const char * fmt,va_list ap)442 vlogprintf(const char *fmt, va_list ap)
443 {
444 #ifdef va_copy
445 va_list lfap;
446 va_copy(lfap, ap);
447 #endif
448 if (log_console)
449 vfprintf(stdout, fmt, ap);
450 if (logfile != NULL)
451 #ifdef va_copy
452 vfprintf(logfile, fmt, lfap);
453 va_end(lfap);
454 #else
455 vfprintf(logfile, fmt, ap);
456 #endif
457 }
458
459 static void __LA_PRINTFLIKE(1, 2)
logprintf(const char * fmt,...)460 logprintf(const char *fmt, ...)
461 {
462 va_list ap;
463 va_start(ap, fmt);
464 vlogprintf(fmt, ap);
465 va_end(ap);
466 }
467
468 /* Set up a message to display only if next assertion fails. */
469 static char msgbuff[4096];
470 static const char *msg, *nextmsg;
471 void
failure(const char * fmt,...)472 failure(const char *fmt, ...)
473 {
474 va_list ap;
475 if (fmt == NULL) {
476 nextmsg = NULL;
477 } else {
478 va_start(ap, fmt);
479 vsnprintf(msgbuff, sizeof(msgbuff), fmt, ap);
480 va_end(ap);
481 nextmsg = msgbuff;
482 }
483 }
484
485 /*
486 * Copy arguments into file-local variables.
487 * This was added to permit vararg assert() functions without needing
488 * variadic wrapper macros. Turns out that the vararg capability is almost
489 * never used, so almost all of the vararg assertions can be simplified
490 * by removing the vararg capability and reworking the wrapper macro to
491 * pass __FILE__, __LINE__ directly into the function instead of using
492 * this hook. I suspect this machinery is used so rarely that we
493 * would be better off just removing it entirely. That would simplify
494 * the code here noticeably.
495 */
496 static const char *skipping_filename;
497 static int skipping_line;
skipping_setup(const char * filename,int line)498 void skipping_setup(const char *filename, int line)
499 {
500 skipping_filename = filename;
501 skipping_line = line;
502 }
503
504 /* Called at the beginning of each assert() function. */
505 static void
assertion_count(const char * file,int line)506 assertion_count(const char *file, int line)
507 {
508 (void)file; /* UNUSED */
509 (void)line; /* UNUSED */
510 ++assertions;
511 /* Proper handling of "failure()" message. */
512 msg = nextmsg;
513 nextmsg = NULL;
514 /* Uncomment to print file:line after every assertion.
515 * Verbose, but occasionally useful in tracking down crashes. */
516 /* printf("Checked %s:%d\n", file, line); */
517 }
518
519 /*
520 * For each test source file, we remember how many times each
521 * assertion was reported. Cleared before each new test,
522 * used by test_summarize().
523 */
524 static struct line {
525 int count;
526 int skip;
527 } failed_lines[10000];
528 static const char *failed_filename;
529
530 /* Count this failure, setup up log destination and handle initial report. */
531 static void __LA_PRINTFLIKE(3, 4)
failure_start(const char * filename,int line,const char * fmt,...)532 failure_start(const char *filename, int line, const char *fmt, ...)
533 {
534 va_list ap;
535
536 /* Record another failure for this line. */
537 ++failures;
538 failed_filename = filename;
539 failed_lines[line].count++;
540
541 /* Determine whether to log header to console. */
542 switch (verbosity) {
543 case VERBOSITY_LIGHT_REPORT:
544 log_console = (failed_lines[line].count < 2);
545 break;
546 default:
547 log_console = (verbosity >= VERBOSITY_FULL);
548 }
549
550 /* Log file:line header for this failure */
551 va_start(ap, fmt);
552 #if _MSC_VER
553 logprintf("%s(%d): ", filename, line);
554 #else
555 logprintf("%s:%d: ", filename, line);
556 #endif
557 vlogprintf(fmt, ap);
558 va_end(ap);
559 logprintf("\n");
560
561 if (msg != NULL && msg[0] != '\0') {
562 logprintf(" Description: %s\n", msg);
563 msg = NULL;
564 }
565
566 /* Determine whether to log details to console. */
567 if (verbosity == VERBOSITY_LIGHT_REPORT)
568 log_console = 0;
569 }
570
571 /* Complete reporting of failed tests. */
572 /*
573 * The 'extra' hook here is used by libarchive to include libarchive
574 * error messages with assertion failures. It could also be used
575 * to add strerror() output, for example. Just define the EXTRA_DUMP()
576 * macro appropriately.
577 */
578 static void
failure_finish(void * extra)579 failure_finish(void *extra)
580 {
581 (void)extra; /* UNUSED (maybe) */
582 #ifdef EXTRA_DUMP
583 if (extra != NULL) {
584 logprintf(" errno: %d\n", EXTRA_ERRNO(extra));
585 logprintf(" detail: %s\n", EXTRA_DUMP(extra));
586 }
587 #endif
588
589 if (dump_on_failure) {
590 fprintf(stderr,
591 " *** forcing core dump so failure can be debugged ***\n");
592 abort();
593 }
594 }
595
596 /* Inform user that we're skipping some checks. */
597 void
test_skipping(const char * fmt,...)598 test_skipping(const char *fmt, ...)
599 {
600 char buff[1024];
601 va_list ap;
602
603 va_start(ap, fmt);
604 vsnprintf(buff, sizeof(buff), fmt, ap);
605 va_end(ap);
606 /* Use failure() message if set. */
607 msg = nextmsg;
608 nextmsg = NULL;
609 /* failure_start() isn't quite right, but is awfully convenient. */
610 failure_start(skipping_filename, skipping_line, "SKIPPING: %s", buff);
611 --failures; /* Undo failures++ in failure_start() */
612 /* Don't failure_finish() here. */
613 /* Mark as skip, so doesn't count as failed test. */
614 failed_lines[skipping_line].skip = 1;
615 ++skips;
616 }
617
618 /*
619 *
620 * ASSERTIONS
621 *
622 */
623
624 /* Generic assert() just displays the failed condition. */
625 int
assertion_assert(const char * file,int line,int value,const char * condition,void * extra)626 assertion_assert(const char *file, int line, int value,
627 const char *condition, void *extra)
628 {
629 assertion_count(file, line);
630 if (!value) {
631 failure_start(file, line, "Assertion failed: %s", condition);
632 failure_finish(extra);
633 }
634 return (value);
635 }
636
637 /* chdir() and report any errors */
638 int
assertion_chdir(const char * file,int line,const char * pathname)639 assertion_chdir(const char *file, int line, const char *pathname)
640 {
641 assertion_count(file, line);
642 if (chdir(pathname) == 0)
643 return (1);
644 failure_start(file, line, "chdir(\"%s\")", pathname);
645 failure_finish(NULL);
646 return (0);
647
648 }
649
650 /* change file/directory permissions and errors if it fails */
651 int
assertion_chmod(const char * file,int line,const char * pathname,int mode)652 assertion_chmod(const char *file, int line, const char *pathname, int mode)
653 {
654 assertion_count(file, line);
655 if (chmod(pathname, (mode_t)mode) == 0)
656 return (1);
657 failure_start(file, line, "chmod(\"%s\", %4.o)", pathname,
658 (unsigned int)mode);
659 failure_finish(NULL);
660 return (0);
661
662 }
663
664 /* change file/directory ownership and errors if it fails */
665 int
assertion_chown(const char * file,int line,const char * pathname,int user,int group)666 assertion_chown(const char *file, int line, const char *pathname, int user,
667 int group)
668 {
669 assertion_count(file, line);
670 #ifdef HAVE_CHOWN
671 if (chown(pathname, (uid_t)user, (gid_t)group) == 0)
672 return (1);
673 #endif
674 failure_start(file, line, "chown(\"%s\", %d, %d)", pathname,
675 user, group);
676 failure_finish(NULL);
677 return (0);
678 }
679
680 /* Verify two integers are equal. */
681 int
assertion_equal_int(const char * file,int line,long long v1,const char * e1,long long v2,const char * e2,void * extra)682 assertion_equal_int(const char *file, int line,
683 long long v1, const char *e1, long long v2, const char *e2, void *extra)
684 {
685 assertion_count(file, line);
686 if (v1 == v2)
687 return (1);
688 failure_start(file, line, "%s != %s", e1, e2);
689 logprintf(" %s=%lld (0x%llx, 0%llo)\n", e1, v1,
690 (unsigned long long)v1, (unsigned long long)v1);
691 logprintf(" %s=%lld (0x%llx, 0%llo)\n", e2, v2,
692 (unsigned long long)v2, (unsigned long long)v2);
693 failure_finish(extra);
694 return (0);
695 }
696
697 /* Verify two pointers are equal. */
698 int
assertion_equal_address(const char * file,int line,const void * v1,const char * e1,const void * v2,const char * e2,void * extra)699 assertion_equal_address(const char *file, int line,
700 const void *v1, const char *e1, const void *v2, const char *e2, void *extra)
701 {
702 assertion_count(file, line);
703 if (v1 == v2)
704 return (1);
705 failure_start(file, line, "%s != %s", e1, e2);
706 logprintf(" %s=0x%llx\n", e1, (unsigned long long)(uintptr_t)v1);
707 logprintf(" %s=0x%llx\n", e2, (unsigned long long)(uintptr_t)v2);
708 failure_finish(extra);
709 return (0);
710 }
711
712 /*
713 * Utility to convert a single UTF-8 sequence.
714 */
715 static int
_utf8_to_unicode(uint32_t * pwc,const char * s,size_t n)716 _utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
717 {
718 static const char utf8_count[256] = {
719 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
720 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
721 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
722 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
723 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
724 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
725 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
726 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
727 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
728 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
729 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
730 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
731 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
732 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
733 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
734 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
735 };
736 int ch;
737 int cnt;
738 uint32_t wc;
739
740 *pwc = 0;
741
742 /* Sanity check. */
743 if (n == 0)
744 return (0);
745 /*
746 * Decode 1-4 bytes depending on the value of the first byte.
747 */
748 ch = (unsigned char)*s;
749 if (ch == 0)
750 return (0); /* Standard: return 0 for end-of-string. */
751 cnt = utf8_count[ch];
752
753 /* Invalid sequence or there are not plenty bytes. */
754 if (n < (size_t)cnt)
755 return (-1);
756
757 /* Make a Unicode code point from a single UTF-8 sequence. */
758 switch (cnt) {
759 case 1: /* 1 byte sequence. */
760 *pwc = ch & 0x7f;
761 return (cnt);
762 case 2: /* 2 bytes sequence. */
763 if ((s[1] & 0xc0) != 0x80) return (-1);
764 *pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
765 return (cnt);
766 case 3: /* 3 bytes sequence. */
767 if ((s[1] & 0xc0) != 0x80) return (-1);
768 if ((s[2] & 0xc0) != 0x80) return (-1);
769 wc = ((ch & 0x0f) << 12)
770 | ((s[1] & 0x3f) << 6)
771 | (s[2] & 0x3f);
772 if (wc < 0x800)
773 return (-1);/* Overlong sequence. */
774 break;
775 case 4: /* 4 bytes sequence. */
776 if (n < 4)
777 return (-1);
778 if ((s[1] & 0xc0) != 0x80) return (-1);
779 if ((s[2] & 0xc0) != 0x80) return (-1);
780 if ((s[3] & 0xc0) != 0x80) return (-1);
781 wc = ((ch & 0x07) << 18)
782 | ((s[1] & 0x3f) << 12)
783 | ((s[2] & 0x3f) << 6)
784 | (s[3] & 0x3f);
785 if (wc < 0x10000)
786 return (-1);/* Overlong sequence. */
787 break;
788 default:
789 return (-1);
790 }
791
792 /* The code point larger than 0x10FFFF is not legal
793 * Unicode values. */
794 if (wc > 0x10FFFF)
795 return (-1);
796 /* Correctly gets a Unicode, returns used bytes. */
797 *pwc = wc;
798 return (cnt);
799 }
800
strdump(const char * e,const char * p,int ewidth,int utf8)801 static void strdump(const char *e, const char *p, int ewidth, int utf8)
802 {
803 const char *q = p;
804
805 logprintf(" %*s = ", ewidth, e);
806 if (p == NULL) {
807 logprintf("NULL\n");
808 return;
809 }
810 logprintf("\"");
811 while (*p != '\0') {
812 unsigned int c = 0xff & *p++;
813 switch (c) {
814 case '\a': logprintf("\\a"); break;
815 case '\b': logprintf("\\b"); break;
816 case '\n': logprintf("\\n"); break;
817 case '\r': logprintf("\\r"); break;
818 default:
819 if (c >= 32 && c < 127)
820 logprintf("%c", (int)c);
821 else
822 logprintf("\\x%02X", c);
823 }
824 }
825 logprintf("\"");
826 logprintf(" (length %d)", q == NULL ? -1 : (int)strlen(q));
827
828 /*
829 * If the current string is UTF-8, dump its code points.
830 */
831 if (utf8) {
832 size_t len;
833 uint32_t uc;
834 int n;
835 int cnt = 0;
836
837 p = q;
838 len = strlen(p);
839 logprintf(" [");
840 while ((n = _utf8_to_unicode(&uc, p, len)) > 0) {
841 if (p != q)
842 logprintf(" ");
843 logprintf("%04X", uc);
844 p += n;
845 len -= n;
846 cnt++;
847 }
848 logprintf("]");
849 logprintf(" (count %d", cnt);
850 if (n < 0) {
851 logprintf(",unknown %zu bytes", len);
852 }
853 logprintf(")");
854
855 }
856 logprintf("\n");
857 }
858
859 /* Verify two strings are equal, dump them if not. */
860 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)861 assertion_equal_string(const char *file, int line,
862 const char *v1, const char *e1,
863 const char *v2, const char *e2,
864 void *extra, int utf8)
865 {
866 int l1, l2;
867
868 assertion_count(file, line);
869 if (v1 == v2 || (v1 != NULL && v2 != NULL && strcmp(v1, v2) == 0))
870 return (1);
871 failure_start(file, line, "%s != %s", e1, e2);
872 l1 = (int)strlen(e1);
873 l2 = (int)strlen(e2);
874 if (l1 < l2)
875 l1 = l2;
876 strdump(e1, v1, l1, utf8);
877 strdump(e2, v2, l1, utf8);
878 failure_finish(extra);
879 return (0);
880 }
881
882 static void
wcsdump(const char * e,const wchar_t * w)883 wcsdump(const char *e, const wchar_t *w)
884 {
885 logprintf(" %s = ", e);
886 if (w == NULL) {
887 logprintf("(null)");
888 return;
889 }
890 logprintf("\"");
891 while (*w != L'\0') {
892 unsigned int c = *w++;
893 if (c >= 32 && c < 127)
894 logprintf("%c", (int)c);
895 else if (c < 256)
896 logprintf("\\x%02X", c);
897 else if (c < 0x10000)
898 logprintf("\\u%04X", c);
899 else
900 logprintf("\\U%08X", c);
901 }
902 logprintf("\"\n");
903 }
904
905 #ifndef HAVE_WCSCMP
906 static int
wcscmp(const wchar_t * s1,const wchar_t * s2)907 wcscmp(const wchar_t *s1, const wchar_t *s2)
908 {
909
910 while (*s1 == *s2++) {
911 if (*s1++ == L'\0')
912 return 0;
913 }
914 if (*s1 > *--s2)
915 return 1;
916 else
917 return -1;
918 }
919 #endif
920
921 /* Verify that two wide strings are equal, dump them if not. */
922 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)923 assertion_equal_wstring(const char *file, int line,
924 const wchar_t *v1, const char *e1,
925 const wchar_t *v2, const char *e2,
926 void *extra)
927 {
928 assertion_count(file, line);
929 if (v1 == v2)
930 return (1);
931 if (v1 != NULL && v2 != NULL && wcscmp(v1, v2) == 0)
932 return (1);
933 failure_start(file, line, "%s != %s", e1, e2);
934 wcsdump(e1, v1);
935 wcsdump(e2, v2);
936 failure_finish(extra);
937 return (0);
938 }
939
940 /*
941 * Pretty standard hexdump routine. As a bonus, if ref != NULL, then
942 * any bytes in p that differ from ref will be highlighted with '_'
943 * before and after the hex value.
944 */
945 static void
hexdump(const char * p,const char * ref,size_t l,size_t offset)946 hexdump(const char *p, const char *ref, size_t l, size_t offset)
947 {
948 size_t i, j;
949 char sep;
950
951 if (p == NULL) {
952 logprintf("(null)\n");
953 return;
954 }
955 for(i=0; i < l; i+=16) {
956 logprintf("%04x", (unsigned)(i + offset));
957 sep = ' ';
958 for (j = 0; j < 16 && i + j < l; j++) {
959 if (ref != NULL && p[i + j] != ref[i + j])
960 sep = '_';
961 logprintf("%c%02x", sep, 0xff & (unsigned int)p[i+j]);
962 if (ref != NULL && p[i + j] == ref[i + j])
963 sep = ' ';
964 }
965 for (; j < 16; j++) {
966 logprintf("%c ", sep);
967 sep = ' ';
968 }
969 logprintf("%c", sep);
970 for (j=0; j < 16 && i + j < l; j++) {
971 int c = p[i + j];
972 if (c >= ' ' && c <= 126)
973 logprintf("%c", c);
974 else
975 logprintf(".");
976 }
977 logprintf("\n");
978 }
979 }
980
981 /* Verify that two blocks of memory are the same, display the first
982 * block of differences if they're not. */
983 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)984 assertion_equal_mem(const char *file, int line,
985 const void *_v1, const char *e1,
986 const void *_v2, const char *e2,
987 size_t l, const char *ld, void *extra)
988 {
989 const char *v1 = (const char *)_v1;
990 const char *v2 = (const char *)_v2;
991 size_t offset;
992
993 assertion_count(file, line);
994 if (v1 == v2 || (v1 != NULL && v2 != NULL && memcmp(v1, v2, l) == 0))
995 return (1);
996 if (v1 == NULL || v2 == NULL)
997 return (0);
998
999 failure_start(file, line, "%s != %s", e1, e2);
1000 logprintf(" size %s = %d\n", ld, (int)l);
1001 /* Dump 48 bytes (3 lines) so that the first difference is
1002 * in the second line. */
1003 offset = 0;
1004 while (l > 64 && memcmp(v1, v2, 32) == 0) {
1005 /* Two lines agree, so step forward one line. */
1006 v1 += 16;
1007 v2 += 16;
1008 l -= 16;
1009 offset += 16;
1010 }
1011 logprintf(" Dump of %s\n", e1);
1012 hexdump(v1, v2, l < 128 ? l : 128, offset);
1013 logprintf(" Dump of %s\n", e2);
1014 hexdump(v2, v1, l < 128 ? l : 128, offset);
1015 logprintf("\n");
1016 failure_finish(extra);
1017 return (0);
1018 }
1019
1020 /* Verify that a block of memory is filled with the specified byte. */
1021 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)1022 assertion_memory_filled_with(const char *file, int line,
1023 const void *_v1, const char *vd,
1024 size_t l, const char *ld,
1025 char b, const char *bd, void *extra)
1026 {
1027 const char *v1 = (const char *)_v1;
1028 size_t c = 0;
1029 size_t i;
1030 (void)ld; /* UNUSED */
1031
1032 assertion_count(file, line);
1033
1034 for (i = 0; i < l; ++i) {
1035 if (v1[i] == b) {
1036 ++c;
1037 }
1038 }
1039 if (c == l)
1040 return (1);
1041
1042 failure_start(file, line, "%s (size %d) not filled with %s", vd, (int)l, bd);
1043 logprintf(" Only %d bytes were correct\n", (int)c);
1044 failure_finish(extra);
1045 return (0);
1046 }
1047
1048 /* Verify that the named file exists and is empty. */
1049 int
assertion_empty_file(const char * filename,int line,const char * f1)1050 assertion_empty_file(const char *filename, int line, const char *f1)
1051 {
1052 char buff[1024];
1053 struct stat st;
1054 ssize_t s;
1055 FILE *f;
1056
1057 assertion_count(filename, line);
1058
1059 if (stat(f1, &st) != 0) {
1060 failure_start(filename, line, "Stat failed: %s", f1);
1061 failure_finish(NULL);
1062 return (0);
1063 }
1064 if (st.st_size == 0)
1065 return (1);
1066
1067 failure_start(filename, line, "File should be empty: %s", f1);
1068 logprintf(" File size: %d\n", (int)st.st_size);
1069 logprintf(" Contents:\n");
1070 f = fopen(f1, "rb");
1071 if (f == NULL) {
1072 logprintf(" Unable to open %s\n", f1);
1073 } else {
1074 s = ((off_t)sizeof(buff) < st.st_size) ?
1075 (ssize_t)sizeof(buff) : (ssize_t)st.st_size;
1076 s = fread(buff, 1, s, f);
1077 hexdump(buff, NULL, s, 0);
1078 fclose(f);
1079 }
1080 failure_finish(NULL);
1081 return (0);
1082 }
1083
1084 /* Verify that the named file exists and is not empty. */
1085 int
assertion_non_empty_file(const char * filename,int line,const char * f1)1086 assertion_non_empty_file(const char *filename, int line, const char *f1)
1087 {
1088 struct stat st;
1089
1090 assertion_count(filename, line);
1091
1092 if (stat(f1, &st) != 0) {
1093 failure_start(filename, line, "Stat failed: %s", f1);
1094 failure_finish(NULL);
1095 return (0);
1096 }
1097 if (st.st_size == 0) {
1098 failure_start(filename, line, "File empty: %s", f1);
1099 failure_finish(NULL);
1100 return (0);
1101 }
1102 return (1);
1103 }
1104
1105 /* Verify that two files have the same contents. */
1106 /* TODO: hexdump the first bytes that actually differ. */
1107 int
assertion_equal_file(const char * filename,int line,const char * fn1,const char * fn2)1108 assertion_equal_file(const char *filename, int line, const char *fn1, const char *fn2)
1109 {
1110 char buff1[1024];
1111 char buff2[1024];
1112 FILE *f1, *f2;
1113 int n1, n2;
1114
1115 assertion_count(filename, line);
1116
1117 f1 = fopen(fn1, "rb");
1118 f2 = fopen(fn2, "rb");
1119 if (f1 == NULL || f2 == NULL) {
1120 if (f1) fclose(f1);
1121 if (f2) fclose(f2);
1122 return (0);
1123 }
1124 for (;;) {
1125 n1 = (int)fread(buff1, 1, sizeof(buff1), f1);
1126 n2 = (int)fread(buff2, 1, sizeof(buff2), f2);
1127 if (n1 != n2)
1128 break;
1129 if (n1 == 0 && n2 == 0) {
1130 fclose(f1);
1131 fclose(f2);
1132 return (1);
1133 }
1134 if (memcmp(buff1, buff2, n1) != 0)
1135 break;
1136 }
1137 fclose(f1);
1138 fclose(f2);
1139 failure_start(filename, line, "Files not identical");
1140 logprintf(" file1=\"%s\"\n", fn1);
1141 logprintf(" file2=\"%s\"\n", fn2);
1142 failure_finish(NULL);
1143 return (0);
1144 }
1145
1146 /* Verify that the named file does exist. */
1147 int
assertion_file_exists(const char * filename,int line,const char * f)1148 assertion_file_exists(const char *filename, int line, const char *f)
1149 {
1150 assertion_count(filename, line);
1151
1152 #if defined(_WIN32) && !defined(__CYGWIN__)
1153 if (!_access(f, 0))
1154 return (1);
1155 #else
1156 if (!access(f, F_OK))
1157 return (1);
1158 #endif
1159 failure_start(filename, line, "File should exist: %s", f);
1160 failure_finish(NULL);
1161 return (0);
1162 }
1163
1164 /* Verify that the named file doesn't exist. */
1165 int
assertion_file_not_exists(const char * filename,int line,const char * f)1166 assertion_file_not_exists(const char *filename, int line, const char *f)
1167 {
1168 assertion_count(filename, line);
1169
1170 #if defined(_WIN32) && !defined(__CYGWIN__)
1171 if (_access(f, 0))
1172 return (1);
1173 #else
1174 if (access(f, F_OK))
1175 return (1);
1176 #endif
1177 failure_start(filename, line, "File should not exist: %s", f);
1178 failure_finish(NULL);
1179 return (0);
1180 }
1181
1182 /* Compare the contents of a file to a block of memory. */
1183 int
assertion_file_contents(const char * filename,int line,const void * buff,int s,const char * fn)1184 assertion_file_contents(const char *filename, int line, const void *buff, int s, const char *fn)
1185 {
1186 char *contents;
1187 FILE *f;
1188 int n;
1189
1190 assertion_count(filename, line);
1191
1192 f = fopen(fn, "rb");
1193 if (f == NULL) {
1194 failure_start(filename, line,
1195 "File should exist: %s", fn);
1196 failure_finish(NULL);
1197 return (0);
1198 }
1199 contents = malloc(s * 2);
1200 n = (int)fread(contents, 1, s * 2, f);
1201 fclose(f);
1202 if (n == s && memcmp(buff, contents, s) == 0) {
1203 free(contents);
1204 return (1);
1205 }
1206 failure_start(filename, line, "File contents don't match");
1207 logprintf(" file=\"%s\"\n", fn);
1208 if (n > 0)
1209 hexdump(contents, buff, n > 512 ? 512 : n, 0);
1210 else {
1211 logprintf(" File empty, contents should be:\n");
1212 hexdump(buff, NULL, s > 512 ? 512 : s, 0);
1213 }
1214 failure_finish(NULL);
1215 free(contents);
1216 return (0);
1217 }
1218
1219 /* Check the contents of a text file, being tolerant of line endings. */
1220 int
assertion_text_file_contents(const char * filename,int line,const char * buff,const char * fn)1221 assertion_text_file_contents(const char *filename, int line, const char *buff, const char *fn)
1222 {
1223 char *contents;
1224 const char *btxt, *ftxt;
1225 FILE *f;
1226 int n, s;
1227
1228 assertion_count(filename, line);
1229 f = fopen(fn, "r");
1230 if (f == NULL) {
1231 failure_start(filename, line,
1232 "File doesn't exist: %s", fn);
1233 failure_finish(NULL);
1234 return (0);
1235 }
1236 s = (int)strlen(buff);
1237 contents = malloc(s * 2 + 128);
1238 n = (int)fread(contents, 1, s * 2 + 128 - 1, f);
1239 if (n >= 0)
1240 contents[n] = '\0';
1241 fclose(f);
1242 /* Compare texts. */
1243 btxt = buff;
1244 ftxt = (const char *)contents;
1245 while (*btxt != '\0' && *ftxt != '\0') {
1246 if (*btxt == *ftxt) {
1247 ++btxt;
1248 ++ftxt;
1249 continue;
1250 }
1251 if (btxt[0] == '\n' && ftxt[0] == '\r' && ftxt[1] == '\n') {
1252 /* Pass over different new line characters. */
1253 ++btxt;
1254 ftxt += 2;
1255 continue;
1256 }
1257 break;
1258 }
1259 if (*btxt == '\0' && *ftxt == '\0') {
1260 free(contents);
1261 return (1);
1262 }
1263 failure_start(filename, line, "Contents don't match");
1264 logprintf(" file=\"%s\"\n", fn);
1265 if (n > 0) {
1266 hexdump(contents, buff, n, 0);
1267 logprintf(" expected\n");
1268 hexdump(buff, contents, s, 0);
1269 } else {
1270 logprintf(" File empty, contents should be:\n");
1271 hexdump(buff, NULL, s, 0);
1272 }
1273 failure_finish(NULL);
1274 free(contents);
1275 return (0);
1276 }
1277
1278 /* Verify that a text file contains the specified lines, regardless of order */
1279 /* This could be more efficient if we sorted both sets of lines, etc, but
1280 * since this is used only for testing and only ever deals with a dozen or so
1281 * lines at a time, this relatively crude approach is just fine. */
1282 int
assertion_file_contains_lines_any_order(const char * file,int line,const char * pathname,const char * lines[])1283 assertion_file_contains_lines_any_order(const char *file, int line,
1284 const char *pathname, const char *lines[])
1285 {
1286 char *buff;
1287 size_t buff_size;
1288 size_t expected_count, actual_count, i, j;
1289 char **expected = NULL;
1290 char *p, **actual = NULL;
1291 char c;
1292 int expected_failure = 0, actual_failure = 0;
1293
1294 assertion_count(file, line);
1295
1296 buff = slurpfile(&buff_size, "%s", pathname);
1297 if (buff == NULL) {
1298 failure_start(pathname, line, "Can't read file: %s", pathname);
1299 failure_finish(NULL);
1300 return (0);
1301 }
1302
1303 /* Make a copy of the provided lines and count up the expected
1304 * file size. */
1305 for (i = 0; lines[i] != NULL; ++i) {
1306 }
1307 expected_count = i;
1308 if (expected_count) {
1309 expected = calloc(expected_count, sizeof(*expected));
1310 if (expected == NULL) {
1311 failure_start(pathname, line, "Can't allocate memory");
1312 failure_finish(NULL);
1313 goto cleanup;
1314 }
1315 for (i = 0; lines[i] != NULL; ++i) {
1316 expected[i] = strdup(lines[i]);
1317 if (expected[i] == NULL) {
1318 failure_start(pathname, line, "Can't allocate memory");
1319 failure_finish(NULL);
1320 goto cleanup;
1321 }
1322 }
1323 }
1324
1325 /* Break the file into lines */
1326 actual_count = 0;
1327 for (c = '\0', p = buff; p < buff + buff_size; ++p) {
1328 if (*p == '\x0d' || *p == '\x0a')
1329 *p = '\0';
1330 if (c == '\0' && *p != '\0')
1331 ++actual_count;
1332 c = *p;
1333 }
1334 if (actual_count) {
1335 actual = calloc(actual_count, sizeof(char *));
1336 if (actual == NULL) {
1337 failure_start(pathname, line, "Can't allocate memory");
1338 failure_finish(NULL);
1339 goto cleanup;
1340 }
1341 for (j = 0, p = buff; p < buff + buff_size;
1342 p += 1 + strlen(p)) {
1343 if (*p != '\0') {
1344 actual[j] = p;
1345 ++j;
1346 }
1347 }
1348 }
1349
1350 /* Erase matching lines from both lists */
1351 for (i = 0; i < expected_count; ++i) {
1352 for (j = 0; j < actual_count; ++j) {
1353 if (actual[j] == NULL)
1354 continue;
1355 if (strcmp(expected[i], actual[j]) == 0) {
1356 free(expected[i]);
1357 expected[i] = NULL;
1358 actual[j] = NULL;
1359 break;
1360 }
1361 }
1362 }
1363
1364 /* If there's anything left, it's a failure */
1365 for (i = 0; i < expected_count; ++i) {
1366 if (expected[i] != NULL)
1367 ++expected_failure;
1368 }
1369 for (j = 0; j < actual_count; ++j) {
1370 if (actual[j] != NULL)
1371 ++actual_failure;
1372 }
1373 if (expected_failure == 0 && actual_failure == 0) {
1374 free(actual);
1375 free(expected);
1376 free(buff);
1377 return (1);
1378 }
1379 failure_start(file, line, "File doesn't match: %s", pathname);
1380 for (i = 0; i < expected_count; ++i) {
1381 if (expected[i] != NULL) {
1382 logprintf(" Expected but not present: %s\n", expected[i]);
1383 free(expected[i]);
1384 expected[i] = NULL;
1385 }
1386 }
1387 for (j = 0; j < actual_count; ++j) {
1388 if (actual[j] != NULL)
1389 logprintf(" Present but not expected: %s\n", actual[j]);
1390 }
1391 failure_finish(NULL);
1392 cleanup:
1393 free(actual);
1394 if (expected != NULL) {
1395 for (i = 0; i < expected_count; ++i)
1396 if (expected[i] != NULL)
1397 free(expected[i]);
1398 free(expected);
1399 }
1400 free(buff);
1401 return (0);
1402 }
1403
1404 /* Verify that a text file does not contains the specified strings */
1405 int
assertion_file_contains_no_invalid_strings(const char * file,int line,const char * pathname,const char * strings[])1406 assertion_file_contains_no_invalid_strings(const char *file, int line,
1407 const char *pathname, const char *strings[])
1408 {
1409 char *buff;
1410 int i;
1411
1412 buff = slurpfile(NULL, "%s", pathname);
1413 if (buff == NULL) {
1414 failure_start(file, line, "Can't read file: %s", pathname);
1415 failure_finish(NULL);
1416 return (0);
1417 }
1418
1419 for (i = 0; strings[i] != NULL; ++i) {
1420 if (strstr(buff, strings[i]) != NULL) {
1421 failure_start(file, line, "Invalid string in %s: %s", pathname,
1422 strings[i]);
1423 failure_finish(NULL);
1424 free(buff);
1425 return(0);
1426 }
1427 }
1428
1429 free(buff);
1430 return (0);
1431 }
1432
1433 /* Test that two paths point to the same file. */
1434 /* As a side-effect, asserts that both files exist. */
1435 static int
is_hardlink(const char * file,int line,const char * path1,const char * path2)1436 is_hardlink(const char *file, int line,
1437 const char *path1, const char *path2)
1438 {
1439 #if defined(_WIN32) && !defined(__CYGWIN__)
1440 BY_HANDLE_FILE_INFORMATION bhfi1, bhfi2;
1441 int r;
1442
1443 assertion_count(file, line);
1444 r = my_GetFileInformationByName(path1, &bhfi1);
1445 if (r == 0) {
1446 failure_start(file, line, "File %s can't be inspected?", path1);
1447 failure_finish(NULL);
1448 return (0);
1449 }
1450 r = my_GetFileInformationByName(path2, &bhfi2);
1451 if (r == 0) {
1452 failure_start(file, line, "File %s can't be inspected?", path2);
1453 failure_finish(NULL);
1454 return (0);
1455 }
1456 return (bhfi1.dwVolumeSerialNumber == bhfi2.dwVolumeSerialNumber
1457 && bhfi1.nFileIndexHigh == bhfi2.nFileIndexHigh
1458 && bhfi1.nFileIndexLow == bhfi2.nFileIndexLow);
1459 #else
1460 struct stat st1, st2;
1461 int r;
1462
1463 assertion_count(file, line);
1464 r = lstat(path1, &st1);
1465 if (r != 0) {
1466 failure_start(file, line, "File should exist: %s", path1);
1467 failure_finish(NULL);
1468 return (0);
1469 }
1470 r = lstat(path2, &st2);
1471 if (r != 0) {
1472 failure_start(file, line, "File should exist: %s", path2);
1473 failure_finish(NULL);
1474 return (0);
1475 }
1476 return (st1.st_ino == st2.st_ino && st1.st_dev == st2.st_dev);
1477 #endif
1478 }
1479
1480 int
assertion_is_hardlink(const char * file,int line,const char * path1,const char * path2)1481 assertion_is_hardlink(const char *file, int line,
1482 const char *path1, const char *path2)
1483 {
1484 if (is_hardlink(file, line, path1, path2))
1485 return (1);
1486 failure_start(file, line,
1487 "Files %s and %s are not hardlinked", path1, path2);
1488 failure_finish(NULL);
1489 return (0);
1490 }
1491
1492 int
assertion_is_not_hardlink(const char * file,int line,const char * path1,const char * path2)1493 assertion_is_not_hardlink(const char *file, int line,
1494 const char *path1, const char *path2)
1495 {
1496 if (!is_hardlink(file, line, path1, path2))
1497 return (1);
1498 failure_start(file, line,
1499 "Files %s and %s should not be hardlinked", path1, path2);
1500 failure_finish(NULL);
1501 return (0);
1502 }
1503
1504 /* Verify a/b/mtime of 'pathname'. */
1505 /* If 'recent', verify that it's within last 10 seconds. */
1506 static int
assertion_file_time(const char * file,int line,const char * pathname,long t,long nsec,char type,int recent)1507 assertion_file_time(const char *file, int line,
1508 const char *pathname, long t, long nsec, char type, int recent)
1509 {
1510 long long filet, filet_nsec;
1511 int r;
1512
1513 #if defined(_WIN32) && !defined(__CYGWIN__)
1514 #define EPOC_TIME (116444736000000000ULL)
1515 FILETIME fxtime, fbirthtime, fatime, fmtime;
1516 ULARGE_INTEGER wintm;
1517 HANDLE h;
1518 fxtime.dwLowDateTime = 0;
1519 fxtime.dwHighDateTime = 0;
1520
1521 assertion_count(file, line);
1522 /* Note: FILE_FLAG_BACKUP_SEMANTICS applies to open
1523 * a directory file. If not, CreateFile() will fail when
1524 * the pathname is a directory. */
1525 h = CreateFileA(pathname, FILE_READ_ATTRIBUTES, 0, NULL,
1526 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
1527 FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1528 if (h == INVALID_HANDLE_VALUE) {
1529 failure_start(file, line, "Can't access %s\n", pathname);
1530 failure_finish(NULL);
1531 return (0);
1532 }
1533 r = GetFileTime(h, &fbirthtime, &fatime, &fmtime);
1534 switch (type) {
1535 case 'a': fxtime = fatime; break;
1536 case 'b': fxtime = fbirthtime; break;
1537 case 'm': fxtime = fmtime; break;
1538 }
1539 CloseHandle(h);
1540 if (r == 0) {
1541 failure_start(file, line, "Can't GetFileTime %s\n", pathname);
1542 failure_finish(NULL);
1543 return (0);
1544 }
1545 wintm.LowPart = fxtime.dwLowDateTime;
1546 wintm.HighPart = fxtime.dwHighDateTime;
1547 filet = (wintm.QuadPart - EPOC_TIME) / 10000000;
1548 filet_nsec = ((wintm.QuadPart - EPOC_TIME) % 10000000) * 100;
1549 nsec = (nsec / 100) * 100; /* Round the request */
1550 #else
1551 struct stat st;
1552
1553 assertion_count(file, line);
1554 r = lstat(pathname, &st);
1555 if (r != 0) {
1556 failure_start(file, line, "Can't stat %s\n", pathname);
1557 failure_finish(NULL);
1558 return (0);
1559 }
1560 switch (type) {
1561 case 'a': filet = st.st_atime; break;
1562 case 'm': filet = st.st_mtime; break;
1563 case 'b': filet = 0; break;
1564 default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);
1565 exit(1);
1566 }
1567 #if defined(__FreeBSD__)
1568 switch (type) {
1569 case 'a': filet_nsec = st.st_atimespec.tv_nsec; break;
1570 case 'b': filet = st.st_birthtime;
1571 /* FreeBSD filesystems that don't support birthtime
1572 * (e.g., UFS1) always return -1 here. */
1573 if (filet == -1) {
1574 return (1);
1575 }
1576 filet_nsec = st.st_birthtimespec.tv_nsec; break;
1577 case 'm': filet_nsec = st.st_mtimespec.tv_nsec; break;
1578 default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);
1579 exit(1);
1580 }
1581 /* FreeBSD generally only stores to microsecond res, so round. */
1582 filet_nsec = (filet_nsec / 1000) * 1000;
1583 nsec = (nsec / 1000) * 1000;
1584 #else
1585 filet_nsec = nsec = 0; /* Generic POSIX only has whole seconds. */
1586 if (type == 'b') return (1); /* Generic POSIX doesn't have birthtime */
1587 #if defined(__HAIKU__)
1588 if (type == 'a') return (1); /* Haiku doesn't have atime. */
1589 #endif
1590 #endif
1591 #endif
1592 if (recent) {
1593 /* Check that requested time is up-to-date. */
1594 time_t now = time(NULL);
1595 if (filet < now - 10 || filet > now + 1) {
1596 failure_start(file, line,
1597 "File %s has %ctime %lld, %lld seconds ago\n",
1598 pathname, type, filet, now - filet);
1599 failure_finish(NULL);
1600 return (0);
1601 }
1602 } else if (filet != t || filet_nsec != nsec) {
1603 failure_start(file, line,
1604 "File %s has %ctime %lld.%09lld, expected %ld.%09ld",
1605 pathname, type, filet, filet_nsec, t, nsec);
1606 failure_finish(NULL);
1607 return (0);
1608 }
1609 return (1);
1610 }
1611
1612 /* Verify atime of 'pathname'. */
1613 int
assertion_file_atime(const char * file,int line,const char * pathname,long t,long nsec)1614 assertion_file_atime(const char *file, int line,
1615 const char *pathname, long t, long nsec)
1616 {
1617 return assertion_file_time(file, line, pathname, t, nsec, 'a', 0);
1618 }
1619
1620 /* Verify atime of 'pathname' is up-to-date. */
1621 int
assertion_file_atime_recent(const char * file,int line,const char * pathname)1622 assertion_file_atime_recent(const char *file, int line, const char *pathname)
1623 {
1624 return assertion_file_time(file, line, pathname, 0, 0, 'a', 1);
1625 }
1626
1627 /* Verify birthtime of 'pathname'. */
1628 int
assertion_file_birthtime(const char * file,int line,const char * pathname,long t,long nsec)1629 assertion_file_birthtime(const char *file, int line,
1630 const char *pathname, long t, long nsec)
1631 {
1632 return assertion_file_time(file, line, pathname, t, nsec, 'b', 0);
1633 }
1634
1635 /* Verify birthtime of 'pathname' is up-to-date. */
1636 int
assertion_file_birthtime_recent(const char * file,int line,const char * pathname)1637 assertion_file_birthtime_recent(const char *file, int line,
1638 const char *pathname)
1639 {
1640 return assertion_file_time(file, line, pathname, 0, 0, 'b', 1);
1641 }
1642
1643 /* Verify mode of 'pathname'. */
1644 int
assertion_file_mode(const char * file,int line,const char * pathname,int expected_mode)1645 assertion_file_mode(const char *file, int line, const char *pathname, int expected_mode)
1646 {
1647 int mode;
1648 int r;
1649
1650 assertion_count(file, line);
1651 #if defined(_WIN32) && !defined(__CYGWIN__)
1652 failure_start(file, line, "assertFileMode not yet implemented for Windows");
1653 (void)mode; /* UNUSED */
1654 (void)r; /* UNUSED */
1655 (void)pathname; /* UNUSED */
1656 (void)expected_mode; /* UNUSED */
1657 #else
1658 {
1659 struct stat st;
1660 r = lstat(pathname, &st);
1661 mode = (int)(st.st_mode & 0777);
1662 }
1663 if (r == 0 && mode == expected_mode)
1664 return (1);
1665 failure_start(file, line, "File %s has mode %o, expected %o",
1666 pathname, (unsigned int)mode, (unsigned int)expected_mode);
1667 #endif
1668 failure_finish(NULL);
1669 return (0);
1670 }
1671
1672 /* Verify mtime of 'pathname'. */
1673 int
assertion_file_mtime(const char * file,int line,const char * pathname,long t,long nsec)1674 assertion_file_mtime(const char *file, int line,
1675 const char *pathname, long t, long nsec)
1676 {
1677 return assertion_file_time(file, line, pathname, t, nsec, 'm', 0);
1678 }
1679
1680 /* Verify mtime of 'pathname' is up-to-date. */
1681 int
assertion_file_mtime_recent(const char * file,int line,const char * pathname)1682 assertion_file_mtime_recent(const char *file, int line, const char *pathname)
1683 {
1684 return assertion_file_time(file, line, pathname, 0, 0, 'm', 1);
1685 }
1686
1687 /* Verify number of links to 'pathname'. */
1688 int
assertion_file_nlinks(const char * file,int line,const char * pathname,int nlinks)1689 assertion_file_nlinks(const char *file, int line,
1690 const char *pathname, int nlinks)
1691 {
1692 #if defined(_WIN32) && !defined(__CYGWIN__)
1693 BY_HANDLE_FILE_INFORMATION bhfi;
1694 int r;
1695
1696 assertion_count(file, line);
1697 r = my_GetFileInformationByName(pathname, &bhfi);
1698 if (r != 0 && bhfi.nNumberOfLinks == (DWORD)nlinks)
1699 return (1);
1700 failure_start(file, line, "File %s has %jd links, expected %d",
1701 pathname, (intmax_t)bhfi.nNumberOfLinks, nlinks);
1702 failure_finish(NULL);
1703 return (0);
1704 #else
1705 struct stat st;
1706 int r;
1707
1708 assertion_count(file, line);
1709 r = lstat(pathname, &st);
1710 if (r == 0 && (int)st.st_nlink == nlinks)
1711 return (1);
1712 failure_start(file, line, "File %s has %jd links, expected %d",
1713 pathname, (intmax_t)st.st_nlink, nlinks);
1714 failure_finish(NULL);
1715 return (0);
1716 #endif
1717 }
1718
1719 /* Verify size of 'pathname'. */
1720 int
assertion_file_size(const char * file,int line,const char * pathname,long size)1721 assertion_file_size(const char *file, int line, const char *pathname, long size)
1722 {
1723 int64_t filesize;
1724 int r;
1725
1726 assertion_count(file, line);
1727 #if defined(_WIN32) && !defined(__CYGWIN__)
1728 {
1729 BY_HANDLE_FILE_INFORMATION bhfi;
1730 r = !my_GetFileInformationByName(pathname, &bhfi);
1731 filesize = ((int64_t)bhfi.nFileSizeHigh << 32) + bhfi.nFileSizeLow;
1732 }
1733 #else
1734 {
1735 struct stat st;
1736 r = lstat(pathname, &st);
1737 filesize = st.st_size;
1738 }
1739 #endif
1740 if (r == 0 && filesize == size)
1741 return (1);
1742 failure_start(file, line, "File %s has size %ld, expected %ld",
1743 pathname, (long)filesize, (long)size);
1744 failure_finish(NULL);
1745 return (0);
1746 }
1747
1748 /* Assert that 'pathname' is a dir. If mode >= 0, verify that too. */
1749 int
assertion_is_dir(const char * file,int line,const char * pathname,int mode)1750 assertion_is_dir(const char *file, int line, const char *pathname, int mode)
1751 {
1752 int r;
1753
1754 assertion_count(file, line);
1755
1756 #if defined(_WIN32) && !defined(__CYGWIN__)
1757 BY_HANDLE_FILE_INFORMATION st;
1758 (void)mode; /* UNUSED */
1759 r = my_GetFileInformationByName(pathname, &st);
1760 if (r == 0) {
1761 failure_start(file, line, "Dir should exist: %s", pathname);
1762 failure_finish(NULL);
1763 return (0);
1764 }
1765 if ((st.dwFileAttributes &
1766 (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) !=
1767 FILE_ATTRIBUTE_DIRECTORY) {
1768 failure_start(file, line, "%s is not a dir", pathname);
1769 failure_finish(NULL);
1770 return (0);
1771 }
1772 #else
1773 struct stat st;
1774 r = lstat(pathname, &st);
1775 if (r != 0) {
1776 failure_start(file, line, "Dir should exist: %s", pathname);
1777 failure_finish(NULL);
1778 return (0);
1779 }
1780 if (!S_ISDIR(st.st_mode)) {
1781 failure_start(file, line, "%s is not a dir", pathname);
1782 failure_finish(NULL);
1783 return (0);
1784 }
1785 /* Windows doesn't handle permissions the same way as POSIX,
1786 * so just ignore the mode tests. */
1787 /* TODO: Can we do better here? */
1788 if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {
1789 failure_start(file, line, "Dir %s has wrong mode", pathname);
1790 logprintf(" Expected: 0%3o\n", (unsigned int)mode);
1791 logprintf(" Found: 0%3o\n", (unsigned int)st.st_mode & 07777);
1792 failure_finish(NULL);
1793 return (0);
1794 }
1795 #endif
1796 return (1);
1797 }
1798
1799 /* Verify that 'pathname' is a regular file. If 'mode' is >= 0,
1800 * verify that too. */
1801 int
assertion_is_reg(const char * file,int line,const char * pathname,int mode)1802 assertion_is_reg(const char *file, int line, const char *pathname, int mode)
1803 {
1804 int r;
1805
1806 assertion_count(file, line);
1807
1808 #if defined(_WIN32) && !defined(__CYGWIN__)
1809 BY_HANDLE_FILE_INFORMATION st;
1810 (void)mode; /* UNUSED */
1811 r = my_GetFileInformationByName(pathname, &st);
1812 if (r == 0) {
1813 failure_start(file, line, "File should exist: %s", pathname);
1814 failure_finish(NULL);
1815 return (0);
1816 }
1817 if ((st.dwFileAttributes &
1818 (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) !=
1819 0) {
1820 failure_start(file, line, "%s is not a regular file", pathname);
1821 failure_finish(NULL);
1822 return (0);
1823 }
1824 #else
1825 struct stat st;
1826 r = lstat(pathname, &st);
1827 if (r != 0 || !S_ISREG(st.st_mode)) {
1828 failure_start(file, line, "File should exist: %s", pathname);
1829 failure_finish(NULL);
1830 return (0);
1831 }
1832
1833 /* Windows doesn't handle permissions the same way as POSIX,
1834 * so just ignore the mode tests. */
1835 /* TODO: Can we do better here? */
1836 if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {
1837 failure_start(file, line, "File %s has wrong mode", pathname);
1838 logprintf(" Expected: 0%3o\n", (unsigned int)mode);
1839 logprintf(" Found: 0%3o\n", (unsigned int)st.st_mode & 07777);
1840 failure_finish(NULL);
1841 return (0);
1842 }
1843 #endif
1844 return (1);
1845 }
1846
1847 /*
1848 * Check whether 'pathname' is a symbolic link. If 'contents' is
1849 * non-NULL, verify that the symlink has those contents.
1850 *
1851 * On platforms with directory symlinks, set isdir to 0 to test for a file
1852 * symlink and to 1 to test for a directory symlink. On other platforms
1853 * the variable is ignored.
1854 */
1855 static int
is_symlink(const char * file,int line,const char * pathname,const char * contents,int isdir)1856 is_symlink(const char *file, int line,
1857 const char *pathname, const char *contents, int isdir)
1858 {
1859 #if defined(_WIN32) && !defined(__CYGWIN__)
1860 HANDLE h;
1861 DWORD inbytes;
1862 REPARSE_DATA_BUFFER *buf;
1863 BY_HANDLE_FILE_INFORMATION st;
1864 size_t len, len2;
1865 wchar_t *linknamew, *contentsw;
1866 const char *p;
1867 char *s, *pn;
1868 int ret = 0;
1869 BYTE *indata;
1870 const DWORD flag = FILE_FLAG_BACKUP_SEMANTICS |
1871 FILE_FLAG_OPEN_REPARSE_POINT;
1872
1873 /* Replace slashes with backslashes in pathname */
1874 pn = malloc(strlen(pathname) + 1);
1875 if (pn == NULL) {
1876 failure_start(file, line, "Can't allocate memory");
1877 failure_finish(NULL);
1878 return (0);
1879 }
1880 for (p = pathname, s = pn; *p != '\0'; p++, s++) {
1881 if (*p == '/')
1882 *s = '\\';
1883 else
1884 *s = *p;
1885 }
1886 *s = '\0';
1887
1888 h = CreateFileA(pn, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1889 flag, NULL);
1890 free(pn);
1891 if (h == INVALID_HANDLE_VALUE) {
1892 failure_start(file, line, "Can't access %s\n", pathname);
1893 failure_finish(NULL);
1894 return (0);
1895 }
1896 ret = GetFileInformationByHandle(h, &st);
1897 if (ret == 0) {
1898 failure_start(file, line,
1899 "Can't stat: %s", pathname);
1900 failure_finish(NULL);
1901 } else if ((st.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) {
1902 failure_start(file, line,
1903 "Not a symlink: %s", pathname);
1904 failure_finish(NULL);
1905 ret = 0;
1906 }
1907 if (isdir && ((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) {
1908 failure_start(file, line,
1909 "Not a directory symlink: %s", pathname);
1910 failure_finish(NULL);
1911 ret = 0;
1912 }
1913 if (!isdir &&
1914 ((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
1915 failure_start(file, line,
1916 "Not a file symlink: %s", pathname);
1917 failure_finish(NULL);
1918 ret = 0;
1919 }
1920 if (ret == 0) {
1921 CloseHandle(h);
1922 return (0);
1923 }
1924
1925 indata = malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
1926 ret = DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, NULL, 0, indata,
1927 1024, &inbytes, NULL);
1928 CloseHandle(h);
1929 if (ret == 0) {
1930 free(indata);
1931 failure_start(file, line,
1932 "Could not retrieve symlink target: %s", pathname);
1933 failure_finish(NULL);
1934 return (0);
1935 }
1936
1937 buf = (REPARSE_DATA_BUFFER *) indata;
1938 if (buf->ReparseTag != IO_REPARSE_TAG_SYMLINK) {
1939 free(indata);
1940 /* File is not a symbolic link */
1941 failure_start(file, line,
1942 "Not a symlink: %s", pathname);
1943 failure_finish(NULL);
1944 return (0);
1945 }
1946
1947 if (contents == NULL) {
1948 free(indata);
1949 return (1);
1950 }
1951
1952 len = buf->SymbolicLinkReparseBuffer.SubstituteNameLength;
1953
1954 linknamew = malloc(len + sizeof(wchar_t));
1955 if (linknamew == NULL) {
1956 free(indata);
1957 return (0);
1958 }
1959
1960 memcpy(linknamew, &((BYTE *)buf->SymbolicLinkReparseBuffer.PathBuffer)
1961 [buf->SymbolicLinkReparseBuffer.SubstituteNameOffset], len);
1962 free(indata);
1963
1964 linknamew[len / sizeof(wchar_t)] = L'\0';
1965
1966 contentsw = malloc(len + sizeof(wchar_t));
1967 if (contentsw == NULL) {
1968 free(linknamew);
1969 return (0);
1970 }
1971
1972 len2 = mbsrtowcs(contentsw, &contents, (len + sizeof(wchar_t)
1973 / sizeof(wchar_t)), NULL);
1974
1975 if (len2 > 0 && wcscmp(linknamew, contentsw) != 0)
1976 ret = 1;
1977
1978 free(linknamew);
1979 free(contentsw);
1980 return (ret);
1981 #else
1982 char buff[300];
1983 struct stat st;
1984 ssize_t linklen;
1985 int r;
1986
1987 (void)isdir; /* UNUSED */
1988 assertion_count(file, line);
1989 r = lstat(pathname, &st);
1990 if (r != 0) {
1991 failure_start(file, line,
1992 "Symlink should exist: %s", pathname);
1993 failure_finish(NULL);
1994 return (0);
1995 }
1996 if (!S_ISLNK(st.st_mode))
1997 return (0);
1998 if (contents == NULL)
1999 return (1);
2000 linklen = readlink(pathname, buff, sizeof(buff) - 1);
2001 if (linklen < 0) {
2002 failure_start(file, line, "Can't read symlink %s", pathname);
2003 failure_finish(NULL);
2004 return (0);
2005 }
2006 buff[linklen] = '\0';
2007 if (strcmp(buff, contents) != 0)
2008 return (0);
2009 return (1);
2010 #endif
2011 }
2012
2013 /* Assert that path is a symlink that (optionally) contains contents. */
2014 int
assertion_is_symlink(const char * file,int line,const char * path,const char * contents,int isdir)2015 assertion_is_symlink(const char *file, int line,
2016 const char *path, const char *contents, int isdir)
2017 {
2018 if (is_symlink(file, line, path, contents, isdir))
2019 return (1);
2020 if (contents)
2021 failure_start(file, line, "File %s is not a symlink to %s",
2022 path, contents);
2023 else
2024 failure_start(file, line, "File %s is not a symlink", path);
2025 failure_finish(NULL);
2026 return (0);
2027 }
2028
2029
2030 /* Create a directory and report any errors. */
2031 int
assertion_make_dir(const char * file,int line,const char * dirname,int mode)2032 assertion_make_dir(const char *file, int line, const char *dirname, int mode)
2033 {
2034 assertion_count(file, line);
2035 #if defined(_WIN32) && !defined(__CYGWIN__)
2036 (void)mode; /* UNUSED */
2037 if (0 == _mkdir(dirname))
2038 return (1);
2039 #else
2040 if (0 == mkdir(dirname, (mode_t)mode)) {
2041 if (0 == chmod(dirname, (mode_t)mode)) {
2042 assertion_file_mode(file, line, dirname, mode);
2043 return (1);
2044 }
2045 }
2046 #endif
2047 failure_start(file, line, "Could not create directory %s", dirname);
2048 failure_finish(NULL);
2049 return(0);
2050 }
2051
2052 /* Create a file with the specified contents and report any failures. */
2053 int
assertion_make_file(const char * file,int line,const char * path,int mode,int csize,const void * contents)2054 assertion_make_file(const char *file, int line,
2055 const char *path, int mode, int csize, const void *contents)
2056 {
2057 #if defined(_WIN32) && !defined(__CYGWIN__)
2058 /* TODO: Rework this to set file mode as well. */
2059 FILE *f;
2060 (void)mode; /* UNUSED */
2061 assertion_count(file, line);
2062 f = fopen(path, "wb");
2063 if (f == NULL) {
2064 failure_start(file, line, "Could not create file %s", path);
2065 failure_finish(NULL);
2066 return (0);
2067 }
2068 if (contents != NULL) {
2069 size_t wsize;
2070
2071 if (csize < 0)
2072 wsize = strlen(contents);
2073 else
2074 wsize = (size_t)csize;
2075 if (wsize != fwrite(contents, 1, wsize, f)) {
2076 fclose(f);
2077 failure_start(file, line,
2078 "Could not write file %s", path);
2079 failure_finish(NULL);
2080 return (0);
2081 }
2082 }
2083 fclose(f);
2084 return (1);
2085 #else
2086 int fd;
2087 assertion_count(file, line);
2088 fd = open(path, O_CREAT | O_WRONLY, mode >= 0 ? mode : 0644);
2089 if (fd < 0) {
2090 failure_start(file, line, "Could not create %s", path);
2091 failure_finish(NULL);
2092 return (0);
2093 }
2094 #ifdef HAVE_FCHMOD
2095 if (0 != fchmod(fd, (mode_t)mode))
2096 #else
2097 if (0 != chmod(path, (mode_t)mode))
2098 #endif
2099 {
2100 failure_start(file, line, "Could not chmod %s", path);
2101 failure_finish(NULL);
2102 close(fd);
2103 return (0);
2104 }
2105 if (contents != NULL) {
2106 ssize_t wsize;
2107
2108 if (csize < 0)
2109 wsize = (ssize_t)strlen(contents);
2110 else
2111 wsize = (ssize_t)csize;
2112 if (wsize != write(fd, contents, wsize)) {
2113 close(fd);
2114 failure_start(file, line,
2115 "Could not write to %s", path);
2116 failure_finish(NULL);
2117 close(fd);
2118 return (0);
2119 }
2120 }
2121 close(fd);
2122 assertion_file_mode(file, line, path, mode);
2123 return (1);
2124 #endif
2125 }
2126
2127 /* Create a hardlink and report any failures. */
2128 int
assertion_make_hardlink(const char * file,int line,const char * newpath,const char * linkto)2129 assertion_make_hardlink(const char *file, int line,
2130 const char *newpath, const char *linkto)
2131 {
2132 int succeeded;
2133
2134 assertion_count(file, line);
2135 #if defined(_WIN32) && !defined(__CYGWIN__)
2136 succeeded = my_CreateHardLinkA(newpath, linkto);
2137 #elif HAVE_LINK
2138 succeeded = !link(linkto, newpath);
2139 #else
2140 succeeded = 0;
2141 #endif
2142 if (succeeded)
2143 return (1);
2144 failure_start(file, line, "Could not create hardlink");
2145 logprintf(" New link: %s\n", newpath);
2146 logprintf(" Old name: %s\n", linkto);
2147 failure_finish(NULL);
2148 return(0);
2149 }
2150
2151 /*
2152 * Create a symlink and report any failures.
2153 *
2154 * Windows symlinks need to know if the target is a directory.
2155 */
2156 int
assertion_make_symlink(const char * file,int line,const char * newpath,const char * linkto,int targetIsDir)2157 assertion_make_symlink(const char *file, int line,
2158 const char *newpath, const char *linkto, int targetIsDir)
2159 {
2160 #if defined(_WIN32) && !defined(__CYGWIN__)
2161 assertion_count(file, line);
2162 if (my_CreateSymbolicLinkA(newpath, linkto, targetIsDir))
2163 return (1);
2164 #elif HAVE_SYMLINK
2165 (void)targetIsDir; /* UNUSED */
2166 assertion_count(file, line);
2167 if (0 == symlink(linkto, newpath))
2168 return (1);
2169 #else
2170 (void)targetIsDir; /* UNUSED */
2171 #endif
2172 failure_start(file, line, "Could not create symlink");
2173 logprintf(" New link: %s\n", newpath);
2174 logprintf(" Old name: %s\n", linkto);
2175 failure_finish(NULL);
2176 return(0);
2177 }
2178
2179 /* Set umask, report failures. */
2180 int
assertion_umask(const char * file,int line,int mask)2181 assertion_umask(const char *file, int line, int mask)
2182 {
2183 assertion_count(file, line);
2184 (void)file; /* UNUSED */
2185 (void)line; /* UNUSED */
2186 umask((mode_t)mask);
2187 return (1);
2188 }
2189
2190 /* Set times, report failures. */
2191 int
assertion_utimes(const char * file,int line,const char * pathname,time_t at,suseconds_t at_nsec,time_t mt,suseconds_t mt_nsec)2192 assertion_utimes(const char *file, int line, const char *pathname,
2193 time_t at, suseconds_t at_nsec, time_t mt, suseconds_t mt_nsec)
2194 {
2195 int r;
2196
2197 #if defined(_WIN32) && !defined(__CYGWIN__)
2198 #define WINTIME(sec, nsec) (((sec * 10000000LL) + EPOC_TIME)\
2199 + (((nsec)/1000)*10))
2200 HANDLE h;
2201 ULARGE_INTEGER wintm;
2202 FILETIME fatime, fmtime;
2203 FILETIME *pat, *pmt;
2204
2205 assertion_count(file, line);
2206 h = CreateFileA(pathname,GENERIC_READ | GENERIC_WRITE,
2207 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
2208 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
2209 if (h == INVALID_HANDLE_VALUE) {
2210 failure_start(file, line, "Can't access %s\n", pathname);
2211 failure_finish(NULL);
2212 return (0);
2213 }
2214
2215 if (at > 0 || at_nsec > 0) {
2216 wintm.QuadPart = WINTIME(at, at_nsec);
2217 fatime.dwLowDateTime = wintm.LowPart;
2218 fatime.dwHighDateTime = wintm.HighPart;
2219 pat = &fatime;
2220 } else
2221 pat = NULL;
2222 if (mt > 0 || mt_nsec > 0) {
2223 wintm.QuadPart = WINTIME(mt, mt_nsec);
2224 fmtime.dwLowDateTime = wintm.LowPart;
2225 fmtime.dwHighDateTime = wintm.HighPart;
2226 pmt = &fmtime;
2227 } else
2228 pmt = NULL;
2229 if (pat != NULL || pmt != NULL)
2230 r = SetFileTime(h, NULL, pat, pmt);
2231 else
2232 r = 1;
2233 CloseHandle(h);
2234 if (r == 0) {
2235 failure_start(file, line, "Can't SetFileTime %s\n", pathname);
2236 failure_finish(NULL);
2237 return (0);
2238 }
2239 return (1);
2240 #else /* defined(_WIN32) && !defined(__CYGWIN__) */
2241 struct stat st;
2242 struct timeval times[2];
2243
2244 #if !defined(__FreeBSD__)
2245 mt_nsec = at_nsec = 0; /* Generic POSIX only has whole seconds. */
2246 #endif
2247 if (mt == 0 && mt_nsec == 0 && at == 0 && at_nsec == 0)
2248 return (1);
2249
2250 r = lstat(pathname, &st);
2251 if (r < 0) {
2252 failure_start(file, line, "Can't stat %s\n", pathname);
2253 failure_finish(NULL);
2254 return (0);
2255 }
2256
2257 if (mt == 0 && mt_nsec == 0) {
2258 mt = st.st_mtime;
2259 #if defined(__FreeBSD__)
2260 mt_nsec = st.st_mtimespec.tv_nsec;
2261 /* FreeBSD generally only stores to microsecond res, so round. */
2262 mt_nsec = (mt_nsec / 1000) * 1000;
2263 #endif
2264 }
2265 if (at == 0 && at_nsec == 0) {
2266 at = st.st_atime;
2267 #if defined(__FreeBSD__)
2268 at_nsec = st.st_atimespec.tv_nsec;
2269 /* FreeBSD generally only stores to microsecond res, so round. */
2270 at_nsec = (at_nsec / 1000) * 1000;
2271 #endif
2272 }
2273
2274 times[1].tv_sec = mt;
2275 times[1].tv_usec = mt_nsec / 1000;
2276
2277 times[0].tv_sec = at;
2278 times[0].tv_usec = at_nsec / 1000;
2279
2280 #ifdef HAVE_LUTIMES
2281 r = lutimes(pathname, times);
2282 #else
2283 r = utimes(pathname, times);
2284 #endif
2285 if (r < 0) {
2286 failure_start(file, line, "Can't utimes %s\n", pathname);
2287 failure_finish(NULL);
2288 return (0);
2289 }
2290 return (1);
2291 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
2292 }
2293
2294 /* Compare file flags */
2295 int
assertion_compare_fflags(const char * file,int line,const char * patha,const char * pathb,int nomatch)2296 assertion_compare_fflags(const char *file, int line, const char *patha,
2297 const char *pathb, int nomatch)
2298 {
2299 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2300 struct stat sa, sb;
2301
2302 assertion_count(file, line);
2303
2304 if (stat(patha, &sa) < 0)
2305 return (0);
2306 if (stat(pathb, &sb) < 0)
2307 return (0);
2308 if (!nomatch && sa.st_flags != sb.st_flags) {
2309 failure_start(file, line, "File flags should be identical: "
2310 "%s=%#010x %s=%#010x", patha, sa.st_flags, pathb,
2311 sb.st_flags);
2312 failure_finish(NULL);
2313 return (0);
2314 }
2315 if (nomatch && sa.st_flags == sb.st_flags) {
2316 failure_start(file, line, "File flags should be different: "
2317 "%s=%#010x %s=%#010x", patha, sa.st_flags, pathb,
2318 sb.st_flags);
2319 failure_finish(NULL);
2320 return (0);
2321 }
2322 #elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) && \
2323 defined(FS_NODUMP_FL)) || \
2324 (defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \
2325 && defined(EXT2_NODUMP_FL))
2326 int fd, r, flagsa, flagsb;
2327
2328 assertion_count(file, line);
2329 fd = open(patha, O_RDONLY | O_NONBLOCK);
2330 if (fd < 0) {
2331 failure_start(file, line, "Can't open %s\n", patha);
2332 failure_finish(NULL);
2333 return (0);
2334 }
2335 r = ioctl(fd,
2336 #ifdef FS_IOC_GETFLAGS
2337 FS_IOC_GETFLAGS,
2338 #else
2339 EXT2_IOC_GETFLAGS,
2340 #endif
2341 &flagsa);
2342 close(fd);
2343 if (r < 0) {
2344 failure_start(file, line, "Can't get flags %s\n", patha);
2345 failure_finish(NULL);
2346 return (0);
2347 }
2348 fd = open(pathb, O_RDONLY | O_NONBLOCK);
2349 if (fd < 0) {
2350 failure_start(file, line, "Can't open %s\n", pathb);
2351 failure_finish(NULL);
2352 return (0);
2353 }
2354 r = ioctl(fd,
2355 #ifdef FS_IOC_GETFLAGS
2356 FS_IOC_GETFLAGS,
2357 #else
2358 EXT2_IOC_GETFLAGS,
2359 #endif
2360 &flagsb);
2361 close(fd);
2362 if (r < 0) {
2363 failure_start(file, line, "Can't get flags %s\n", pathb);
2364 failure_finish(NULL);
2365 return (0);
2366 }
2367 if (!nomatch && flagsa != flagsb) {
2368 failure_start(file, line, "File flags should be identical: "
2369 "%s=%#010x %s=%#010x", patha, flagsa, pathb, flagsb);
2370 failure_finish(NULL);
2371 return (0);
2372 }
2373 if (nomatch && flagsa == flagsb) {
2374 failure_start(file, line, "File flags should be different: "
2375 "%s=%#010x %s=%#010x", patha, flagsa, pathb, flagsb);
2376 failure_finish(NULL);
2377 return (0);
2378 }
2379 #else
2380 (void)patha; /* UNUSED */
2381 (void)pathb; /* UNUSED */
2382 (void)nomatch; /* UNUSED */
2383 assertion_count(file, line);
2384 #endif
2385 return (1);
2386 }
2387
2388 /* Set nodump, report failures. */
2389 int
assertion_set_nodump(const char * file,int line,const char * pathname)2390 assertion_set_nodump(const char *file, int line, const char *pathname)
2391 {
2392 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2393 int r;
2394
2395 assertion_count(file, line);
2396 r = chflags(pathname, UF_NODUMP);
2397 if (r < 0) {
2398 failure_start(file, line, "Can't set nodump %s\n", pathname);
2399 failure_finish(NULL);
2400 return (0);
2401 }
2402 #elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) && \
2403 defined(FS_NODUMP_FL)) || \
2404 (defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \
2405 && defined(EXT2_NODUMP_FL))
2406 int fd, r, flags;
2407
2408 assertion_count(file, line);
2409 fd = open(pathname, O_RDONLY | O_NONBLOCK);
2410 if (fd < 0) {
2411 failure_start(file, line, "Can't open %s\n", pathname);
2412 failure_finish(NULL);
2413 return (0);
2414 }
2415 r = ioctl(fd,
2416 #ifdef FS_IOC_GETFLAGS
2417 FS_IOC_GETFLAGS,
2418 #else
2419 EXT2_IOC_GETFLAGS,
2420 #endif
2421 &flags);
2422 if (r < 0) {
2423 failure_start(file, line, "Can't get flags %s\n", pathname);
2424 failure_finish(NULL);
2425 return (0);
2426 }
2427 #ifdef FS_NODUMP_FL
2428 flags |= FS_NODUMP_FL;
2429 #else
2430 flags |= EXT2_NODUMP_FL;
2431 #endif
2432
2433 r = ioctl(fd,
2434 #ifdef FS_IOC_SETFLAGS
2435 FS_IOC_SETFLAGS,
2436 #else
2437 EXT2_IOC_SETFLAGS,
2438 #endif
2439 &flags);
2440 if (r < 0) {
2441 failure_start(file, line, "Can't set nodump %s\n", pathname);
2442 failure_finish(NULL);
2443 return (0);
2444 }
2445 close(fd);
2446 #else
2447 (void)pathname; /* UNUSED */
2448 assertion_count(file, line);
2449 #endif
2450 return (1);
2451 }
2452
2453 #ifdef PROGRAM
assert_version_id(char ** qq,size_t * ss)2454 static void assert_version_id(char **qq, size_t *ss)
2455 {
2456 char *q = *qq;
2457 size_t s = *ss;
2458
2459 /* Version number is a series of digits and periods. */
2460 while (s > 0 && (*q == '.' || (*q >= '0' && *q <= '9'))) {
2461 ++q;
2462 --s;
2463 }
2464
2465 if (q[0] == 'd' && q[1] == 'e' && q[2] == 'v') {
2466 q += 3;
2467 s -= 3;
2468 }
2469
2470 /* Skip a single trailing a,b,c, or d. */
2471 if (*q == 'a' || *q == 'b' || *q == 'c' || *q == 'd')
2472 ++q;
2473
2474 /* Version number terminated by space. */
2475 failure("No space after version: ``%s''", q);
2476 assert(s > 1);
2477 failure("No space after version: ``%s''", q);
2478 assert(*q == ' ');
2479
2480 ++q; --s;
2481
2482 *qq = q;
2483 *ss = s;
2484 }
2485
2486
2487 /*
2488 * Check program version
2489 */
assertVersion(const char * prog,const char * base)2490 void assertVersion(const char *prog, const char *base)
2491 {
2492 int r;
2493 char *p, *q;
2494 size_t s;
2495 size_t prog_len = strlen(base);
2496
2497 r = systemf("%s --version >version.stdout 2>version.stderr", prog);
2498 if (r != 0)
2499 r = systemf("%s -W version >version.stdout 2>version.stderr",
2500 prog);
2501
2502 failure("Unable to run either %s --version or %s -W version",
2503 prog, prog);
2504 if (!assert(r == 0))
2505 return;
2506
2507 /* --version should generate nothing to stdout. */
2508 assertEmptyFile("version.stderr");
2509
2510 /* Verify format of version message. */
2511 q = p = slurpfile(&s, "version.stdout");
2512
2513 /* Version message should start with name of program, then space. */
2514 assert(s > prog_len + 1);
2515
2516 failure("Version must start with '%s': ``%s''", base, p);
2517 if (!assertEqualMem(q, base, prog_len)) {
2518 free(p);
2519 return;
2520 }
2521
2522 q += prog_len; s -= prog_len;
2523
2524 assert(*q == ' ');
2525 q++; s--;
2526
2527 assert_version_id(&q, &s);
2528
2529 /* Separator. */
2530 failure("No `-' between program name and versions: ``%s''", p);
2531 assertEqualMem(q, "- ", 2);
2532 q += 2; s -= 2;
2533
2534 failure("Not long enough for libarchive version: ``%s''", p);
2535 assert(s > 11);
2536
2537 failure("Libarchive version must start with `libarchive': ``%s''", p);
2538 assertEqualMem(q, "libarchive ", 11);
2539
2540 q += 11; s -= 11;
2541
2542 assert_version_id(&q, &s);
2543
2544 /* Skip arbitrary third-party version numbers. */
2545 while (s > 0 && (*q == ' ' || *q == '-' || *q == '/' || *q == '.' ||
2546 *q == '_' || isalnum((unsigned char)*q))) {
2547 ++q;
2548 --s;
2549 }
2550
2551 /* All terminated by end-of-line. */
2552 assert(s >= 1);
2553
2554 /* Skip an optional CR character (e.g., Windows) */
2555 failure("Version output must end with \\n or \\r\\n");
2556
2557 if (*q == '\r') { ++q; --s; }
2558 assertEqualMem(q, "\n", 1);
2559
2560 free(p);
2561 }
2562 #endif /* PROGRAM */
2563
2564 /*
2565 *
2566 * UTILITIES for use by tests.
2567 *
2568 */
2569
2570 /*
2571 * Check whether platform supports symlinks. This is intended
2572 * for tests to use in deciding whether to bother testing symlink
2573 * support; if the platform doesn't support symlinks, there's no point
2574 * in checking whether the program being tested can create them.
2575 *
2576 * Note that the first time this test is called, we actually go out to
2577 * disk to create and verify a symlink. This is necessary because
2578 * symlink support is actually a property of a particular filesystem
2579 * and can thus vary between directories on a single system. After
2580 * the first call, this returns the cached result from memory, so it's
2581 * safe to call it as often as you wish.
2582 */
2583 int
canSymlink(void)2584 canSymlink(void)
2585 {
2586 /* Remember the test result */
2587 static int value = 0, tested = 0;
2588 if (tested)
2589 return (value);
2590
2591 ++tested;
2592 assertion_make_file(__FILE__, __LINE__, "canSymlink.0", 0644, 1, "a");
2593 /* Note: Cygwin has its own symlink() emulation that does not
2594 * use the Win32 CreateSymbolicLink() function. */
2595 #if defined(_WIN32) && !defined(__CYGWIN__)
2596 value = my_CreateSymbolicLinkA("canSymlink.1", "canSymlink.0", 0)
2597 && is_symlink(__FILE__, __LINE__, "canSymlink.1", "canSymlink.0",
2598 0);
2599 #elif HAVE_SYMLINK
2600 value = (0 == symlink("canSymlink.0", "canSymlink.1"))
2601 && is_symlink(__FILE__, __LINE__, "canSymlink.1","canSymlink.0",
2602 0);
2603 #endif
2604 return (value);
2605 }
2606
2607 /* Platform-dependent options for hiding the output of a subcommand. */
2608 #if defined(_WIN32) && !defined(__CYGWIN__)
2609 static const char *redirectArgs = ">NUL 2>NUL"; /* Win32 cmd.exe */
2610 #else
2611 static const char *redirectArgs = ">/dev/null 2>/dev/null"; /* POSIX 'sh' */
2612 #endif
2613
2614 /*
2615 * Can this platform run the specified command?
2616 */
2617 int
canRunCommand(const char * cmd,int * tested)2618 canRunCommand(const char *cmd, int *tested)
2619 {
2620 int value = tested ? *tested : 0;
2621 if (!value) {
2622 value = systemf("%s %s", cmd, redirectArgs) ? -1 : +1;
2623 if (tested)
2624 *tested = value;
2625 }
2626 return (value > 0);
2627 }
2628
2629 #define CAN_RUN_FUNC(Program, Command) \
2630 int can##Program(void) { \
2631 static int tested = 0; \
2632 return canRunCommand((Command), &tested); \
2633 }
2634
2635 /*
2636 * Can this platform run the bzip2 program?
2637 */
2638 CAN_RUN_FUNC(Bzip2, "bzip2 --help")
2639
2640 /*
2641 * Can this platform run the grzip program?
2642 */
2643 CAN_RUN_FUNC(Grzip, "grzip -V")
2644
2645 /*
2646 * Can this platform run the gzip program?
2647 */
2648 CAN_RUN_FUNC(Gzip, "gzip --help")
2649
2650 /*
2651 * Can this platform run the lrzip program?
2652 */
2653 CAN_RUN_FUNC(Lrzip, "lrzip -V")
2654
2655 /*
2656 * Can this platform run the lz4 program?
2657 */
2658 CAN_RUN_FUNC(Lz4, "lz4 --help")
2659
2660 /*
2661 * Can this platform run the zstd program?
2662 */
2663 CAN_RUN_FUNC(Zstd, "zstd --help")
2664
2665 /*
2666 * Can this platform run the lzip program?
2667 */
2668 CAN_RUN_FUNC(Lzip, "lzip --help")
2669
2670 /*
2671 * Can this platform run the lzma program?
2672 */
2673 CAN_RUN_FUNC(Lzma, "lzma --help")
2674
2675 /*
2676 * Can this platform run the lzop program?
2677 */
2678 CAN_RUN_FUNC(Lzop, "lzop --help")
2679
2680 /*
2681 * Can this platform run the xz program?
2682 */
2683 CAN_RUN_FUNC(Xz, "xz --help")
2684
2685 /*
2686 * Can this filesystem handle nodump flags.
2687 */
2688 int
canNodump(void)2689 canNodump(void)
2690 {
2691 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
2692 const char *path = "cannodumptest";
2693 struct stat sb;
2694
2695 assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);
2696 if (chflags(path, UF_NODUMP) < 0)
2697 return (0);
2698 if (stat(path, &sb) < 0)
2699 return (0);
2700 if (sb.st_flags & UF_NODUMP)
2701 return (1);
2702 #elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) \
2703 && defined(FS_NODUMP_FL)) || \
2704 (defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \
2705 && defined(EXT2_NODUMP_FL))
2706 const char *path = "cannodumptest";
2707 int fd, r, flags;
2708
2709 assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);
2710 fd = open(path, O_RDONLY | O_NONBLOCK);
2711 if (fd < 0)
2712 return (0);
2713 r = ioctl(fd,
2714 #ifdef FS_IOC_GETFLAGS
2715 FS_IOC_GETFLAGS,
2716 #else
2717 EXT2_IOC_GETFLAGS,
2718 #endif
2719 &flags);
2720 if (r < 0)
2721 return (0);
2722 #ifdef FS_NODUMP_FL
2723 flags |= FS_NODUMP_FL;
2724 #else
2725 flags |= EXT2_NODUMP_FL;
2726 #endif
2727 r = ioctl(fd,
2728 #ifdef FS_IOC_SETFLAGS
2729 FS_IOC_SETFLAGS,
2730 #else
2731 EXT2_IOC_SETFLAGS,
2732 #endif
2733 &flags);
2734 if (r < 0)
2735 return (0);
2736 close(fd);
2737 fd = open(path, O_RDONLY | O_NONBLOCK);
2738 if (fd < 0)
2739 return (0);
2740 r = ioctl(fd,
2741 #ifdef FS_IOC_GETFLAGS
2742 FS_IOC_GETFLAGS,
2743 #else
2744 EXT2_IOC_GETFLAGS,
2745 #endif
2746 &flags);
2747 if (r < 0)
2748 return (0);
2749 close(fd);
2750 #ifdef FS_NODUMP_FL
2751 if (flags & FS_NODUMP_FL)
2752 #else
2753 if (flags & EXT2_NODUMP_FL)
2754 #endif
2755 return (1);
2756 #endif
2757 return (0);
2758 }
2759
2760 /* Get extended attribute value from a path */
2761 void *
getXattr(const char * path,const char * name,size_t * sizep)2762 getXattr(const char *path, const char *name, size_t *sizep)
2763 {
2764 void *value = NULL;
2765 #if ARCHIVE_XATTR_SUPPORT
2766 ssize_t size;
2767 #if ARCHIVE_XATTR_LINUX
2768 size = lgetxattr(path, name, NULL, 0);
2769 #elif ARCHIVE_XATTR_DARWIN
2770 size = getxattr(path, name, NULL, 0, 0, XATTR_NOFOLLOW);
2771 #elif ARCHIVE_XATTR_AIX
2772 size = lgetea(path, name, NULL, 0);
2773 #elif ARCHIVE_XATTR_FREEBSD
2774 size = extattr_get_link(path, EXTATTR_NAMESPACE_USER, name + 5,
2775 NULL, 0);
2776 #endif
2777
2778 if (size >= 0) {
2779 value = malloc(size);
2780 #if ARCHIVE_XATTR_LINUX
2781 size = lgetxattr(path, name, value, size);
2782 #elif ARCHIVE_XATTR_DARWIN
2783 size = getxattr(path, name, value, size, 0, XATTR_NOFOLLOW);
2784 #elif ARCHIVE_XATTR_AIX
2785 size = lgetea(path, name, value, size);
2786 #elif ARCHIVE_XATTR_FREEBSD
2787 size = extattr_get_link(path, EXTATTR_NAMESPACE_USER, name + 5,
2788 value, size);
2789 #endif
2790 if (size < 0) {
2791 free(value);
2792 value = NULL;
2793 }
2794 }
2795 if (size < 0)
2796 *sizep = 0;
2797 else
2798 *sizep = (size_t)size;
2799 #else /* !ARCHIVE_XATTR_SUPPORT */
2800 (void)path; /* UNUSED */
2801 (void)name; /* UNUSED */
2802 *sizep = 0;
2803 #endif /* !ARCHIVE_XATTR_SUPPORT */
2804 return (value);
2805 }
2806
2807 /*
2808 * Set extended attribute on a path
2809 * Returns 0 on error, 1 on success
2810 */
2811 int
setXattr(const char * path,const char * name,const void * value,size_t size)2812 setXattr(const char *path, const char *name, const void *value, size_t size)
2813 {
2814 #if ARCHIVE_XATTR_SUPPORT
2815 #if ARCHIVE_XATTR_LINUX
2816 if (lsetxattr(path, name, value, size, 0) == 0)
2817 #elif ARCHIVE_XATTR_DARWIN
2818 if (setxattr(path, name, value, size, 0, XATTR_NOFOLLOW) == 0)
2819 #elif ARCHIVE_XATTR_AIX
2820 if (lsetea(path, name, value, size, 0) == 0)
2821 #elif ARCHIVE_XATTR_FREEBSD
2822 if (extattr_set_link(path, EXTATTR_NAMESPACE_USER, name + 5, value,
2823 size) > -1)
2824 #else
2825 if (0)
2826 #endif
2827 return (1);
2828 #else /* !ARCHIVE_XATTR_SUPPORT */
2829 (void)path; /* UNUSED */
2830 (void)name; /* UNUSED */
2831 (void)value; /* UNUSED */
2832 (void)size; /* UNUSED */
2833 #endif /* !ARCHIVE_XATTR_SUPPORT */
2834 return (0);
2835 }
2836
2837 #if ARCHIVE_ACL_SUNOS
2838 /* Fetch ACLs on Solaris using acl() or facl() */
2839 void *
sunacl_get(int cmd,int * aclcnt,int fd,const char * path)2840 sunacl_get(int cmd, int *aclcnt, int fd, const char *path)
2841 {
2842 int cnt, cntcmd;
2843 size_t size;
2844 void *aclp;
2845
2846 if (cmd == GETACL) {
2847 cntcmd = GETACLCNT;
2848 size = sizeof(aclent_t);
2849 }
2850 #if ARCHIVE_ACL_SUNOS_NFS4
2851 else if (cmd == ACE_GETACL) {
2852 cntcmd = ACE_GETACLCNT;
2853 size = sizeof(ace_t);
2854 }
2855 #endif
2856 else {
2857 errno = EINVAL;
2858 *aclcnt = -1;
2859 return (NULL);
2860 }
2861
2862 aclp = NULL;
2863 cnt = -2;
2864 while (cnt == -2 || (cnt == -1 && errno == ENOSPC)) {
2865 if (path != NULL)
2866 cnt = acl(path, cntcmd, 0, NULL);
2867 else
2868 cnt = facl(fd, cntcmd, 0, NULL);
2869
2870 if (cnt > 0) {
2871 if (aclp == NULL)
2872 aclp = malloc(cnt * size);
2873 else
2874 aclp = realloc(NULL, cnt * size);
2875 if (aclp != NULL) {
2876 if (path != NULL)
2877 cnt = acl(path, cmd, cnt, aclp);
2878 else
2879 cnt = facl(fd, cmd, cnt, aclp);
2880 }
2881 } else {
2882 free(aclp);
2883 aclp = NULL;
2884 break;
2885 }
2886 }
2887
2888 *aclcnt = cnt;
2889 return (aclp);
2890 }
2891 #endif /* ARCHIVE_ACL_SUNOS */
2892
2893 /*
2894 * Set test ACLs on a path
2895 * Return values:
2896 * 0: error setting ACLs
2897 * ARCHIVE_TEST_ACL_TYPE_POSIX1E: POSIX.1E ACLs have been set
2898 * ARCHIVE_TEST_ACL_TYPE_NFS4: NFSv4 or extended ACLs have been set
2899 */
2900 int
setTestAcl(const char * path)2901 setTestAcl(const char *path)
2902 {
2903 #if ARCHIVE_ACL_SUPPORT
2904 int r = 1;
2905 #if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_DARWIN
2906 acl_t acl;
2907 #endif
2908 #if ARCHIVE_ACL_LIBRICHACL
2909 struct richacl *richacl;
2910 #endif
2911 #if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_FREEBSD
2912 const char *acltext_posix1e = "user:1:rw-,"
2913 "group:15:r-x,"
2914 "user::rwx,"
2915 "group::rwx,"
2916 "other::r-x,"
2917 "mask::rwx";
2918 #elif ARCHIVE_ACL_SUNOS /* Solaris POSIX.1e */
2919 aclent_t aclp_posix1e[] = {
2920 { USER_OBJ, -1, 4 | 2 | 1 },
2921 { USER, 1, 4 | 2 },
2922 { GROUP_OBJ, -1, 4 | 2 | 1 },
2923 { GROUP, 15, 4 | 1 },
2924 { CLASS_OBJ, -1, 4 | 2 | 1 },
2925 { OTHER_OBJ, -1, 4 | 2 | 1 }
2926 };
2927 #endif
2928 #if ARCHIVE_ACL_FREEBSD /* FreeBSD NFS4 */
2929 const char *acltext_nfs4 = "user:1:rwpaRcs::allow:1,"
2930 "group:15:rxaRcs::allow:15,"
2931 "owner@:rwpxaARWcCos::allow,"
2932 "group@:rwpxaRcs::allow,"
2933 "everyone@:rxaRcs::allow";
2934 #elif ARCHIVE_ACL_LIBRICHACL
2935 const char *acltext_nfs4 = "owner:rwpxaARWcCoS::mask,"
2936 "group:rwpxaRcS::mask,"
2937 "other:rxaRcS::mask,"
2938 "user:1:rwpaRcS::allow,"
2939 "group:15:rxaRcS::allow,"
2940 "owner@:rwpxaARWcCoS::allow,"
2941 "group@:rwpxaRcS::allow,"
2942 "everyone@:rxaRcS::allow";
2943 #elif ARCHIVE_ACL_SUNOS_NFS4 /* Solaris NFS4 */
2944 ace_t aclp_nfs4[] = {
2945 { 1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |
2946 ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS | ACE_READ_ACL |
2947 ACE_SYNCHRONIZE, 0, ACE_ACCESS_ALLOWED_ACE_TYPE },
2948 { 15, ACE_READ_DATA | ACE_EXECUTE | ACE_READ_ATTRIBUTES |
2949 ACE_READ_NAMED_ATTRS | ACE_READ_ACL | ACE_SYNCHRONIZE,
2950 ACE_IDENTIFIER_GROUP, ACE_ACCESS_ALLOWED_ACE_TYPE },
2951 { -1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |
2952 ACE_EXECUTE | ACE_READ_ATTRIBUTES | ACE_WRITE_ATTRIBUTES |
2953 ACE_READ_NAMED_ATTRS | ACE_WRITE_NAMED_ATTRS |
2954 ACE_READ_ACL | ACE_WRITE_ACL | ACE_WRITE_OWNER | ACE_SYNCHRONIZE,
2955 ACE_OWNER, ACE_ACCESS_ALLOWED_ACE_TYPE },
2956 { -1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |
2957 ACE_EXECUTE | ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS |
2958 ACE_READ_ACL | ACE_SYNCHRONIZE, ACE_GROUP | ACE_IDENTIFIER_GROUP,
2959 ACE_ACCESS_ALLOWED_ACE_TYPE },
2960 { -1, ACE_READ_DATA | ACE_EXECUTE | ACE_READ_ATTRIBUTES |
2961 ACE_READ_NAMED_ATTRS | ACE_READ_ACL | ACE_SYNCHRONIZE,
2962 ACE_EVERYONE, ACE_ACCESS_ALLOWED_ACE_TYPE }
2963 };
2964 #elif ARCHIVE_ACL_DARWIN /* Mac OS X */
2965 acl_entry_t aclent;
2966 acl_permset_t permset;
2967 const uid_t uid = 1;
2968 uuid_t uuid;
2969 const acl_perm_t acl_perms[] = {
2970 ACL_READ_DATA,
2971 ACL_WRITE_DATA,
2972 ACL_APPEND_DATA,
2973 ACL_EXECUTE,
2974 ACL_READ_ATTRIBUTES,
2975 ACL_READ_EXTATTRIBUTES,
2976 ACL_READ_SECURITY,
2977 #if HAVE_DECL_ACL_SYNCHRONIZE
2978 ACL_SYNCHRONIZE
2979 #endif
2980 };
2981 #endif /* ARCHIVE_ACL_DARWIN */
2982
2983 #if ARCHIVE_ACL_FREEBSD
2984 acl = acl_from_text(acltext_nfs4);
2985 failure("acl_from_text() error: %s", strerror(errno));
2986 if (assert(acl != NULL) == 0)
2987 return (0);
2988 #elif ARCHIVE_ACL_LIBRICHACL
2989 richacl = richacl_from_text(acltext_nfs4, NULL, NULL);
2990 failure("richacl_from_text() error: %s", strerror(errno));
2991 if (assert(richacl != NULL) == 0)
2992 return (0);
2993 #elif ARCHIVE_ACL_DARWIN
2994 acl = acl_init(1);
2995 failure("acl_init() error: %s", strerror(errno));
2996 if (assert(acl != NULL) == 0)
2997 return (0);
2998 r = acl_create_entry(&acl, &aclent);
2999 failure("acl_create_entry() error: %s", strerror(errno));
3000 if (assertEqualInt(r, 0) == 0)
3001 goto testacl_free;
3002 r = acl_set_tag_type(aclent, ACL_EXTENDED_ALLOW);
3003 failure("acl_set_tag_type() error: %s", strerror(errno));
3004 if (assertEqualInt(r, 0) == 0)
3005 goto testacl_free;
3006 r = acl_get_permset(aclent, &permset);
3007 failure("acl_get_permset() error: %s", strerror(errno));
3008 if (assertEqualInt(r, 0) == 0)
3009 goto testacl_free;
3010 for (size_t i = 0; i < nitems(acl_perms); i++) {
3011 r = acl_add_perm(permset, acl_perms[i]);
3012 failure("acl_add_perm() error: %s", strerror(errno));
3013 if (assertEqualInt(r, 0) == 0)
3014 goto testacl_free;
3015 }
3016 r = acl_set_permset(aclent, permset);
3017 failure("acl_set_permset() error: %s", strerror(errno));
3018 if (assertEqualInt(r, 0) == 0)
3019 goto testacl_free;
3020 r = mbr_uid_to_uuid(uid, uuid);
3021 failure("mbr_uid_to_uuid() error: %s", strerror(errno));
3022 if (assertEqualInt(r, 0) == 0)
3023 goto testacl_free;
3024 r = acl_set_qualifier(aclent, uuid);
3025 failure("acl_set_qualifier() error: %s", strerror(errno));
3026 if (assertEqualInt(r, 0) == 0)
3027 goto testacl_free;
3028 #endif /* ARCHIVE_ACL_DARWIN */
3029
3030 #if ARCHIVE_ACL_NFS4
3031 #if ARCHIVE_ACL_FREEBSD
3032 r = acl_set_file(path, ACL_TYPE_NFS4, acl);
3033 acl_free(acl);
3034 #elif ARCHIVE_ACL_LIBRICHACL
3035 r = richacl_set_file(path, richacl);
3036 richacl_free(richacl);
3037 #elif ARCHIVE_ACL_SUNOS_NFS4
3038 r = acl(path, ACE_SETACL,
3039 (int)(sizeof(aclp_nfs4)/sizeof(aclp_nfs4[0])), aclp_nfs4);
3040 #elif ARCHIVE_ACL_DARWIN
3041 r = acl_set_file(path, ACL_TYPE_EXTENDED, acl);
3042 acl_free(acl);
3043 #endif
3044 if (r == 0)
3045 return (ARCHIVE_TEST_ACL_TYPE_NFS4);
3046 #endif /* ARCHIVE_ACL_NFS4 */
3047
3048 #if ARCHIVE_ACL_POSIX1E
3049 #if ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_LIBACL
3050 acl = acl_from_text(acltext_posix1e);
3051 failure("acl_from_text() error: %s", strerror(errno));
3052 if (assert(acl != NULL) == 0)
3053 return (0);
3054
3055 r = acl_set_file(path, ACL_TYPE_ACCESS, acl);
3056 acl_free(acl);
3057 #elif ARCHIVE_ACL_SUNOS
3058 r = acl(path, SETACL,
3059 (int)(sizeof(aclp_posix1e)/sizeof(aclp_posix1e[0])), aclp_posix1e);
3060 #endif
3061 if (r == 0)
3062 return (ARCHIVE_TEST_ACL_TYPE_POSIX1E);
3063 else
3064 return (0);
3065 #endif /* ARCHIVE_ACL_POSIX1E */
3066 #if ARCHIVE_ACL_DARWIN
3067 testacl_free:
3068 acl_free(acl);
3069 #endif
3070 #endif /* ARCHIVE_ACL_SUPPORT */
3071 (void)path; /* UNUSED */
3072 return (0);
3073 }
3074
3075 /*
3076 * Sleep as needed; useful for verifying disk timestamp changes by
3077 * ensuring that the wall-clock time has actually changed before we
3078 * go back to re-read something from disk.
3079 */
3080 void
sleepUntilAfter(time_t t)3081 sleepUntilAfter(time_t t)
3082 {
3083 while (t >= time(NULL))
3084 #if defined(_WIN32) && !defined(__CYGWIN__)
3085 Sleep(500);
3086 #else
3087 sleep(1);
3088 #endif
3089 }
3090
3091 /*
3092 * Call standard system() call, but build up the command line using
3093 * sprintf() conventions.
3094 */
3095 int
systemf(const char * fmt,...)3096 systemf(const char *fmt, ...)
3097 {
3098 char buff[8192];
3099 #if USE_POSIX_SPAWN
3100 char *argv[] = { "/bin/sh", "-c", buff, NULL };
3101 pid_t pid;
3102 #endif
3103 va_list ap;
3104 size_t off = 0, avail = sizeof(buff);
3105 int r;
3106
3107 #if defined(_WIN32) && !defined(__CYGWIN__)
3108 /* system() on Windows runs its arguments through CMD.EXE, which has
3109 * notoriously unfriendly quoting rules. The current best documented way around
3110 * them is to wrap your *entire commandline* in sacrificial quotes.
3111 *
3112 * See CMD.EXE /? for more information. Excerpted here:
3113 * | Otherwise, old behavior is to see if the first character is
3114 * | a quote character and if so, strip the leading character and
3115 * | remove the last quote character on the command line, preserving
3116 * | any text after the last quote character.
3117 *
3118 * Since these tests often make use of systemf() with quoted arguments inside
3119 * the commandline, wrap every formatted commandline in quotes.
3120 */
3121 avail -= 2;
3122 off++;
3123 buff[0] = '"';
3124 #endif
3125
3126 va_start(ap, fmt);
3127 r = vsnprintf(buff + off, avail, fmt, ap);
3128 va_end(ap);
3129
3130 if (r < 0 || (size_t)r >= avail) {
3131 return (-1);
3132 }
3133
3134 #if defined(_WIN32) && !defined(__CYGWIN__)
3135 buff[off + r] = '"';
3136 buff[off + r + 1] = '\0';
3137 #endif
3138
3139 if (verbosity > VERBOSITY_FULL)
3140 logprintf("Cmd: %s\n", buff);
3141 #if USE_POSIX_SPAWN
3142 if ((r = posix_spawn(&pid, *argv, NULL, NULL, argv, environ)) == 0) {
3143 while (waitpid(pid, &r, 0) == -1) {
3144 if (errno != EINTR)
3145 return (-1);
3146 }
3147 }
3148 #else
3149 r = system(buff);
3150 #endif
3151 return (r);
3152 }
3153
3154 /*
3155 * Slurp a file into memory for ease of comparison and testing.
3156 * Returns size of file in 'sizep' if non-NULL, null-terminates
3157 * data in memory for ease of use.
3158 */
3159 char *
slurpfile(size_t * sizep,const char * fmt,...)3160 slurpfile(size_t * sizep, const char *fmt, ...)
3161 {
3162 char filename[8192];
3163 struct stat st;
3164 va_list ap;
3165 char *p;
3166 ssize_t bytes_read;
3167 FILE *f;
3168 int r;
3169
3170 va_start(ap, fmt);
3171 vsnprintf(filename, sizeof(filename), fmt, ap);
3172 va_end(ap);
3173
3174 f = fopen(filename, "rb");
3175 if (f == NULL) {
3176 /* Note: No error; non-existent file is okay here. */
3177 return (NULL);
3178 }
3179 r = fstat(fileno(f), &st);
3180 if (r != 0) {
3181 logprintf("Can't stat file %s\n", filename);
3182 fclose(f);
3183 return (NULL);
3184 }
3185 p = malloc((size_t)st.st_size + 1);
3186 if (p == NULL) {
3187 logprintf("Can't allocate %ld bytes of memory to read file %s\n",
3188 (long int)st.st_size, filename);
3189 fclose(f);
3190 return (NULL);
3191 }
3192 bytes_read = fread(p, 1, (size_t)st.st_size, f);
3193 if (bytes_read < st.st_size) {
3194 logprintf("Can't read file %s\n", filename);
3195 fclose(f);
3196 free(p);
3197 return (NULL);
3198 }
3199 p[st.st_size] = '\0';
3200 if (sizep != NULL)
3201 *sizep = (size_t)st.st_size;
3202 fclose(f);
3203 return (p);
3204 }
3205
3206 /*
3207 * Slurp a file into memory for ease of comparison and testing.
3208 * Returns size of file in 'sizep' if non-NULL, null-terminates
3209 * data in memory for ease of use.
3210 */
3211 void
dumpfile(const char * filename,void * data,size_t len)3212 dumpfile(const char *filename, void *data, size_t len)
3213 {
3214 ssize_t bytes_written;
3215 FILE *f;
3216
3217 f = fopen(filename, "wb");
3218 if (f == NULL) {
3219 logprintf("Can't open file %s for writing\n", filename);
3220 return;
3221 }
3222 bytes_written = fwrite(data, 1, len, f);
3223 if (bytes_written < (ssize_t)len)
3224 logprintf("Can't write file %s\n", filename);
3225 fclose(f);
3226 }
3227
3228 /* Read a uuencoded file from the reference directory, decode, and
3229 * write the result into the current directory. */
3230 #define VALID_UUDECODE(c) (c >= 32 && c <= 96)
3231 #define UUDECODE(c) (((c) - 0x20) & 0x3f)
3232 void
extract_reference_file(const char * name)3233 extract_reference_file(const char *name)
3234 {
3235 char buff[1024];
3236 FILE *in, *out;
3237
3238 snprintf(buff, sizeof(buff), "%s/%s.uu", refdir, name);
3239 in = fopen(buff, "r");
3240 failure("Couldn't open reference file %s", buff);
3241 assert(in != NULL);
3242 if (in == NULL)
3243 return;
3244 /* Read up to and including the 'begin' line. */
3245 for (;;) {
3246 if (fgets(buff, sizeof(buff), in) == NULL) {
3247 /* TODO: This is a failure. */
3248 return;
3249 }
3250 if (memcmp(buff, "begin ", 6) == 0)
3251 break;
3252 }
3253 /* Now, decode the rest and write it. */
3254 out = fopen(name, "wb");
3255 while (fgets(buff, sizeof(buff), in) != NULL) {
3256 char *p = buff;
3257 int bytes;
3258
3259 if (memcmp(buff, "end", 3) == 0)
3260 break;
3261
3262 bytes = UUDECODE(*p++);
3263 while (bytes > 0) {
3264 int n = 0;
3265 /* Write out 1-3 bytes from that. */
3266 assert(VALID_UUDECODE(p[0]));
3267 assert(VALID_UUDECODE(p[1]));
3268 n = UUDECODE(*p++) << 18;
3269 n |= UUDECODE(*p++) << 12;
3270 fputc(n >> 16, out);
3271 --bytes;
3272 if (bytes > 0) {
3273 assert(VALID_UUDECODE(p[0]));
3274 n |= UUDECODE(*p++) << 6;
3275 fputc((n >> 8) & 0xFF, out);
3276 --bytes;
3277 }
3278 if (bytes > 0) {
3279 assert(VALID_UUDECODE(p[0]));
3280 n |= UUDECODE(*p++);
3281 fputc(n & 0xFF, out);
3282 --bytes;
3283 }
3284 }
3285 }
3286 fclose(out);
3287 fclose(in);
3288 }
3289
3290 void
copy_reference_file(const char * name)3291 copy_reference_file(const char *name)
3292 {
3293 char buff[1024];
3294 FILE *in, *out;
3295 size_t rbytes;
3296
3297 snprintf(buff, sizeof(buff), "%s/%s", refdir, name);
3298 in = fopen(buff, "rb");
3299 failure("Couldn't open reference file %s", buff);
3300 assert(in != NULL);
3301 if (in == NULL)
3302 return;
3303 /* Now, decode the rest and write it. */
3304 /* Not a lot of error checking here; the input better be right. */
3305 out = fopen(name, "wb");
3306 while ((rbytes = fread(buff, 1, sizeof(buff), in)) > 0) {
3307 if (fwrite(buff, 1, rbytes, out) != rbytes) {
3308 logprintf("Error: fwrite\n");
3309 break;
3310 }
3311 }
3312 fclose(out);
3313 fclose(in);
3314 }
3315
3316 int
is_LargeInode(const char * file)3317 is_LargeInode(const char *file)
3318 {
3319 #if defined(_WIN32) && !defined(__CYGWIN__)
3320 BY_HANDLE_FILE_INFORMATION bhfi;
3321 int r;
3322
3323 r = my_GetFileInformationByName(file, &bhfi);
3324 if (r != 0)
3325 return (0);
3326 return (bhfi.nFileIndexHigh & 0x0000FFFFUL);
3327 #else
3328 struct stat st;
3329 int64_t ino;
3330
3331 if (stat(file, &st) < 0)
3332 return (0);
3333 ino = (int64_t)st.st_ino;
3334 return (ino > 0xffffffff);
3335 #endif
3336 }
3337
3338 void
extract_reference_files(const char ** names)3339 extract_reference_files(const char **names)
3340 {
3341 while (names && *names)
3342 extract_reference_file(*names++);
3343 }
3344
3345 #ifndef PROGRAM
3346 /* Set ACLs */
3347 int
assertion_entry_set_acls(const char * file,int line,struct archive_entry * ae,struct archive_test_acl_t * acls,int n)3348 assertion_entry_set_acls(const char *file, int line, struct archive_entry *ae,
3349 struct archive_test_acl_t *acls, int n)
3350 {
3351 int i, r, ret;
3352
3353 assertion_count(file, line);
3354
3355 ret = 0;
3356 archive_entry_acl_clear(ae);
3357 for (i = 0; i < n; i++) {
3358 r = archive_entry_acl_add_entry(ae,
3359 acls[i].type, acls[i].permset, acls[i].tag,
3360 acls[i].qual, acls[i].name);
3361 if (r != 0) {
3362 ret = 1;
3363 failure_start(file, line, "type=%#010x, "
3364 "permset=%#010x, tag=%d, qual=%d name=%s",
3365 (unsigned int)acls[i].type,
3366 (unsigned int)acls[i].permset, acls[i].tag,
3367 acls[i].qual, acls[i].name);
3368 failure_finish(NULL);
3369 }
3370 }
3371
3372 return (ret);
3373 }
3374
3375 static int
archive_test_acl_match(struct archive_test_acl_t * acl,int type,int permset,int tag,int qual,const char * name)3376 archive_test_acl_match(struct archive_test_acl_t *acl, int type, int permset,
3377 int tag, int qual, const char *name)
3378 {
3379 if (type != acl->type)
3380 return (0);
3381 if (permset != acl->permset)
3382 return (0);
3383 if (tag != acl->tag)
3384 return (0);
3385 if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ)
3386 return (1);
3387 if (tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ)
3388 return (1);
3389 if (tag == ARCHIVE_ENTRY_ACL_EVERYONE)
3390 return (1);
3391 if (tag == ARCHIVE_ENTRY_ACL_OTHER)
3392 return (1);
3393 if (qual != acl->qual)
3394 return (0);
3395 if (name == NULL) {
3396 if (acl->name == NULL || acl->name[0] == '\0')
3397 return (1);
3398 return (0);
3399 }
3400 if (acl->name == NULL) {
3401 if (name[0] == '\0')
3402 return (1);
3403 return (0);
3404 }
3405 return (0 == strcmp(name, acl->name));
3406 }
3407
3408 /* Compare ACLs */
3409 int
assertion_entry_compare_acls(const char * file,int line,struct archive_entry * ae,struct archive_test_acl_t * acls,int cnt,int want_type,int mode)3410 assertion_entry_compare_acls(const char *file, int line,
3411 struct archive_entry *ae, struct archive_test_acl_t *acls, int cnt,
3412 int want_type, int mode)
3413 {
3414 int *marker;
3415 int i, r, n, ret;
3416 int type, permset, tag, qual;
3417 int matched;
3418 const char *name;
3419
3420 assertion_count(file, line);
3421
3422 ret = 0;
3423 n = 0;
3424 marker = malloc(sizeof(marker[0]) * cnt);
3425
3426 for (i = 0; i < cnt; i++) {
3427 if ((acls[i].type & want_type) != 0) {
3428 marker[n] = i;
3429 n++;
3430 }
3431 }
3432
3433 if (n == 0) {
3434 failure_start(file, line, "No ACL's to compare, type mask: %d",
3435 want_type);
3436 return (1);
3437 }
3438
3439 while (0 == (r = archive_entry_acl_next(ae, want_type,
3440 &type, &permset, &tag, &qual, &name))) {
3441 for (i = 0, matched = 0; i < n && !matched; i++) {
3442 if (archive_test_acl_match(&acls[marker[i]], type,
3443 permset, tag, qual, name)) {
3444 /* We found a match; remove it. */
3445 marker[i] = marker[n - 1];
3446 n--;
3447 matched = 1;
3448 }
3449 }
3450 if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS
3451 && tag == ARCHIVE_ENTRY_ACL_USER_OBJ) {
3452 if (!matched) {
3453 failure_start(file, line, "No match for "
3454 "user_obj perm");
3455 failure_finish(NULL);
3456 ret = 1;
3457 }
3458 if ((permset << 6) != (mode & 0700)) {
3459 failure_start(file, line, "USER_OBJ permset "
3460 "(%02o) != user mode (%02o)",
3461 (unsigned int)permset,
3462 (unsigned int)(07 & (mode >> 6)));
3463 failure_finish(NULL);
3464 ret = 1;
3465 }
3466 } else if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS
3467 && tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ) {
3468 if (!matched) {
3469 failure_start(file, line, "No match for "
3470 "group_obj perm");
3471 failure_finish(NULL);
3472 ret = 1;
3473 }
3474 if ((permset << 3) != (mode & 0070)) {
3475 failure_start(file, line, "GROUP_OBJ permset "
3476 "(%02o) != group mode (%02o)",
3477 (unsigned int)permset,
3478 (unsigned int)(07 & (mode >> 3)));
3479 failure_finish(NULL);
3480 ret = 1;
3481 }
3482 } else if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS
3483 && tag == ARCHIVE_ENTRY_ACL_OTHER) {
3484 if (!matched) {
3485 failure_start(file, line, "No match for "
3486 "other perm");
3487 failure_finish(NULL);
3488 ret = 1;
3489 }
3490 if ((permset << 0) != (mode & 0007)) {
3491 failure_start(file, line, "OTHER permset "
3492 "(%02o) != other mode (%02o)",
3493 (unsigned int)permset,
3494 (unsigned int)mode & 07);
3495 failure_finish(NULL);
3496 ret = 1;
3497 }
3498 } else if (matched != 1) {
3499 failure_start(file, line, "Could not find match for "
3500 "ACL (type=%#010x,permset=%#010x,tag=%d,qual=%d,"
3501 "name=``%s'')", (unsigned int)type,
3502 (unsigned int)permset, tag, qual, name);
3503 failure_finish(NULL);
3504 ret = 1;
3505 }
3506 }
3507 if (r != ARCHIVE_EOF) {
3508 failure_start(file, line, "Should not exit before EOF");
3509 failure_finish(NULL);
3510 ret = 1;
3511 }
3512 if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0 &&
3513 (mode_t)(mode & 0777) != (archive_entry_mode(ae) & 0777)) {
3514 failure_start(file, line, "Mode (%02o) and entry mode (%02o) "
3515 "mismatch", (unsigned int)mode,
3516 (unsigned int)archive_entry_mode(ae));
3517 failure_finish(NULL);
3518 ret = 1;
3519 }
3520 if (n != 0) {
3521 failure_start(file, line, "Could not find match for ACL "
3522 "(type=%#010x,permset=%#010x,tag=%d,qual=%d,name=``%s'')",
3523 (unsigned int)acls[marker[0]].type,
3524 (unsigned int)acls[marker[0]].permset,
3525 acls[marker[0]].tag, acls[marker[0]].qual,
3526 acls[marker[0]].name);
3527 failure_finish(NULL);
3528 ret = 1;
3529 /* Number of ACLs not matched should == 0 */
3530 }
3531 free(marker);
3532 return (ret);
3533 }
3534 #endif /* !defined(PROGRAM) */
3535
3536 /*
3537 *
3538 * TEST management
3539 *
3540 */
3541
3542 /*
3543 * "list.h" is simply created by "grep DEFINE_TEST test_*.c"; it has
3544 * a line like
3545 * DEFINE_TEST(test_function)
3546 * for each test.
3547 */
3548 struct test_list_t
3549 {
3550 void (*func)(void);
3551 const char *name;
3552 int failures;
3553 };
3554
3555 /* Use "list.h" to declare all of the test functions. */
3556 #undef DEFINE_TEST
3557 #define DEFINE_TEST(name) void name(void);
3558 #include "list.h"
3559
3560 /* Use "list.h" to create a list of all tests (functions and names). */
3561 #undef DEFINE_TEST
3562 #define DEFINE_TEST(n) { n, #n, 0 },
3563 static struct test_list_t tests[] = {
3564 #include "list.h"
3565 };
3566
3567 /*
3568 * Summarize repeated failures in the just-completed test.
3569 */
3570 static void
test_summarize(int failed,int skips_num)3571 test_summarize(int failed, int skips_num)
3572 {
3573 unsigned int i;
3574
3575 switch (verbosity) {
3576 case VERBOSITY_SUMMARY_ONLY:
3577 printf(failed ? "E" : ".");
3578 fflush(stdout);
3579 break;
3580 case VERBOSITY_PASSFAIL:
3581 printf(failed ? "FAIL\n" : skips_num ? "skipped\n" : "ok\n");
3582 break;
3583 }
3584
3585 log_console = (verbosity == VERBOSITY_LIGHT_REPORT);
3586
3587 for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {
3588 if (failed_lines[i].count > 1 && !failed_lines[i].skip)
3589 logprintf("%s:%u: Summary: Failed %d times\n",
3590 failed_filename, i, failed_lines[i].count);
3591 }
3592 /* Clear the failure history for the next file. */
3593 failed_filename = NULL;
3594 memset(failed_lines, 0, sizeof(failed_lines));
3595 }
3596
3597 /*
3598 * Set or unset environment variable.
3599 */
3600 static void
set_environment(const char * key,const char * value)3601 set_environment(const char *key, const char *value)
3602 {
3603
3604 #if defined(_WIN32) && !defined(__CYGWIN__)
3605 if (!SetEnvironmentVariable(key, value)) {
3606 fprintf(stderr, "SetEnvironmentVariable failed with %d\n",
3607 (int)GetLastError());
3608 }
3609 #else
3610 if (value == NULL) {
3611 if (unsetenv(key) == -1)
3612 fprintf(stderr, "unsetenv: %s\n", strerror(errno));
3613 } else {
3614 if (setenv(key, value, 1) == -1)
3615 fprintf(stderr, "setenv: %s\n", strerror(errno));
3616 }
3617 #endif
3618 }
3619
3620 /*
3621 * Enforce C locale for (sub)processes.
3622 */
3623 static void
set_c_locale(void)3624 set_c_locale(void)
3625 {
3626 static const char *lcs[] = {
3627 "LC_ADDRESS",
3628 "LC_ALL",
3629 "LC_COLLATE",
3630 "LC_CTYPE",
3631 "LC_IDENTIFICATION",
3632 "LC_MEASUREMENT",
3633 "LC_MESSAGES",
3634 "LC_MONETARY",
3635 "LC_NAME",
3636 "LC_NUMERIC",
3637 "LC_PAPER",
3638 "LC_TELEPHONE",
3639 "LC_TIME",
3640 NULL
3641 };
3642 size_t i;
3643
3644 setlocale(LC_ALL, "C");
3645 set_environment("LANG", "C");
3646 for (i = 0; lcs[i] != NULL; i++)
3647 set_environment(lcs[i], NULL);
3648 }
3649
3650 /*
3651 * Actually run a single test, with appropriate setup and cleanup.
3652 */
3653 static int
test_run(int i,const char * tmpdir)3654 test_run(int i, const char *tmpdir)
3655 {
3656 #ifdef PATH_MAX
3657 char workdir[PATH_MAX * 2];
3658 #else
3659 char workdir[1024 * 2];
3660 #endif
3661 char logfilename[256];
3662 int failures_before = failures;
3663 int skips_before = skips;
3664 int tmp;
3665 mode_t oldumask;
3666
3667 switch (verbosity) {
3668 case VERBOSITY_SUMMARY_ONLY: /* No per-test reports at all */
3669 break;
3670 case VERBOSITY_PASSFAIL: /* rest of line will include ok/FAIL marker */
3671 printf("%3d: %-64s", i, tests[i].name);
3672 fflush(stdout);
3673 break;
3674 default: /* Title of test, details will follow */
3675 printf("%3d: %s\n", i, tests[i].name);
3676 }
3677
3678 /* Chdir to the top-level work directory. */
3679 if (!assertChdir(tmpdir)) {
3680 fprintf(stderr,
3681 "ERROR: Can't chdir to top work dir %s\n", tmpdir);
3682 exit(1);
3683 }
3684 /* Create a log file for this test. */
3685 tmp = snprintf(logfilename, sizeof(logfilename), "%s.log", tests[i].name);
3686 if (tmp < 0) {
3687 fprintf(stderr,
3688 "ERROR can't create %s.log: %s\n",
3689 tests[i].name, strerror(errno));
3690 exit(1);
3691 }
3692 if ((size_t)tmp >= sizeof(logfilename)) {
3693 fprintf(stderr,
3694 "ERROR can't create %s.log: Name too long. "
3695 "Length %d; Max allowed length %zu\n",
3696 tests[i].name, tmp, sizeof(logfilename) - 1);
3697 exit(1);
3698 }
3699 logfile = fopen(logfilename, "w");
3700 fprintf(logfile, "%s\n\n", tests[i].name);
3701 /* Chdir() to a work dir for this specific test. */
3702 tmp = snprintf(workdir,
3703 sizeof(workdir), "%s/%s", tmpdir, tests[i].name);
3704 if (tmp < 0) {
3705 fprintf(stderr,
3706 "ERROR can't create %s/%s: %s\n",
3707 tmpdir, tests[i].name, strerror(errno));
3708 exit(1);
3709 }
3710 if ((size_t)tmp >= sizeof(workdir)) {
3711 fprintf(stderr,
3712 "ERROR can't create %s/%s: Path too long. "
3713 "Length %d; Max allowed length %zu\n",
3714 tmpdir, tests[i].name, tmp, sizeof(workdir) - 1);
3715 exit(1);
3716 }
3717 testworkdir = workdir;
3718 if (!assertMakeDir(testworkdir, 0755) ||
3719 #ifdef RUN_TEST_UNPRIV
3720 (tuser != NULL && !assertChown(testworkdir, tuid, tgid)) ||
3721 #endif
3722 !assertChdir(testworkdir)) {
3723 fprintf(stderr,
3724 "ERROR: Can't chdir to work dir %s\n", testworkdir);
3725 exit(1);
3726 }
3727 /* Explicitly reset the locale before each test. */
3728 set_c_locale();
3729 /* Record the umask before we run the test. */
3730 umask(oldumask = umask(0));
3731 #ifdef RUN_TEST_UNPRIV
3732 /*
3733 * Temporarily drop privileges.
3734 */
3735 if (tuser != NULL) {
3736 (void)setegid(tuid);
3737 (void)seteuid(tuid);
3738 }
3739 #endif
3740 /*
3741 * Run the actual test.
3742 */
3743 (*tests[i].func)();
3744 #ifdef RUN_TEST_UNPRIV
3745 /*
3746 * Restore original credentials.
3747 */
3748 if (tuser != NULL) {
3749 (void)seteuid(ouid);
3750 (void)setegid(ogid);
3751 }
3752 #endif
3753 /*
3754 * Clean up and report afterwards.
3755 */
3756 testworkdir = NULL;
3757 /* Restore umask */
3758 umask(oldumask);
3759 /* Reset locale. */
3760 set_c_locale();
3761 /* Reset directory. */
3762 if (!assertChdir(tmpdir)) {
3763 fprintf(stderr, "ERROR: Couldn't chdir to temp dir %s\n",
3764 tmpdir);
3765 exit(1);
3766 }
3767 /* Report per-test summaries. */
3768 tests[i].failures = failures - failures_before;
3769 test_summarize(tests[i].failures, skips - skips_before);
3770 /* Close the per-test log file. */
3771 fclose(logfile);
3772 logfile = NULL;
3773 /* If there were no failures, we can remove the work dir and logfile. */
3774 if (tests[i].failures == 0) {
3775 if (!keep_temp_files && assertChdir(tmpdir)) {
3776 #if defined(_WIN32) && !defined(__CYGWIN__)
3777 /* Make sure not to leave empty directories.
3778 * Sometimes a processing of closing files used by tests
3779 * is not done, then rmdir will be failed and it will
3780 * leave a empty test directory. So we should wait a few
3781 * seconds and retry rmdir. */
3782 int r, t;
3783 for (t = 0; t < 10; t++) {
3784 if (t > 0)
3785 Sleep(1000);
3786 r = systemf("rmdir /S /Q %s", tests[i].name);
3787 if (r == 0)
3788 break;
3789 }
3790 systemf("del %s", logfilename);
3791 #else
3792 systemf("rm -rf %s", tests[i].name);
3793 systemf("rm %s", logfilename);
3794 #endif
3795 }
3796 }
3797 /* Return appropriate status. */
3798 return (tests[i].failures);
3799 }
3800
3801 /*
3802 *
3803 *
3804 * MAIN and support routines.
3805 *
3806 *
3807 */
3808
3809 static void
list_tests(void)3810 list_tests(void)
3811 {
3812 static const int limit = nitems(tests);
3813 int i;
3814
3815 for (i = 0; i < limit; i++)
3816 printf(" %d: %s\n", i, tests[i].name);
3817 }
3818
3819 static void
usage(const char * program)3820 usage(const char *program)
3821 {
3822
3823 printf("Usage: %s [options] <test> <test> ...\n", program);
3824 printf("Default is to run all tests.\n");
3825 printf("Otherwise, specify tests by name or number.\n");
3826 printf("Options:\n");
3827 printf(" -d Dump core after any failure, for debugging.\n");
3828 printf(" -k Keep all temp files.\n");
3829 printf(" Default: temp files for successful tests deleted.\n");
3830 printf(" -l List available tests and exit, ignoring all other.\n");
3831 printf(" options and arguments.\n");
3832 #ifdef PROGRAM
3833 printf(" -p <path> Path to executable to be tested.\n");
3834 printf(" Default: path taken from " ENVBASE " environment variable.\n");
3835 #endif
3836 printf(" -q Quiet.\n");
3837 printf(" -r <dir> Path to dir containing reference files.\n");
3838 printf(" Default: Current directory.\n");
3839 printf(" -s Exit with code 2 if any tests were skipped.\n");
3840 printf(" -u Keep running specified tests until one fails.\n");
3841 printf(" -v Verbose.\n");
3842 printf("Available tests:\n");
3843 list_tests();
3844 exit(1);
3845 }
3846
3847 static char *
get_refdir(const char * d)3848 get_refdir(const char *d)
3849 {
3850 size_t tried_size, buff_size;
3851 char *buff, *tried, *pwd = NULL, *p = NULL;
3852
3853 #ifdef PATH_MAX
3854 buff_size = PATH_MAX;
3855 #else
3856 buff_size = 8192;
3857 #endif
3858 buff = calloc(buff_size, 1);
3859 if (buff == NULL) {
3860 fprintf(stderr, "Unable to allocate memory\n");
3861 exit(1);
3862 }
3863
3864 /* Allocate a buffer to hold the various directories we checked. */
3865 tried_size = buff_size * 2;
3866 tried = calloc(tried_size, 1);
3867 if (tried == NULL) {
3868 fprintf(stderr, "Unable to allocate memory\n");
3869 exit(1);
3870 }
3871
3872 /* If a dir was specified, try that */
3873 if (d != NULL) {
3874 pwd = NULL;
3875 snprintf(buff, buff_size, "%s", d);
3876 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3877 if (p != NULL) goto success;
3878 strncat(tried, buff, tried_size - strlen(tried) - 1);
3879 strncat(tried, "\n", tried_size - strlen(tried) - 1);
3880 goto failure;
3881 }
3882
3883 /* Get the current dir. */
3884 #if defined(PATH_MAX) && !defined(__GLIBC__)
3885 pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */
3886 #else
3887 pwd = getcwd(NULL, 0);
3888 #endif
3889 while (pwd[strlen(pwd) - 1] == '\n')
3890 pwd[strlen(pwd) - 1] = '\0';
3891
3892 /* Look for a known file. */
3893 snprintf(buff, buff_size, "%s", pwd);
3894 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3895 if (p != NULL) goto success;
3896 strncat(tried, buff, tried_size - strlen(tried) - 1);
3897 strncat(tried, "\n", tried_size - strlen(tried) - 1);
3898
3899 snprintf(buff, buff_size, "%s/test", pwd);
3900 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3901 if (p != NULL) goto success;
3902 strncat(tried, buff, tried_size - strlen(tried) - 1);
3903 strncat(tried, "\n", tried_size - strlen(tried) - 1);
3904
3905 #if defined(LIBRARY)
3906 snprintf(buff, buff_size, "%s/%s/test", pwd, LIBRARY);
3907 #else
3908 snprintf(buff, buff_size, "%s/%s/test", pwd, PROGRAM);
3909 #endif
3910 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3911 if (p != NULL) goto success;
3912 strncat(tried, buff, tried_size - strlen(tried) - 1);
3913 strncat(tried, "\n", tried_size - strlen(tried) - 1);
3914
3915 #if defined(PROGRAM_ALIAS)
3916 snprintf(buff, buff_size, "%s/%s/test", pwd, PROGRAM_ALIAS);
3917 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3918 if (p != NULL) goto success;
3919 strncat(tried, buff, tried_size - strlen(tried) - 1);
3920 strncat(tried, "\n", tried_size - strlen(tried) - 1);
3921 #endif
3922
3923 if (memcmp(pwd, "/usr/obj", 8) == 0) {
3924 snprintf(buff, buff_size, "%s", pwd + 8);
3925 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3926 if (p != NULL) goto success;
3927 strncat(tried, buff, tried_size - strlen(tried) - 1);
3928 strncat(tried, "\n", tried_size - strlen(tried) - 1);
3929
3930 snprintf(buff, buff_size, "%s/test", pwd + 8);
3931 p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);
3932 if (p != NULL) goto success;
3933 strncat(tried, buff, tried_size - strlen(tried) - 1);
3934 strncat(tried, "\n", tried_size - strlen(tried) - 1);
3935 }
3936
3937 failure:
3938 printf("Unable to locate known reference file %s\n", KNOWNREF);
3939 printf(" Checked following directories:\n%s\n", tried);
3940 printf("Use -r option to specify full path to reference directory\n");
3941 #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
3942 DebugBreak();
3943 #endif
3944 exit(1);
3945
3946 success:
3947 free(p);
3948 free(pwd);
3949 free(tried);
3950
3951 /* Copy result into a fresh buffer to reduce memory usage. */
3952 p = strdup(buff);
3953 free(buff);
3954 return p;
3955 }
3956
3957 /* Filter tests against a glob pattern. Returns non-zero if test matches
3958 * pattern, zero otherwise. A '^' at the beginning of the pattern negates
3959 * the return values (i.e. returns zero for a match, non-zero otherwise.
3960 */
3961 static int
test_filter(const char * pattern,const char * test)3962 test_filter(const char *pattern, const char *test)
3963 {
3964 int retval = 0;
3965 int negate = 0;
3966 const char *p = pattern;
3967 const char *t = test;
3968
3969 if (p[0] == '^')
3970 {
3971 negate = 1;
3972 p++;
3973 }
3974
3975 while (1)
3976 {
3977 if (p[0] == '\\')
3978 p++;
3979 else if (p[0] == '*')
3980 {
3981 while (p[0] == '*')
3982 p++;
3983 if (p[0] == '\\')
3984 p++;
3985 if ((t = strchr(t, p[0])) == 0)
3986 break;
3987 }
3988 if (p[0] != t[0])
3989 break;
3990 if (p[0] == '\0') {
3991 retval = 1;
3992 break;
3993 }
3994 p++;
3995 t++;
3996 }
3997
3998 return (negate) ? !retval : retval;
3999 }
4000
4001 static int
get_test_set(int * test_set,int limit,const char * test)4002 get_test_set(int *test_set, int limit, const char *test)
4003 {
4004 int start, end;
4005 int idx = 0;
4006
4007 if (test == NULL) {
4008 /* Default: Run all tests. */
4009 for (;idx < limit; idx++)
4010 test_set[idx] = idx;
4011 return (limit);
4012 }
4013 if (*test >= '0' && *test <= '9') {
4014 const char *vp = test;
4015 start = 0;
4016 while (*vp >= '0' && *vp <= '9') {
4017 start *= 10;
4018 start += *vp - '0';
4019 ++vp;
4020 }
4021 if (*vp == '\0') {
4022 end = start;
4023 } else if (*vp == '-') {
4024 ++vp;
4025 if (*vp == '\0') {
4026 end = limit - 1;
4027 } else {
4028 end = 0;
4029 while (*vp >= '0' && *vp <= '9') {
4030 end *= 10;
4031 end += *vp - '0';
4032 ++vp;
4033 }
4034 }
4035 } else
4036 return (-1);
4037 if (start < 0 || end >= limit || start > end)
4038 return (-1);
4039 while (start <= end)
4040 test_set[idx++] = start++;
4041 } else {
4042 for (start = 0; start < limit; ++start) {
4043 const char *name = tests[start].name;
4044 if (test_filter(test, name))
4045 test_set[idx++] = start;
4046 }
4047 }
4048 return ((idx == 0)?-1:idx);
4049 }
4050
4051 int
main(int argc,char ** argv)4052 main(int argc, char **argv)
4053 {
4054 static const int limit = nitems(tests);
4055 int test_set[nitems(tests)];
4056 int i = 0, j = 0, tests_run = 0, tests_failed = 0, option;
4057 size_t testprogdir_len;
4058 size_t tmplen;
4059 #ifdef PROGRAM
4060 size_t tmp2_len;
4061 #endif
4062 time_t now;
4063 struct tm *tmptr;
4064 #if defined(HAVE_LOCALTIME_R) || defined(HAVE_LOCALTIME_S)
4065 struct tm tmbuf;
4066 #endif
4067 char *refdir_alloc = NULL;
4068 const char *progname;
4069 char **saved_argv;
4070 const char *tmp, *option_arg, *p;
4071 #ifdef PATH_MAX
4072 char tmpdir[PATH_MAX];
4073 #else
4074 char tmpdir[256];
4075 #endif
4076 char *pwd, *testprogdir, *tmp2 = NULL, *vlevel = NULL;
4077 char tmpdir_timestamp[32];
4078 #ifdef RUN_TEST_UNPRIV
4079 struct passwd *pw;
4080 #endif
4081
4082 (void)argc; /* UNUSED */
4083
4084 /* Get the current dir. */
4085 #if defined(PATH_MAX) && !defined(__GLIBC__)
4086 pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */
4087 #else
4088 pwd = getcwd(NULL, 0);
4089 #endif
4090 while (pwd[strlen(pwd) - 1] == '\n')
4091 pwd[strlen(pwd) - 1] = '\0';
4092
4093 #if defined(HAVE__CrtSetReportMode) && !defined(__WATCOMC__)
4094 /* To stop to run the default invalid parameter handler. */
4095 _set_invalid_parameter_handler(invalid_parameter_handler);
4096 /* Disable annoying assertion message box. */
4097 _CrtSetReportMode(_CRT_ASSERT, 0);
4098 #endif
4099
4100 /*
4101 * Name of this program, used to build root of our temp directory
4102 * tree.
4103 */
4104 progname = p = argv[0];
4105 testprogdir_len = strlen(progname) + 1;
4106 if ((testprogdir = malloc(testprogdir_len)) == NULL)
4107 {
4108 fprintf(stderr, "ERROR: Out of memory.");
4109 exit(1);
4110 }
4111 strncpy(testprogdir, progname, testprogdir_len);
4112 while (*p != '\0') {
4113 /* Support \ or / dir separators for Windows compat. */
4114 if (*p == '/' || *p == '\\')
4115 {
4116 progname = p + 1;
4117 i = j;
4118 }
4119 ++p;
4120 j++;
4121 }
4122 testprogdir[i] = '\0';
4123 #if defined(_WIN32) && !defined(__CYGWIN__)
4124 if (testprogdir[0] != '/' && testprogdir[0] != '\\' &&
4125 !(((testprogdir[0] >= 'a' && testprogdir[0] <= 'z') ||
4126 (testprogdir[0] >= 'A' && testprogdir[0] <= 'Z')) &&
4127 testprogdir[1] == ':' &&
4128 (testprogdir[2] == '/' || testprogdir[2] == '\\')))
4129 #else
4130 if (testprogdir[0] != '/')
4131 #endif
4132 {
4133 /* Fixup path for relative directories. */
4134 if ((testprogdir = realloc(testprogdir,
4135 strlen(pwd) + 1 + strlen(testprogdir) + 1)) == NULL)
4136 {
4137 fprintf(stderr, "ERROR: Out of memory.");
4138 exit(1);
4139 }
4140 memmove(testprogdir + strlen(pwd) + 1, testprogdir,
4141 strlen(testprogdir) + 1);
4142 memcpy(testprogdir, pwd, strlen(pwd));
4143 testprogdir[strlen(pwd)] = '/';
4144 }
4145
4146 #ifdef PROGRAM
4147 /* Get the target program from environment, if available. */
4148 testprogfile = getenv(ENVBASE);
4149 #endif
4150
4151 if (getenv("TMPDIR") != NULL)
4152 tmp = getenv("TMPDIR");
4153 else if (getenv("TMP") != NULL)
4154 tmp = getenv("TMP");
4155 else if (getenv("TEMP") != NULL)
4156 tmp = getenv("TEMP");
4157 else if (getenv("TEMPDIR") != NULL)
4158 tmp = getenv("TEMPDIR");
4159 else
4160 tmp = "/tmp";
4161 tmplen = strlen(tmp);
4162 while (tmplen > 0 && tmp[tmplen - 1] == '/')
4163 tmplen--;
4164
4165 /* Allow -d to be controlled through the environment. */
4166 if (getenv(ENVBASE "_DEBUG") != NULL)
4167 dump_on_failure = 1;
4168
4169 /* Allow -v to be controlled through the environment. */
4170 if (getenv("_VERBOSITY_LEVEL") != NULL)
4171 {
4172 vlevel = getenv("_VERBOSITY_LEVEL");
4173 verbosity = atoi(vlevel);
4174 if (verbosity < VERBOSITY_SUMMARY_ONLY || verbosity > VERBOSITY_FULL)
4175 {
4176 /* Unsupported verbosity levels are silently ignored */
4177 vlevel = NULL;
4178 verbosity = VERBOSITY_PASSFAIL;
4179 }
4180 }
4181
4182 /* Get the directory holding test files from environment. */
4183 refdir = getenv(ENVBASE "_TEST_FILES");
4184
4185 /*
4186 * Parse options, without using getopt(), which isn't available
4187 * on all platforms.
4188 */
4189 ++argv; /* Skip program name */
4190 while (*argv != NULL) {
4191 if (**argv != '-')
4192 break;
4193 p = *argv++;
4194 ++p; /* Skip '-' */
4195 while (*p != '\0') {
4196 option = *p++;
4197 option_arg = NULL;
4198 /* If 'opt' takes an argument, parse that. */
4199 if (option == 'p' || option == 'r') {
4200 if (*p != '\0')
4201 option_arg = p;
4202 else if (*argv == NULL) {
4203 fprintf(stderr,
4204 "Option -%c requires argument.\n",
4205 option);
4206 usage(progname);
4207 } else
4208 option_arg = *argv++;
4209 p = ""; /* End of this option word. */
4210 }
4211
4212 /* Now, handle the option. */
4213 switch (option) {
4214 case 'd':
4215 dump_on_failure = 1;
4216 break;
4217 case 'k':
4218 keep_temp_files = 1;
4219 break;
4220 case 'l':
4221 list_tests();
4222 exit(0);
4223 break;
4224 case 'p':
4225 #ifdef PROGRAM
4226 testprogfile = option_arg;
4227 #else
4228 fprintf(stderr, "-p option not permitted\n");
4229 usage(progname);
4230 #endif
4231 break;
4232 case 'q':
4233 if (!vlevel)
4234 verbosity--;
4235 break;
4236 case 'r':
4237 refdir = option_arg;
4238 break;
4239 case 's':
4240 fail_if_tests_skipped = 1;
4241 break;
4242 #ifdef RUN_TEST_UNPRIV
4243 case 'U':
4244 tuser = optarg;
4245 break;
4246 #endif
4247 case 'u':
4248 until_failure++;
4249 break;
4250 case 'v':
4251 if (!vlevel)
4252 verbosity++;
4253 break;
4254 default:
4255 fprintf(stderr, "Unrecognized option '%c'\n",
4256 option);
4257 usage(progname);
4258 }
4259 }
4260 }
4261
4262 /*
4263 * Sanity-check that our options make sense.
4264 */
4265 #ifdef PROGRAM
4266 if (testprogfile == NULL)
4267 {
4268 tmp2_len = strlen(testprogdir) + 1 + strlen(PROGRAM) + 1;
4269 #if defined(_WIN32) && !defined(__CYGWIN__)
4270 tmp2_len += 4;
4271 #endif
4272 if ((tmp2 = malloc(tmp2_len)) == NULL)
4273 {
4274 fprintf(stderr, "ERROR: Out of memory.");
4275 exit(1);
4276 }
4277 strncpy(tmp2, testprogdir, tmp2_len);
4278 strncat(tmp2, "/", tmp2_len);
4279 strncat(tmp2, PROGRAM, tmp2_len);
4280 #if defined(_WIN32) && !defined(__CYGWIN__)
4281 strncat(tmp2, ".exe", tmp2_len);
4282 #endif
4283 testprogfile = tmp2;
4284 }
4285
4286 {
4287 char *testprg;
4288 size_t testprg_len;
4289 #if defined(_WIN32) && !defined(__CYGWIN__)
4290 /* Command.com sometimes rejects '/' separators. */
4291 testprg = strdup(testprogfile);
4292 for (i = 0; testprg[i] != '\0'; i++) {
4293 if (testprg[i] == '/')
4294 testprg[i] = '\\';
4295 }
4296 testprogfile = testprg;
4297 #endif
4298 /* Quote the name that gets put into shell command lines. */
4299 testprg_len = strlen(testprogfile) + 3;
4300 testprg = malloc(testprg_len);
4301 strncpy(testprg, "\"", testprg_len);
4302 strncat(testprg, testprogfile, testprg_len);
4303 strncat(testprg, "\"", testprg_len);
4304 testprog = testprg;
4305 }
4306
4307 /* Sanity check: reject a relative path for refdir. */
4308 if (refdir != NULL) {
4309 #if defined(_WIN32) && !defined(__CYGWIN__)
4310 /* TODO: probably use PathIsRelative() from <shlwapi.h>. */
4311 #else
4312 if (refdir[0] != '/') {
4313 fprintf(stderr,
4314 "ERROR: Cannot use relative path for refdir\n");
4315 exit(1);
4316 }
4317 #endif
4318 }
4319 #endif
4320
4321 #if !defined(_WIN32) && defined(SIGPIPE)
4322 { /* Ignore SIGPIPE signals */
4323 struct sigaction sa;
4324 sa.sa_handler = SIG_IGN;
4325 sigemptyset(&sa.sa_mask);
4326 sa.sa_flags = 0;
4327 sigaction(SIGPIPE, &sa, NULL);
4328 }
4329 #endif
4330
4331 #ifdef RUN_TEST_UNPRIV
4332 /*
4333 * Check if we are root, and get user to run as.
4334 */
4335 ouid = getuid();
4336 ogid = getgid();
4337 if (ouid == 0) {
4338 if ((pw = getpwnam(tuser)) == NULL) {
4339 fprintf(stderr, "ERROR: Unknown user %s\n", tuser);
4340 exit(1);
4341 }
4342 tuid = pw->pw_uid;
4343 tgid = pw->pw_gid;
4344 printf("Will switch to user %s (uid %d gid %d)\n", tuser,
4345 tuid, tgid);
4346 } else {
4347 tuser = NULL;
4348 tuid = ouid;
4349 tgid = ogid;
4350 }
4351 #endif
4352
4353 /*
4354 * Create a temp directory for the following tests.
4355 * Include the time the tests started as part of the name,
4356 * to make it easier to track the results of multiple tests.
4357 */
4358 now = time(NULL);
4359 for (i = 0; ; i++) {
4360 #if defined(HAVE_LOCALTIME_S)
4361 tmptr = localtime_s(&tmbuf, &now) ? NULL : &tmbuf;
4362 #elif defined(HAVE_LOCALTIME_R)
4363 tmptr = localtime_r(&now, &tmbuf);
4364 #else
4365 tmptr = localtime(&now);
4366 #endif
4367 strftime(tmpdir_timestamp, sizeof(tmpdir_timestamp),
4368 "%Y-%m-%dT%H.%M.%S", tmptr);
4369 if (tmplen + 1 + strlen(progname) + 1 +
4370 strlen(tmpdir_timestamp) + 1 + 3 >=
4371 nitems(tmpdir)) {
4372 fprintf(stderr,
4373 "ERROR: Temp directory pathname too long\n");
4374 exit(1);
4375 }
4376 snprintf(tmpdir, sizeof(tmpdir), "%.*s/%s.%s-%03d",
4377 (int)tmplen, tmp, progname, tmpdir_timestamp, i);
4378 if (assertMakeDir(tmpdir, 0755))
4379 break;
4380 if (i >= 999) {
4381 fprintf(stderr,
4382 "ERROR: Unable to create temp directory %s\n",
4383 tmpdir);
4384 exit(1);
4385 }
4386 }
4387
4388 /*
4389 * If the user didn't specify a directory for locating
4390 * reference files, try to find the reference files in
4391 * the "usual places."
4392 */
4393 refdir = refdir_alloc = get_refdir(refdir);
4394
4395 /*
4396 * Banner with basic information.
4397 */
4398 printf("\n");
4399 printf("If tests fail or crash, details will be in:\n");
4400 printf(" %s\n", tmpdir);
4401 printf("\n");
4402 if (verbosity > VERBOSITY_SUMMARY_ONLY) {
4403 printf("Reference files will be read from: %s\n", refdir);
4404 #ifdef PROGRAM
4405 printf("Running tests on: %s\n", testprog);
4406 #endif
4407 printf("Exercising: ");
4408 fflush(stdout);
4409 printf("%s\n", EXTRA_VERSION);
4410 } else {
4411 printf("Running ");
4412 fflush(stdout);
4413 }
4414
4415 /*
4416 * Run some or all of the individual tests.
4417 */
4418 saved_argv = argv;
4419 do {
4420 argv = saved_argv;
4421 do {
4422 int test_num;
4423
4424 test_num = get_test_set(test_set, limit, *argv);
4425 if (test_num < 0) {
4426 printf("*** INVALID Test %s\n", *argv);
4427 free(refdir_alloc);
4428 free(testprogdir);
4429 usage(progname);
4430 }
4431 for (i = 0; i < test_num; i++) {
4432 tests_run++;
4433 if (test_run(test_set[i], tmpdir)) {
4434 tests_failed++;
4435 if (until_failure)
4436 goto finish;
4437 }
4438 }
4439 if (*argv != NULL)
4440 argv++;
4441 } while (*argv != NULL);
4442 } while (until_failure);
4443
4444 finish:
4445 /* Must be freed after all tests run */
4446 free(tmp2);
4447 free(testprogdir);
4448 free(pwd);
4449
4450 /*
4451 * Report summary statistics.
4452 */
4453 if (verbosity > VERBOSITY_SUMMARY_ONLY) {
4454 printf("\n");
4455 printf("Totals:\n");
4456 printf(" Tests run: %8d\n", tests_run);
4457 printf(" Tests failed: %8d\n", tests_failed);
4458 printf(" Assertions checked:%8d\n", assertions);
4459 printf(" Assertions failed: %8d\n", failures);
4460 printf(" Skips reported: %8d\n", skips);
4461 }
4462 if (failures) {
4463 printf("\n");
4464 printf("Failing tests:\n");
4465 for (i = 0; i < limit; ++i) {
4466 if (tests[i].failures)
4467 printf(" %d: %s (%d failures)\n", i,
4468 tests[i].name, tests[i].failures);
4469 }
4470 printf("\n");
4471 printf("Details for failing tests: %s\n", tmpdir);
4472 printf("\n");
4473 } else {
4474 if (verbosity == VERBOSITY_SUMMARY_ONLY)
4475 printf("\n");
4476 printf("%d tests passed, no failures\n", tests_run);
4477 }
4478
4479 free(refdir_alloc);
4480
4481 /* If the final tmpdir is empty, we can remove it. */
4482 /* This should be the usual case when all tests succeed. */
4483 assertChdir("..");
4484 rmdir(tmpdir);
4485
4486 if (tests_failed) return 1;
4487
4488 if (fail_if_tests_skipped == 1 && skips > 0) return 2;
4489
4490 return 0;
4491 }
4492