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