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