Path: blob/main/contrib/libarchive/test_utils/test_main.c
39586 views
/*1* Copyright (c) 2003-2009 Tim Kientzle2* All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12*13* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR14* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES15* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.16* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,17* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT18* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,19* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY20* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT21* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF22* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.23*/2425#include "test.h"26#include "test_utils.h"27#ifdef HAVE_SYS_IOCTL_H28#include <sys/ioctl.h>29#endif30#ifdef HAVE_SYS_TIME_H31#include <sys/time.h>32#endif33#include <errno.h>34#ifdef HAVE_ICONV_H35#include <iconv.h>36#endif37/*38* Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.39* As the include guards don't agree, the order of include is important.40*/41#ifdef HAVE_LINUX_EXT2_FS_H42#include <linux/ext2_fs.h> /* for Linux file flags */43#endif44#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)45#include <ext2fs/ext2_fs.h> /* Linux file flags, broken on Cygwin */46#endif47#ifdef HAVE_LINUX_FS_H48#include <linux/fs.h>49#endif50#include <limits.h>51#include <locale.h>52#ifdef HAVE_SIGNAL_H53#include <signal.h>54#endif55#include <stdarg.h>56#include <time.h>5758#ifdef HAVE_SIGNAL_H59#endif60#ifdef HAVE_ACL_LIBACL_H61#include <acl/libacl.h>62#endif63#ifdef HAVE_SYS_TYPES_H64#include <sys/types.h>65#endif66#ifdef HAVE_SYS_ACL_H67#include <sys/acl.h>68#endif69#ifdef HAVE_SYS_EA_H70#include <sys/ea.h>71#endif72#ifdef HAVE_SYS_EXTATTR_H73#include <sys/extattr.h>74#endif75#if HAVE_SYS_XATTR_H76#include <sys/xattr.h>77#elif HAVE_ATTR_XATTR_H78#include <attr/xattr.h>79#endif80#ifdef HAVE_SYS_RICHACL_H81#include <sys/richacl.h>82#endif83#if HAVE_MEMBERSHIP_H84#include <membership.h>85#endif8687#ifndef nitems88#define nitems(arr) (sizeof(arr) / sizeof((arr)[0]))89#endif9091/*92*93* Windows support routines94*95* Note: Configuration is a tricky issue. Using HAVE_* feature macros96* in the test harness is dangerous because they cover up97* configuration errors. The classic example of this is omitting a98* configure check. If libarchive and libarchive_test both look for99* the same feature macro, such errors are hard to detect. Platform100* macros (e.g., _WIN32 or __GNUC__) are a little better, but can101* easily lead to very messy code. It's best to limit yourself102* to only the most generic programming techniques in the test harness103* and thus avoid conditionals altogether. Where that's not possible,104* try to minimize conditionals by grouping platform-specific tests in105* one place (e.g., test_acl_freebsd) or by adding new assert()106* functions (e.g., assertMakeHardlink()) to cover up platform107* differences. Platform-specific coding in libarchive_test is often108* a symptom that some capability is missing from libarchive itself.109*/110#if defined(_WIN32) && !defined(__CYGWIN__)111#include <io.h>112#include <direct.h>113#include <windows.h>114#ifndef F_OK115#define F_OK (0)116#endif117#ifndef S_ISDIR118#define S_ISDIR(m) ((m) & _S_IFDIR)119#endif120#ifndef S_ISREG121#define S_ISREG(m) ((m) & _S_IFREG)122#endif123#if !defined(__BORLANDC__)124#define access _access125#undef chdir126#define chdir _chdir127#undef chmod128#define chmod _chmod129#endif130#ifndef fileno131#define fileno _fileno132#endif133/*#define fstat _fstat64*/134#if !defined(__BORLANDC__)135#define getcwd _getcwd136#endif137#define lstat stat138/*#define lstat _stat64*/139/*#define stat _stat64*/140#define rmdir _rmdir141#if !defined(__BORLANDC__)142#define strdup _strdup143#define umask _umask144#endif145#define int64_t __int64146#endif147148#if defined(HAVE__CrtSetReportMode)149# include <crtdbg.h>150#endif151152mode_t umasked(mode_t expected_mode)153{154mode_t mode = umask(0);155umask(mode);156return expected_mode & ~mode;157}158159/* Path to working directory for current test */160const char *testworkdir;161#ifdef PROGRAM162/* Pathname of exe to be tested. */163const char *testprogfile;164/* Name of exe to use in printf-formatted command strings. */165/* On Windows, this includes leading/trailing quotes. */166const char *testprog;167#endif168169#if defined(_WIN32) && !defined(__CYGWIN__)170static void *GetFunctionKernel32(const char *);171static int my_CreateSymbolicLinkA(const char *, const char *, int);172static int my_CreateHardLinkA(const char *, const char *);173static int my_GetFileInformationByName(const char *,174BY_HANDLE_FILE_INFORMATION *);175176typedef struct _REPARSE_DATA_BUFFER {177ULONG ReparseTag;178USHORT ReparseDataLength;179USHORT Reserved;180union {181struct {182USHORT SubstituteNameOffset;183USHORT SubstituteNameLength;184USHORT PrintNameOffset;185USHORT PrintNameLength;186ULONG Flags;187WCHAR PathBuffer[1];188} SymbolicLinkReparseBuffer;189struct {190USHORT SubstituteNameOffset;191USHORT SubstituteNameLength;192USHORT PrintNameOffset;193USHORT PrintNameLength;194WCHAR PathBuffer[1];195} MountPointReparseBuffer;196struct {197UCHAR DataBuffer[1];198} GenericReparseBuffer;199} DUMMYUNIONNAME;200} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;201202static void *203GetFunctionKernel32(const char *name)204{205static HINSTANCE lib;206static int set;207if (!set) {208set = 1;209lib = LoadLibrary("kernel32.dll");210}211if (lib == NULL) {212fprintf(stderr, "Can't load kernel32.dll?!\n");213exit(1);214}215return (void *)GetProcAddress(lib, name);216}217218static int219my_CreateSymbolicLinkA(const char *linkname, const char *target,220int targetIsDir)221{222static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, DWORD);223DWORD attrs;224static int set;225int ret, tmpflags;226size_t llen, tlen;227int flags = 0;228char *src, *tgt, *p;229if (!set) {230set = 1;231f = GetFunctionKernel32("CreateSymbolicLinkA");232}233if (f == NULL)234return (0);235236tlen = strlen(target);237llen = strlen(linkname);238239if (tlen == 0 || llen == 0)240return (0);241242tgt = malloc(tlen + 1);243if (tgt == NULL)244return (0);245src = malloc(llen + 1);246if (src == NULL) {247free(tgt);248return (0);249}250251/*252* Translate slashes to backslashes253*/254p = src;255while(*linkname != '\0') {256if (*linkname == '/')257*p = '\\';258else259*p = *linkname;260linkname++;261p++;262}263*p = '\0';264265p = tgt;266while(*target != '\0') {267if (*target == '/')268*p = '\\';269else270*p = *target;271target++;272p++;273}274*p = '\0';275276/*277* Each test has to specify if a file or a directory symlink278* should be created.279*/280if (targetIsDir) {281#if defined(SYMBOLIC_LINK_FLAG_DIRECTORY)282flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;283#else284flags |= 0x1;285#endif286}287288#if defined(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)289tmpflags = flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;290#else291tmpflags = flags | 0x2;292#endif293/*294* Windows won't overwrite existing links295*/296attrs = GetFileAttributesA(linkname);297if (attrs != INVALID_FILE_ATTRIBUTES) {298if (attrs & FILE_ATTRIBUTE_DIRECTORY)299RemoveDirectoryA(linkname);300else301DeleteFileA(linkname);302}303304ret = (*f)(src, tgt, tmpflags);305/*306* Prior to Windows 10 the SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE307* is not understood308*/309if (!ret)310ret = (*f)(src, tgt, flags);311312free(src);313free(tgt);314return (ret);315}316317static int318my_CreateHardLinkA(const char *linkname, const char *target)319{320static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, LPSECURITY_ATTRIBUTES);321static int set;322if (!set) {323set = 1;324f = GetFunctionKernel32("CreateHardLinkA");325}326return f == NULL ? 0 : (*f)(linkname, target, NULL);327}328329static int330my_GetFileInformationByName(const char *path, BY_HANDLE_FILE_INFORMATION *bhfi)331{332HANDLE h;333int r;334335memset(bhfi, 0, sizeof(*bhfi));336h = CreateFileA(path, FILE_READ_ATTRIBUTES, 0, NULL,337OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);338if (h == INVALID_HANDLE_VALUE)339return (0);340r = GetFileInformationByHandle(h, bhfi);341CloseHandle(h);342return (r);343}344#endif345346#if defined(HAVE__CrtSetReportMode) && !defined(__WATCOMC__)347static void348invalid_parameter_handler(const wchar_t * expression,349const wchar_t * function, const wchar_t * file,350unsigned int line, uintptr_t pReserved)351{352/* nop */353// Silence unused-parameter compiler warnings.354(void)expression;355(void)function;356(void)file;357(void)line;358(void)pReserved;359}360#endif361362/*363*364* OPTIONS FLAGS365*366*/367368/* Enable core dump on failure. */369static int dump_on_failure = 0;370/* Default is to remove temp dirs and log data for successful tests. */371static int keep_temp_files = 0;372/* Default is to only return a failure code (1) if there were test failures. If enabled, exit with code 2 if there were no failures, but some tests were skipped. */373static int fail_if_tests_skipped = 0;374/* Default is to run the specified tests once and report errors. */375static int until_failure = 0;376/* Default is to just report pass/fail for each test. */377static int verbosity = 0;378#define VERBOSITY_SUMMARY_ONLY -1 /* -q */379#define VERBOSITY_PASSFAIL 0 /* Default */380#define VERBOSITY_LIGHT_REPORT 1 /* -v */381#define VERBOSITY_FULL 2 /* -vv */382/* A few places generate even more output for verbosity > VERBOSITY_FULL,383* mostly for debugging the test harness itself. */384/* Cumulative count of assertion failures. */385static int failures = 0;386/* Cumulative count of reported skips. */387static int skips = 0;388/* Cumulative count of assertions checked. */389static int assertions = 0;390391/* Directory where uuencoded reference files can be found. */392static const char *refdir;393394/*395* Report log information selectively to console and/or disk log.396*/397static int log_console = 0;398static FILE *logfile;399static void __LA_PRINTFLIKE(1, 0)400vlogprintf(const char *fmt, va_list ap)401{402#ifdef va_copy403va_list lfap;404va_copy(lfap, ap);405#endif406if (log_console)407vfprintf(stdout, fmt, ap);408if (logfile != NULL)409#ifdef va_copy410vfprintf(logfile, fmt, lfap);411va_end(lfap);412#else413vfprintf(logfile, fmt, ap);414#endif415}416417static void __LA_PRINTFLIKE(1, 2)418logprintf(const char *fmt, ...)419{420va_list ap;421va_start(ap, fmt);422vlogprintf(fmt, ap);423va_end(ap);424}425426/* Set up a message to display only if next assertion fails. */427static char msgbuff[4096];428static const char *msg, *nextmsg;429void430failure(const char *fmt, ...)431{432va_list ap;433if (fmt == NULL) {434nextmsg = NULL;435} else {436va_start(ap, fmt);437vsnprintf(msgbuff, sizeof(msgbuff), fmt, ap);438va_end(ap);439nextmsg = msgbuff;440}441}442443/*444* Copy arguments into file-local variables.445* This was added to permit vararg assert() functions without needing446* variadic wrapper macros. Turns out that the vararg capability is almost447* never used, so almost all of the vararg assertions can be simplified448* by removing the vararg capability and reworking the wrapper macro to449* pass __FILE__, __LINE__ directly into the function instead of using450* this hook. I suspect this machinery is used so rarely that we451* would be better off just removing it entirely. That would simplify452* the code here noticeably.453*/454static const char *skipping_filename;455static int skipping_line;456void skipping_setup(const char *filename, int line)457{458skipping_filename = filename;459skipping_line = line;460}461462/* Called at the beginning of each assert() function. */463static void464assertion_count(const char *file, int line)465{466(void)file; /* UNUSED */467(void)line; /* UNUSED */468++assertions;469/* Proper handling of "failure()" message. */470msg = nextmsg;471nextmsg = NULL;472/* Uncomment to print file:line after every assertion.473* Verbose, but occasionally useful in tracking down crashes. */474/* printf("Checked %s:%d\n", file, line); */475}476477/*478* For each test source file, we remember how many times each479* assertion was reported. Cleared before each new test,480* used by test_summarize().481*/482static struct line {483int count;484int skip;485} failed_lines[10000];486static const char *failed_filename;487488/* Count this failure, setup up log destination and handle initial report. */489static void __LA_PRINTFLIKE(3, 4)490failure_start(const char *filename, int line, const char *fmt, ...)491{492va_list ap;493494/* Record another failure for this line. */495++failures;496failed_filename = filename;497failed_lines[line].count++;498499/* Determine whether to log header to console. */500switch (verbosity) {501case VERBOSITY_LIGHT_REPORT:502log_console = (failed_lines[line].count < 2);503break;504default:505log_console = (verbosity >= VERBOSITY_FULL);506}507508/* Log file:line header for this failure */509va_start(ap, fmt);510#if _MSC_VER511logprintf("%s(%d): ", filename, line);512#else513logprintf("%s:%d: ", filename, line);514#endif515vlogprintf(fmt, ap);516va_end(ap);517logprintf("\n");518519if (msg != NULL && msg[0] != '\0') {520logprintf(" Description: %s\n", msg);521msg = NULL;522}523524/* Determine whether to log details to console. */525if (verbosity == VERBOSITY_LIGHT_REPORT)526log_console = 0;527}528529/* Complete reporting of failed tests. */530/*531* The 'extra' hook here is used by libarchive to include libarchive532* error messages with assertion failures. It could also be used533* to add strerror() output, for example. Just define the EXTRA_DUMP()534* macro appropriately.535*/536static void537failure_finish(void *extra)538{539(void)extra; /* UNUSED (maybe) */540#ifdef EXTRA_DUMP541if (extra != NULL) {542logprintf(" errno: %d\n", EXTRA_ERRNO(extra));543logprintf(" detail: %s\n", EXTRA_DUMP(extra));544}545#endif546547if (dump_on_failure) {548fprintf(stderr,549" *** forcing core dump so failure can be debugged ***\n");550abort();551}552}553554/* Inform user that we're skipping some checks. */555void556test_skipping(const char *fmt, ...)557{558char buff[1024];559va_list ap;560561va_start(ap, fmt);562vsnprintf(buff, sizeof(buff), fmt, ap);563va_end(ap);564/* Use failure() message if set. */565msg = nextmsg;566nextmsg = NULL;567/* failure_start() isn't quite right, but is awfully convenient. */568failure_start(skipping_filename, skipping_line, "SKIPPING: %s", buff);569--failures; /* Undo failures++ in failure_start() */570/* Don't failure_finish() here. */571/* Mark as skip, so doesn't count as failed test. */572failed_lines[skipping_line].skip = 1;573++skips;574}575576/*577*578* ASSERTIONS579*580*/581582/* Generic assert() just displays the failed condition. */583int584assertion_assert(const char *file, int line, int value,585const char *condition, void *extra)586{587assertion_count(file, line);588if (!value) {589failure_start(file, line, "Assertion failed: %s", condition);590failure_finish(extra);591}592return (value);593}594595/* chdir() and report any errors */596int597assertion_chdir(const char *file, int line, const char *pathname)598{599assertion_count(file, line);600if (chdir(pathname) == 0)601return (1);602failure_start(file, line, "chdir(\"%s\")", pathname);603failure_finish(NULL);604return (0);605606}607608/* change file/directory permissions and errors if it fails */609int610assertion_chmod(const char *file, int line, const char *pathname, int mode)611{612assertion_count(file, line);613if (chmod(pathname, (mode_t)mode) == 0)614return (1);615failure_start(file, line, "chmod(\"%s\", %4.o)", pathname,616(unsigned int)mode);617failure_finish(NULL);618return (0);619620}621622/* Verify two integers are equal. */623int624assertion_equal_int(const char *file, int line,625long long v1, const char *e1, long long v2, const char *e2, void *extra)626{627assertion_count(file, line);628if (v1 == v2)629return (1);630failure_start(file, line, "%s != %s", e1, e2);631logprintf(" %s=%lld (0x%llx, 0%llo)\n", e1, v1,632(unsigned long long)v1, (unsigned long long)v1);633logprintf(" %s=%lld (0x%llx, 0%llo)\n", e2, v2,634(unsigned long long)v2, (unsigned long long)v2);635failure_finish(extra);636return (0);637}638639/* Verify two pointers are equal. */640int641assertion_equal_address(const char *file, int line,642const void *v1, const char *e1, const void *v2, const char *e2, void *extra)643{644assertion_count(file, line);645if (v1 == v2)646return (1);647failure_start(file, line, "%s != %s", e1, e2);648logprintf(" %s=0x%llx\n", e1, (unsigned long long)(uintptr_t)v1);649logprintf(" %s=0x%llx\n", e2, (unsigned long long)(uintptr_t)v2);650failure_finish(extra);651return (0);652}653654/*655* Utility to convert a single UTF-8 sequence.656*/657static int658_utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)659{660static const char utf8_count[256] = {6611, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */6621, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */6631, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */6641, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */6651, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */6661, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */6671, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */6681, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */6690, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */6700, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */6710, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */6720, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */6730, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */6742, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */6753, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */6764, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */677};678int ch;679int cnt;680uint32_t wc;681682*pwc = 0;683684/* Sanity check. */685if (n == 0)686return (0);687/*688* Decode 1-4 bytes depending on the value of the first byte.689*/690ch = (unsigned char)*s;691if (ch == 0)692return (0); /* Standard: return 0 for end-of-string. */693cnt = utf8_count[ch];694695/* Invalid sequence or there are not plenty bytes. */696if (n < (size_t)cnt)697return (-1);698699/* Make a Unicode code point from a single UTF-8 sequence. */700switch (cnt) {701case 1: /* 1 byte sequence. */702*pwc = ch & 0x7f;703return (cnt);704case 2: /* 2 bytes sequence. */705if ((s[1] & 0xc0) != 0x80) return (-1);706*pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);707return (cnt);708case 3: /* 3 bytes sequence. */709if ((s[1] & 0xc0) != 0x80) return (-1);710if ((s[2] & 0xc0) != 0x80) return (-1);711wc = ((ch & 0x0f) << 12)712| ((s[1] & 0x3f) << 6)713| (s[2] & 0x3f);714if (wc < 0x800)715return (-1);/* Overlong sequence. */716break;717case 4: /* 4 bytes sequence. */718if (n < 4)719return (-1);720if ((s[1] & 0xc0) != 0x80) return (-1);721if ((s[2] & 0xc0) != 0x80) return (-1);722if ((s[3] & 0xc0) != 0x80) return (-1);723wc = ((ch & 0x07) << 18)724| ((s[1] & 0x3f) << 12)725| ((s[2] & 0x3f) << 6)726| (s[3] & 0x3f);727if (wc < 0x10000)728return (-1);/* Overlong sequence. */729break;730default:731return (-1);732}733734/* The code point larger than 0x10FFFF is not legal735* Unicode values. */736if (wc > 0x10FFFF)737return (-1);738/* Correctly gets a Unicode, returns used bytes. */739*pwc = wc;740return (cnt);741}742743static void strdump(const char *e, const char *p, int ewidth, int utf8)744{745const char *q = p;746747logprintf(" %*s = ", ewidth, e);748if (p == NULL) {749logprintf("NULL\n");750return;751}752logprintf("\"");753while (*p != '\0') {754unsigned int c = 0xff & *p++;755switch (c) {756case '\a': logprintf("\\a"); break;757case '\b': logprintf("\\b"); break;758case '\n': logprintf("\\n"); break;759case '\r': logprintf("\\r"); break;760default:761if (c >= 32 && c < 127)762logprintf("%c", (int)c);763else764logprintf("\\x%02X", c);765}766}767logprintf("\"");768logprintf(" (length %d)", q == NULL ? -1 : (int)strlen(q));769770/*771* If the current string is UTF-8, dump its code points.772*/773if (utf8) {774size_t len;775uint32_t uc;776int n;777int cnt = 0;778779p = q;780len = strlen(p);781logprintf(" [");782while ((n = _utf8_to_unicode(&uc, p, len)) > 0) {783if (p != q)784logprintf(" ");785logprintf("%04X", uc);786p += n;787len -= n;788cnt++;789}790logprintf("]");791logprintf(" (count %d", cnt);792if (n < 0) {793logprintf(",unknown %zu bytes", len);794}795logprintf(")");796797}798logprintf("\n");799}800801/* Verify two strings are equal, dump them if not. */802int803assertion_equal_string(const char *file, int line,804const char *v1, const char *e1,805const char *v2, const char *e2,806void *extra, int utf8)807{808int l1, l2;809810assertion_count(file, line);811if (v1 == v2 || (v1 != NULL && v2 != NULL && strcmp(v1, v2) == 0))812return (1);813failure_start(file, line, "%s != %s", e1, e2);814l1 = (int)strlen(e1);815l2 = (int)strlen(e2);816if (l1 < l2)817l1 = l2;818strdump(e1, v1, l1, utf8);819strdump(e2, v2, l1, utf8);820failure_finish(extra);821return (0);822}823824static void825wcsdump(const char *e, const wchar_t *w)826{827logprintf(" %s = ", e);828if (w == NULL) {829logprintf("(null)");830return;831}832logprintf("\"");833while (*w != L'\0') {834unsigned int c = *w++;835if (c >= 32 && c < 127)836logprintf("%c", (int)c);837else if (c < 256)838logprintf("\\x%02X", c);839else if (c < 0x10000)840logprintf("\\u%04X", c);841else842logprintf("\\U%08X", c);843}844logprintf("\"\n");845}846847#ifndef HAVE_WCSCMP848static int849wcscmp(const wchar_t *s1, const wchar_t *s2)850{851852while (*s1 == *s2++) {853if (*s1++ == L'\0')854return 0;855}856if (*s1 > *--s2)857return 1;858else859return -1;860}861#endif862863/* Verify that two wide strings are equal, dump them if not. */864int865assertion_equal_wstring(const char *file, int line,866const wchar_t *v1, const char *e1,867const wchar_t *v2, const char *e2,868void *extra)869{870assertion_count(file, line);871if (v1 == v2)872return (1);873if (v1 != NULL && v2 != NULL && wcscmp(v1, v2) == 0)874return (1);875failure_start(file, line, "%s != %s", e1, e2);876wcsdump(e1, v1);877wcsdump(e2, v2);878failure_finish(extra);879return (0);880}881882/*883* Pretty standard hexdump routine. As a bonus, if ref != NULL, then884* any bytes in p that differ from ref will be highlighted with '_'885* before and after the hex value.886*/887static void888hexdump(const char *p, const char *ref, size_t l, size_t offset)889{890size_t i, j;891char sep;892893if (p == NULL) {894logprintf("(null)\n");895return;896}897for(i=0; i < l; i+=16) {898logprintf("%04x", (unsigned)(i + offset));899sep = ' ';900for (j = 0; j < 16 && i + j < l; j++) {901if (ref != NULL && p[i + j] != ref[i + j])902sep = '_';903logprintf("%c%02x", sep, 0xff & (unsigned int)p[i+j]);904if (ref != NULL && p[i + j] == ref[i + j])905sep = ' ';906}907for (; j < 16; j++) {908logprintf("%c ", sep);909sep = ' ';910}911logprintf("%c", sep);912for (j=0; j < 16 && i + j < l; j++) {913int c = p[i + j];914if (c >= ' ' && c <= 126)915logprintf("%c", c);916else917logprintf(".");918}919logprintf("\n");920}921}922923/* Verify that two blocks of memory are the same, display the first924* block of differences if they're not. */925int926assertion_equal_mem(const char *file, int line,927const void *_v1, const char *e1,928const void *_v2, const char *e2,929size_t l, const char *ld, void *extra)930{931const char *v1 = (const char *)_v1;932const char *v2 = (const char *)_v2;933size_t offset;934935assertion_count(file, line);936if (v1 == v2 || (v1 != NULL && v2 != NULL && memcmp(v1, v2, l) == 0))937return (1);938if (v1 == NULL || v2 == NULL)939return (0);940941failure_start(file, line, "%s != %s", e1, e2);942logprintf(" size %s = %d\n", ld, (int)l);943/* Dump 48 bytes (3 lines) so that the first difference is944* in the second line. */945offset = 0;946while (l > 64 && memcmp(v1, v2, 32) == 0) {947/* Two lines agree, so step forward one line. */948v1 += 16;949v2 += 16;950l -= 16;951offset += 16;952}953logprintf(" Dump of %s\n", e1);954hexdump(v1, v2, l < 128 ? l : 128, offset);955logprintf(" Dump of %s\n", e2);956hexdump(v2, v1, l < 128 ? l : 128, offset);957logprintf("\n");958failure_finish(extra);959return (0);960}961962/* Verify that a block of memory is filled with the specified byte. */963int964assertion_memory_filled_with(const char *file, int line,965const void *_v1, const char *vd,966size_t l, const char *ld,967char b, const char *bd, void *extra)968{969const char *v1 = (const char *)_v1;970size_t c = 0;971size_t i;972(void)ld; /* UNUSED */973974assertion_count(file, line);975976for (i = 0; i < l; ++i) {977if (v1[i] == b) {978++c;979}980}981if (c == l)982return (1);983984failure_start(file, line, "%s (size %d) not filled with %s", vd, (int)l, bd);985logprintf(" Only %d bytes were correct\n", (int)c);986failure_finish(extra);987return (0);988}989990/* Verify that the named file exists and is empty. */991int992assertion_empty_file(const char *filename, int line, const char *f1)993{994char buff[1024];995struct stat st;996ssize_t s;997FILE *f;998999assertion_count(filename, line);10001001if (stat(f1, &st) != 0) {1002failure_start(filename, line, "Stat failed: %s", f1);1003failure_finish(NULL);1004return (0);1005}1006if (st.st_size == 0)1007return (1);10081009failure_start(filename, line, "File should be empty: %s", f1);1010logprintf(" File size: %d\n", (int)st.st_size);1011logprintf(" Contents:\n");1012f = fopen(f1, "rb");1013if (f == NULL) {1014logprintf(" Unable to open %s\n", f1);1015} else {1016s = ((off_t)sizeof(buff) < st.st_size) ?1017(ssize_t)sizeof(buff) : (ssize_t)st.st_size;1018s = fread(buff, 1, s, f);1019hexdump(buff, NULL, s, 0);1020fclose(f);1021}1022failure_finish(NULL);1023return (0);1024}10251026/* Verify that the named file exists and is not empty. */1027int1028assertion_non_empty_file(const char *filename, int line, const char *f1)1029{1030struct stat st;10311032assertion_count(filename, line);10331034if (stat(f1, &st) != 0) {1035failure_start(filename, line, "Stat failed: %s", f1);1036failure_finish(NULL);1037return (0);1038}1039if (st.st_size == 0) {1040failure_start(filename, line, "File empty: %s", f1);1041failure_finish(NULL);1042return (0);1043}1044return (1);1045}10461047/* Verify that two files have the same contents. */1048/* TODO: hexdump the first bytes that actually differ. */1049int1050assertion_equal_file(const char *filename, int line, const char *fn1, const char *fn2)1051{1052char buff1[1024];1053char buff2[1024];1054FILE *f1, *f2;1055int n1, n2;10561057assertion_count(filename, line);10581059f1 = fopen(fn1, "rb");1060f2 = fopen(fn2, "rb");1061if (f1 == NULL || f2 == NULL) {1062if (f1) fclose(f1);1063if (f2) fclose(f2);1064return (0);1065}1066for (;;) {1067n1 = (int)fread(buff1, 1, sizeof(buff1), f1);1068n2 = (int)fread(buff2, 1, sizeof(buff2), f2);1069if (n1 != n2)1070break;1071if (n1 == 0 && n2 == 0) {1072fclose(f1);1073fclose(f2);1074return (1);1075}1076if (memcmp(buff1, buff2, n1) != 0)1077break;1078}1079fclose(f1);1080fclose(f2);1081failure_start(filename, line, "Files not identical");1082logprintf(" file1=\"%s\"\n", fn1);1083logprintf(" file2=\"%s\"\n", fn2);1084failure_finish(NULL);1085return (0);1086}10871088/* Verify that the named file does exist. */1089int1090assertion_file_exists(const char *filename, int line, const char *f)1091{1092assertion_count(filename, line);10931094#if defined(_WIN32) && !defined(__CYGWIN__)1095if (!_access(f, 0))1096return (1);1097#else1098if (!access(f, F_OK))1099return (1);1100#endif1101failure_start(filename, line, "File should exist: %s", f);1102failure_finish(NULL);1103return (0);1104}11051106/* Verify that the named file doesn't exist. */1107int1108assertion_file_not_exists(const char *filename, int line, const char *f)1109{1110assertion_count(filename, line);11111112#if defined(_WIN32) && !defined(__CYGWIN__)1113if (_access(f, 0))1114return (1);1115#else1116if (access(f, F_OK))1117return (1);1118#endif1119failure_start(filename, line, "File should not exist: %s", f);1120failure_finish(NULL);1121return (0);1122}11231124/* Compare the contents of a file to a block of memory. */1125int1126assertion_file_contents(const char *filename, int line, const void *buff, int s, const char *fn)1127{1128char *contents;1129FILE *f;1130int n;11311132assertion_count(filename, line);11331134f = fopen(fn, "rb");1135if (f == NULL) {1136failure_start(filename, line,1137"File should exist: %s", fn);1138failure_finish(NULL);1139return (0);1140}1141contents = malloc(s * 2);1142n = (int)fread(contents, 1, s * 2, f);1143fclose(f);1144if (n == s && memcmp(buff, contents, s) == 0) {1145free(contents);1146return (1);1147}1148failure_start(filename, line, "File contents don't match");1149logprintf(" file=\"%s\"\n", fn);1150if (n > 0)1151hexdump(contents, buff, n > 512 ? 512 : n, 0);1152else {1153logprintf(" File empty, contents should be:\n");1154hexdump(buff, NULL, s > 512 ? 512 : s, 0);1155}1156failure_finish(NULL);1157free(contents);1158return (0);1159}11601161/* Check the contents of a text file, being tolerant of line endings. */1162int1163assertion_text_file_contents(const char *filename, int line, const char *buff, const char *fn)1164{1165char *contents;1166const char *btxt, *ftxt;1167FILE *f;1168int n, s;11691170assertion_count(filename, line);1171f = fopen(fn, "r");1172if (f == NULL) {1173failure_start(filename, line,1174"File doesn't exist: %s", fn);1175failure_finish(NULL);1176return (0);1177}1178s = (int)strlen(buff);1179contents = malloc(s * 2 + 128);1180n = (int)fread(contents, 1, s * 2 + 128 - 1, f);1181if (n >= 0)1182contents[n] = '\0';1183fclose(f);1184/* Compare texts. */1185btxt = buff;1186ftxt = (const char *)contents;1187while (*btxt != '\0' && *ftxt != '\0') {1188if (*btxt == *ftxt) {1189++btxt;1190++ftxt;1191continue;1192}1193if (btxt[0] == '\n' && ftxt[0] == '\r' && ftxt[1] == '\n') {1194/* Pass over different new line characters. */1195++btxt;1196ftxt += 2;1197continue;1198}1199break;1200}1201if (*btxt == '\0' && *ftxt == '\0') {1202free(contents);1203return (1);1204}1205failure_start(filename, line, "Contents don't match");1206logprintf(" file=\"%s\"\n", fn);1207if (n > 0) {1208hexdump(contents, buff, n, 0);1209logprintf(" expected\n");1210hexdump(buff, contents, s, 0);1211} else {1212logprintf(" File empty, contents should be:\n");1213hexdump(buff, NULL, s, 0);1214}1215failure_finish(NULL);1216free(contents);1217return (0);1218}12191220/* Verify that a text file contains the specified lines, regardless of order */1221/* This could be more efficient if we sorted both sets of lines, etc, but1222* since this is used only for testing and only ever deals with a dozen or so1223* lines at a time, this relatively crude approach is just fine. */1224int1225assertion_file_contains_lines_any_order(const char *file, int line,1226const char *pathname, const char *lines[])1227{1228char *buff;1229size_t buff_size;1230size_t expected_count, actual_count, i, j;1231char **expected = NULL;1232char *p, **actual = NULL;1233char c;1234int expected_failure = 0, actual_failure = 0;12351236assertion_count(file, line);12371238buff = slurpfile(&buff_size, "%s", pathname);1239if (buff == NULL) {1240failure_start(pathname, line, "Can't read file: %s", pathname);1241failure_finish(NULL);1242return (0);1243}12441245/* Make a copy of the provided lines and count up the expected1246* file size. */1247for (i = 0; lines[i] != NULL; ++i) {1248}1249expected_count = i;1250if (expected_count) {1251expected = calloc(expected_count, sizeof(*expected));1252if (expected == NULL) {1253failure_start(pathname, line, "Can't allocate memory");1254failure_finish(NULL);1255goto cleanup;1256}1257for (i = 0; lines[i] != NULL; ++i) {1258expected[i] = strdup(lines[i]);1259if (expected[i] == NULL) {1260failure_start(pathname, line, "Can't allocate memory");1261failure_finish(NULL);1262goto cleanup;1263}1264}1265}12661267/* Break the file into lines */1268actual_count = 0;1269for (c = '\0', p = buff; p < buff + buff_size; ++p) {1270if (*p == '\x0d' || *p == '\x0a')1271*p = '\0';1272if (c == '\0' && *p != '\0')1273++actual_count;1274c = *p;1275}1276if (actual_count) {1277actual = calloc(actual_count, sizeof(char *));1278if (actual == NULL) {1279failure_start(pathname, line, "Can't allocate memory");1280failure_finish(NULL);1281goto cleanup;1282}1283for (j = 0, p = buff; p < buff + buff_size;1284p += 1 + strlen(p)) {1285if (*p != '\0') {1286actual[j] = p;1287++j;1288}1289}1290}12911292/* Erase matching lines from both lists */1293for (i = 0; i < expected_count; ++i) {1294for (j = 0; j < actual_count; ++j) {1295if (actual[j] == NULL)1296continue;1297if (strcmp(expected[i], actual[j]) == 0) {1298free(expected[i]);1299expected[i] = NULL;1300actual[j] = NULL;1301break;1302}1303}1304}13051306/* If there's anything left, it's a failure */1307for (i = 0; i < expected_count; ++i) {1308if (expected[i] != NULL)1309++expected_failure;1310}1311for (j = 0; j < actual_count; ++j) {1312if (actual[j] != NULL)1313++actual_failure;1314}1315if (expected_failure == 0 && actual_failure == 0) {1316free(actual);1317free(expected);1318free(buff);1319return (1);1320}1321failure_start(file, line, "File doesn't match: %s", pathname);1322for (i = 0; i < expected_count; ++i) {1323if (expected[i] != NULL) {1324logprintf(" Expected but not present: %s\n", expected[i]);1325free(expected[i]);1326expected[i] = NULL;1327}1328}1329for (j = 0; j < actual_count; ++j) {1330if (actual[j] != NULL)1331logprintf(" Present but not expected: %s\n", actual[j]);1332}1333failure_finish(NULL);1334cleanup:1335free(actual);1336if (expected != NULL) {1337for (i = 0; i < expected_count; ++i)1338if (expected[i] != NULL)1339free(expected[i]);1340free(expected);1341}1342free(buff);1343return (0);1344}13451346/* Verify that a text file does not contains the specified strings */1347int1348assertion_file_contains_no_invalid_strings(const char *file, int line,1349const char *pathname, const char *strings[])1350{1351char *buff;1352int i;13531354buff = slurpfile(NULL, "%s", pathname);1355if (buff == NULL) {1356failure_start(file, line, "Can't read file: %s", pathname);1357failure_finish(NULL);1358return (0);1359}13601361for (i = 0; strings[i] != NULL; ++i) {1362if (strstr(buff, strings[i]) != NULL) {1363failure_start(file, line, "Invalid string in %s: %s", pathname,1364strings[i]);1365failure_finish(NULL);1366free(buff);1367return(0);1368}1369}13701371free(buff);1372return (0);1373}13741375/* Test that two paths point to the same file. */1376/* As a side-effect, asserts that both files exist. */1377static int1378is_hardlink(const char *file, int line,1379const char *path1, const char *path2)1380{1381#if defined(_WIN32) && !defined(__CYGWIN__)1382BY_HANDLE_FILE_INFORMATION bhfi1, bhfi2;1383int r;13841385assertion_count(file, line);1386r = my_GetFileInformationByName(path1, &bhfi1);1387if (r == 0) {1388failure_start(file, line, "File %s can't be inspected?", path1);1389failure_finish(NULL);1390return (0);1391}1392r = my_GetFileInformationByName(path2, &bhfi2);1393if (r == 0) {1394failure_start(file, line, "File %s can't be inspected?", path2);1395failure_finish(NULL);1396return (0);1397}1398return (bhfi1.dwVolumeSerialNumber == bhfi2.dwVolumeSerialNumber1399&& bhfi1.nFileIndexHigh == bhfi2.nFileIndexHigh1400&& bhfi1.nFileIndexLow == bhfi2.nFileIndexLow);1401#else1402struct stat st1, st2;1403int r;14041405assertion_count(file, line);1406r = lstat(path1, &st1);1407if (r != 0) {1408failure_start(file, line, "File should exist: %s", path1);1409failure_finish(NULL);1410return (0);1411}1412r = lstat(path2, &st2);1413if (r != 0) {1414failure_start(file, line, "File should exist: %s", path2);1415failure_finish(NULL);1416return (0);1417}1418return (st1.st_ino == st2.st_ino && st1.st_dev == st2.st_dev);1419#endif1420}14211422int1423assertion_is_hardlink(const char *file, int line,1424const char *path1, const char *path2)1425{1426if (is_hardlink(file, line, path1, path2))1427return (1);1428failure_start(file, line,1429"Files %s and %s are not hardlinked", path1, path2);1430failure_finish(NULL);1431return (0);1432}14331434int1435assertion_is_not_hardlink(const char *file, int line,1436const char *path1, const char *path2)1437{1438if (!is_hardlink(file, line, path1, path2))1439return (1);1440failure_start(file, line,1441"Files %s and %s should not be hardlinked", path1, path2);1442failure_finish(NULL);1443return (0);1444}14451446/* Verify a/b/mtime of 'pathname'. */1447/* If 'recent', verify that it's within last 10 seconds. */1448static int1449assertion_file_time(const char *file, int line,1450const char *pathname, long t, long nsec, char type, int recent)1451{1452long long filet, filet_nsec;1453int r;14541455#if defined(_WIN32) && !defined(__CYGWIN__)1456#define EPOC_TIME (116444736000000000ULL)1457FILETIME fxtime, fbirthtime, fatime, fmtime;1458ULARGE_INTEGER wintm;1459HANDLE h;1460fxtime.dwLowDateTime = 0;1461fxtime.dwHighDateTime = 0;14621463assertion_count(file, line);1464/* Note: FILE_FLAG_BACKUP_SEMANTICS applies to open1465* a directory file. If not, CreateFile() will fail when1466* the pathname is a directory. */1467h = CreateFileA(pathname, FILE_READ_ATTRIBUTES, 0, NULL,1468OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);1469if (h == INVALID_HANDLE_VALUE) {1470failure_start(file, line, "Can't access %s\n", pathname);1471failure_finish(NULL);1472return (0);1473}1474r = GetFileTime(h, &fbirthtime, &fatime, &fmtime);1475switch (type) {1476case 'a': fxtime = fatime; break;1477case 'b': fxtime = fbirthtime; break;1478case 'm': fxtime = fmtime; break;1479}1480CloseHandle(h);1481if (r == 0) {1482failure_start(file, line, "Can't GetFileTime %s\n", pathname);1483failure_finish(NULL);1484return (0);1485}1486wintm.LowPart = fxtime.dwLowDateTime;1487wintm.HighPart = fxtime.dwHighDateTime;1488filet = (wintm.QuadPart - EPOC_TIME) / 10000000;1489filet_nsec = ((wintm.QuadPart - EPOC_TIME) % 10000000) * 100;1490nsec = (nsec / 100) * 100; /* Round the request */1491#else1492struct stat st;14931494assertion_count(file, line);1495r = lstat(pathname, &st);1496if (r != 0) {1497failure_start(file, line, "Can't stat %s\n", pathname);1498failure_finish(NULL);1499return (0);1500}1501switch (type) {1502case 'a': filet = st.st_atime; break;1503case 'm': filet = st.st_mtime; break;1504case 'b': filet = 0; break;1505default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);1506exit(1);1507}1508#if defined(__FreeBSD__)1509switch (type) {1510case 'a': filet_nsec = st.st_atimespec.tv_nsec; break;1511case 'b': filet = st.st_birthtime;1512/* FreeBSD filesystems that don't support birthtime1513* (e.g., UFS1) always return -1 here. */1514if (filet == -1) {1515return (1);1516}1517filet_nsec = st.st_birthtimespec.tv_nsec; break;1518case 'm': filet_nsec = st.st_mtimespec.tv_nsec; break;1519default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);1520exit(1);1521}1522/* FreeBSD generally only stores to microsecond res, so round. */1523filet_nsec = (filet_nsec / 1000) * 1000;1524nsec = (nsec / 1000) * 1000;1525#else1526filet_nsec = nsec = 0; /* Generic POSIX only has whole seconds. */1527if (type == 'b') return (1); /* Generic POSIX doesn't have birthtime */1528#if defined(__HAIKU__)1529if (type == 'a') return (1); /* Haiku doesn't have atime. */1530#endif1531#endif1532#endif1533if (recent) {1534/* Check that requested time is up-to-date. */1535time_t now = time(NULL);1536if (filet < now - 10 || filet > now + 1) {1537failure_start(file, line,1538"File %s has %ctime %lld, %lld seconds ago\n",1539pathname, type, filet, now - filet);1540failure_finish(NULL);1541return (0);1542}1543} else if (filet != t || filet_nsec != nsec) {1544failure_start(file, line,1545"File %s has %ctime %lld.%09lld, expected %ld.%09ld",1546pathname, type, filet, filet_nsec, t, nsec);1547failure_finish(NULL);1548return (0);1549}1550return (1);1551}15521553/* Verify atime of 'pathname'. */1554int1555assertion_file_atime(const char *file, int line,1556const char *pathname, long t, long nsec)1557{1558return assertion_file_time(file, line, pathname, t, nsec, 'a', 0);1559}15601561/* Verify atime of 'pathname' is up-to-date. */1562int1563assertion_file_atime_recent(const char *file, int line, const char *pathname)1564{1565return assertion_file_time(file, line, pathname, 0, 0, 'a', 1);1566}15671568/* Verify birthtime of 'pathname'. */1569int1570assertion_file_birthtime(const char *file, int line,1571const char *pathname, long t, long nsec)1572{1573return assertion_file_time(file, line, pathname, t, nsec, 'b', 0);1574}15751576/* Verify birthtime of 'pathname' is up-to-date. */1577int1578assertion_file_birthtime_recent(const char *file, int line,1579const char *pathname)1580{1581return assertion_file_time(file, line, pathname, 0, 0, 'b', 1);1582}15831584/* Verify mode of 'pathname'. */1585int1586assertion_file_mode(const char *file, int line, const char *pathname, int expected_mode)1587{1588int mode;1589int r;15901591assertion_count(file, line);1592#if defined(_WIN32) && !defined(__CYGWIN__)1593failure_start(file, line, "assertFileMode not yet implemented for Windows");1594(void)mode; /* UNUSED */1595(void)r; /* UNUSED */1596(void)pathname; /* UNUSED */1597(void)expected_mode; /* UNUSED */1598#else1599{1600struct stat st;1601r = lstat(pathname, &st);1602mode = (int)(st.st_mode & 0777);1603}1604if (r == 0 && mode == expected_mode)1605return (1);1606failure_start(file, line, "File %s has mode %o, expected %o",1607pathname, (unsigned int)mode, (unsigned int)expected_mode);1608#endif1609failure_finish(NULL);1610return (0);1611}16121613/* Verify mtime of 'pathname'. */1614int1615assertion_file_mtime(const char *file, int line,1616const char *pathname, long t, long nsec)1617{1618return assertion_file_time(file, line, pathname, t, nsec, 'm', 0);1619}16201621/* Verify mtime of 'pathname' is up-to-date. */1622int1623assertion_file_mtime_recent(const char *file, int line, const char *pathname)1624{1625return assertion_file_time(file, line, pathname, 0, 0, 'm', 1);1626}16271628/* Verify number of links to 'pathname'. */1629int1630assertion_file_nlinks(const char *file, int line,1631const char *pathname, int nlinks)1632{1633#if defined(_WIN32) && !defined(__CYGWIN__)1634BY_HANDLE_FILE_INFORMATION bhfi;1635int r;16361637assertion_count(file, line);1638r = my_GetFileInformationByName(pathname, &bhfi);1639if (r != 0 && bhfi.nNumberOfLinks == (DWORD)nlinks)1640return (1);1641failure_start(file, line, "File %s has %jd links, expected %d",1642pathname, (intmax_t)bhfi.nNumberOfLinks, nlinks);1643failure_finish(NULL);1644return (0);1645#else1646struct stat st;1647int r;16481649assertion_count(file, line);1650r = lstat(pathname, &st);1651if (r == 0 && (int)st.st_nlink == nlinks)1652return (1);1653failure_start(file, line, "File %s has %jd links, expected %d",1654pathname, (intmax_t)st.st_nlink, nlinks);1655failure_finish(NULL);1656return (0);1657#endif1658}16591660/* Verify size of 'pathname'. */1661int1662assertion_file_size(const char *file, int line, const char *pathname, long size)1663{1664int64_t filesize;1665int r;16661667assertion_count(file, line);1668#if defined(_WIN32) && !defined(__CYGWIN__)1669{1670BY_HANDLE_FILE_INFORMATION bhfi;1671r = !my_GetFileInformationByName(pathname, &bhfi);1672filesize = ((int64_t)bhfi.nFileSizeHigh << 32) + bhfi.nFileSizeLow;1673}1674#else1675{1676struct stat st;1677r = lstat(pathname, &st);1678filesize = st.st_size;1679}1680#endif1681if (r == 0 && filesize == size)1682return (1);1683failure_start(file, line, "File %s has size %ld, expected %ld",1684pathname, (long)filesize, (long)size);1685failure_finish(NULL);1686return (0);1687}16881689/* Assert that 'pathname' is a dir. If mode >= 0, verify that too. */1690int1691assertion_is_dir(const char *file, int line, const char *pathname, int mode)1692{1693struct stat st;1694int r;16951696#if defined(_WIN32) && !defined(__CYGWIN__)1697(void)mode; /* UNUSED */1698#endif1699assertion_count(file, line);1700r = lstat(pathname, &st);1701if (r != 0) {1702failure_start(file, line, "Dir should exist: %s", pathname);1703failure_finish(NULL);1704return (0);1705}1706if (!S_ISDIR(st.st_mode)) {1707failure_start(file, line, "%s is not a dir", pathname);1708failure_finish(NULL);1709return (0);1710}1711#if !defined(_WIN32) || defined(__CYGWIN__)1712/* Windows doesn't handle permissions the same way as POSIX,1713* so just ignore the mode tests. */1714/* TODO: Can we do better here? */1715if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {1716failure_start(file, line, "Dir %s has wrong mode", pathname);1717logprintf(" Expected: 0%3o\n", (unsigned int)mode);1718logprintf(" Found: 0%3o\n", (unsigned int)st.st_mode & 07777);1719failure_finish(NULL);1720return (0);1721}1722#endif1723return (1);1724}17251726/* Verify that 'pathname' is a regular file. If 'mode' is >= 0,1727* verify that too. */1728int1729assertion_is_reg(const char *file, int line, const char *pathname, int mode)1730{1731struct stat st;1732int r;17331734#if defined(_WIN32) && !defined(__CYGWIN__)1735(void)mode; /* UNUSED */1736#endif1737assertion_count(file, line);1738r = lstat(pathname, &st);1739if (r != 0 || !S_ISREG(st.st_mode)) {1740failure_start(file, line, "File should exist: %s", pathname);1741failure_finish(NULL);1742return (0);1743}1744#if !defined(_WIN32) || defined(__CYGWIN__)1745/* Windows doesn't handle permissions the same way as POSIX,1746* so just ignore the mode tests. */1747/* TODO: Can we do better here? */1748if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {1749failure_start(file, line, "File %s has wrong mode", pathname);1750logprintf(" Expected: 0%3o\n", (unsigned int)mode);1751logprintf(" Found: 0%3o\n", (unsigned int)st.st_mode & 07777);1752failure_finish(NULL);1753return (0);1754}1755#endif1756return (1);1757}17581759/*1760* Check whether 'pathname' is a symbolic link. If 'contents' is1761* non-NULL, verify that the symlink has those contents.1762*1763* On platforms with directory symlinks, set isdir to 0 to test for a file1764* symlink and to 1 to test for a directory symlink. On other platforms1765* the variable is ignored.1766*/1767static int1768is_symlink(const char *file, int line,1769const char *pathname, const char *contents, int isdir)1770{1771#if defined(_WIN32) && !defined(__CYGWIN__)1772HANDLE h;1773DWORD inbytes;1774REPARSE_DATA_BUFFER *buf;1775BY_HANDLE_FILE_INFORMATION st;1776size_t len, len2;1777wchar_t *linknamew, *contentsw;1778const char *p;1779char *s, *pn;1780int ret = 0;1781BYTE *indata;1782const DWORD flag = FILE_FLAG_BACKUP_SEMANTICS |1783FILE_FLAG_OPEN_REPARSE_POINT;17841785/* Replace slashes with backslashes in pathname */1786pn = malloc(strlen(pathname) + 1);1787if (pn == NULL) {1788failure_start(file, line, "Can't allocate memory");1789failure_finish(NULL);1790return (0);1791}1792for (p = pathname, s = pn; *p != '\0'; p++, s++) {1793if (*p == '/')1794*s = '\\';1795else1796*s = *p;1797}1798*s = '\0';17991800h = CreateFileA(pn, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,1801flag, NULL);1802free(pn);1803if (h == INVALID_HANDLE_VALUE) {1804failure_start(file, line, "Can't access %s\n", pathname);1805failure_finish(NULL);1806return (0);1807}1808ret = GetFileInformationByHandle(h, &st);1809if (ret == 0) {1810failure_start(file, line,1811"Can't stat: %s", pathname);1812failure_finish(NULL);1813} else if ((st.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) {1814failure_start(file, line,1815"Not a symlink: %s", pathname);1816failure_finish(NULL);1817ret = 0;1818}1819if (isdir && ((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) {1820failure_start(file, line,1821"Not a directory symlink: %s", pathname);1822failure_finish(NULL);1823ret = 0;1824}1825if (!isdir &&1826((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)) {1827failure_start(file, line,1828"Not a file symlink: %s", pathname);1829failure_finish(NULL);1830ret = 0;1831}1832if (ret == 0) {1833CloseHandle(h);1834return (0);1835}18361837indata = malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);1838ret = DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, NULL, 0, indata,18391024, &inbytes, NULL);1840CloseHandle(h);1841if (ret == 0) {1842free(indata);1843failure_start(file, line,1844"Could not retrieve symlink target: %s", pathname);1845failure_finish(NULL);1846return (0);1847}18481849buf = (REPARSE_DATA_BUFFER *) indata;1850if (buf->ReparseTag != IO_REPARSE_TAG_SYMLINK) {1851free(indata);1852/* File is not a symbolic link */1853failure_start(file, line,1854"Not a symlink: %s", pathname);1855failure_finish(NULL);1856return (0);1857}18581859if (contents == NULL) {1860free(indata);1861return (1);1862}18631864len = buf->SymbolicLinkReparseBuffer.SubstituteNameLength;18651866linknamew = malloc(len + sizeof(wchar_t));1867if (linknamew == NULL) {1868free(indata);1869return (0);1870}18711872memcpy(linknamew, &((BYTE *)buf->SymbolicLinkReparseBuffer.PathBuffer)1873[buf->SymbolicLinkReparseBuffer.SubstituteNameOffset], len);1874free(indata);18751876linknamew[len / sizeof(wchar_t)] = L'\0';18771878contentsw = malloc(len + sizeof(wchar_t));1879if (contentsw == NULL) {1880free(linknamew);1881return (0);1882}18831884len2 = mbsrtowcs(contentsw, &contents, (len + sizeof(wchar_t)1885/ sizeof(wchar_t)), NULL);18861887if (len2 > 0 && wcscmp(linknamew, contentsw) != 0)1888ret = 1;18891890free(linknamew);1891free(contentsw);1892return (ret);1893#else1894char buff[300];1895struct stat st;1896ssize_t linklen;1897int r;18981899(void)isdir; /* UNUSED */1900assertion_count(file, line);1901r = lstat(pathname, &st);1902if (r != 0) {1903failure_start(file, line,1904"Symlink should exist: %s", pathname);1905failure_finish(NULL);1906return (0);1907}1908if (!S_ISLNK(st.st_mode))1909return (0);1910if (contents == NULL)1911return (1);1912linklen = readlink(pathname, buff, sizeof(buff) - 1);1913if (linklen < 0) {1914failure_start(file, line, "Can't read symlink %s", pathname);1915failure_finish(NULL);1916return (0);1917}1918buff[linklen] = '\0';1919if (strcmp(buff, contents) != 0)1920return (0);1921return (1);1922#endif1923}19241925/* Assert that path is a symlink that (optionally) contains contents. */1926int1927assertion_is_symlink(const char *file, int line,1928const char *path, const char *contents, int isdir)1929{1930if (is_symlink(file, line, path, contents, isdir))1931return (1);1932if (contents)1933failure_start(file, line, "File %s is not a symlink to %s",1934path, contents);1935else1936failure_start(file, line, "File %s is not a symlink", path);1937failure_finish(NULL);1938return (0);1939}194019411942/* Create a directory and report any errors. */1943int1944assertion_make_dir(const char *file, int line, const char *dirname, int mode)1945{1946assertion_count(file, line);1947#if defined(_WIN32) && !defined(__CYGWIN__)1948(void)mode; /* UNUSED */1949if (0 == _mkdir(dirname))1950return (1);1951#else1952if (0 == mkdir(dirname, (mode_t)mode)) {1953if (0 == chmod(dirname, (mode_t)mode)) {1954assertion_file_mode(file, line, dirname, mode);1955return (1);1956}1957}1958#endif1959failure_start(file, line, "Could not create directory %s", dirname);1960failure_finish(NULL);1961return(0);1962}19631964/* Create a file with the specified contents and report any failures. */1965int1966assertion_make_file(const char *file, int line,1967const char *path, int mode, int csize, const void *contents)1968{1969#if defined(_WIN32) && !defined(__CYGWIN__)1970/* TODO: Rework this to set file mode as well. */1971FILE *f;1972(void)mode; /* UNUSED */1973assertion_count(file, line);1974f = fopen(path, "wb");1975if (f == NULL) {1976failure_start(file, line, "Could not create file %s", path);1977failure_finish(NULL);1978return (0);1979}1980if (contents != NULL) {1981size_t wsize;19821983if (csize < 0)1984wsize = strlen(contents);1985else1986wsize = (size_t)csize;1987if (wsize != fwrite(contents, 1, wsize, f)) {1988fclose(f);1989failure_start(file, line,1990"Could not write file %s", path);1991failure_finish(NULL);1992return (0);1993}1994}1995fclose(f);1996return (1);1997#else1998int fd;1999assertion_count(file, line);2000fd = open(path, O_CREAT | O_WRONLY, mode >= 0 ? mode : 0644);2001if (fd < 0) {2002failure_start(file, line, "Could not create %s", path);2003failure_finish(NULL);2004return (0);2005}2006#ifdef HAVE_FCHMOD2007if (0 != fchmod(fd, (mode_t)mode))2008#else2009if (0 != chmod(path, (mode_t)mode))2010#endif2011{2012failure_start(file, line, "Could not chmod %s", path);2013failure_finish(NULL);2014close(fd);2015return (0);2016}2017if (contents != NULL) {2018ssize_t wsize;20192020if (csize < 0)2021wsize = (ssize_t)strlen(contents);2022else2023wsize = (ssize_t)csize;2024if (wsize != write(fd, contents, wsize)) {2025close(fd);2026failure_start(file, line,2027"Could not write to %s", path);2028failure_finish(NULL);2029close(fd);2030return (0);2031}2032}2033close(fd);2034assertion_file_mode(file, line, path, mode);2035return (1);2036#endif2037}20382039/* Create a hardlink and report any failures. */2040int2041assertion_make_hardlink(const char *file, int line,2042const char *newpath, const char *linkto)2043{2044int succeeded;20452046assertion_count(file, line);2047#if defined(_WIN32) && !defined(__CYGWIN__)2048succeeded = my_CreateHardLinkA(newpath, linkto);2049#elif HAVE_LINK2050succeeded = !link(linkto, newpath);2051#else2052succeeded = 0;2053#endif2054if (succeeded)2055return (1);2056failure_start(file, line, "Could not create hardlink");2057logprintf(" New link: %s\n", newpath);2058logprintf(" Old name: %s\n", linkto);2059failure_finish(NULL);2060return(0);2061}20622063/*2064* Create a symlink and report any failures.2065*2066* Windows symlinks need to know if the target is a directory.2067*/2068int2069assertion_make_symlink(const char *file, int line,2070const char *newpath, const char *linkto, int targetIsDir)2071{2072#if defined(_WIN32) && !defined(__CYGWIN__)2073assertion_count(file, line);2074if (my_CreateSymbolicLinkA(newpath, linkto, targetIsDir))2075return (1);2076#elif HAVE_SYMLINK2077(void)targetIsDir; /* UNUSED */2078assertion_count(file, line);2079if (0 == symlink(linkto, newpath))2080return (1);2081#else2082(void)targetIsDir; /* UNUSED */2083#endif2084failure_start(file, line, "Could not create symlink");2085logprintf(" New link: %s\n", newpath);2086logprintf(" Old name: %s\n", linkto);2087failure_finish(NULL);2088return(0);2089}20902091/* Set umask, report failures. */2092int2093assertion_umask(const char *file, int line, int mask)2094{2095assertion_count(file, line);2096(void)file; /* UNUSED */2097(void)line; /* UNUSED */2098umask((mode_t)mask);2099return (1);2100}21012102/* Set times, report failures. */2103int2104assertion_utimes(const char *file, int line, const char *pathname,2105time_t at, suseconds_t at_nsec, time_t mt, suseconds_t mt_nsec)2106{2107int r;21082109#if defined(_WIN32) && !defined(__CYGWIN__)2110#define WINTIME(sec, nsec) (((sec * 10000000LL) + EPOC_TIME)\2111+ (((nsec)/1000)*10))2112HANDLE h;2113ULARGE_INTEGER wintm;2114FILETIME fatime, fmtime;2115FILETIME *pat, *pmt;21162117assertion_count(file, line);2118h = CreateFileA(pathname,GENERIC_READ | GENERIC_WRITE,2119FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,2120FILE_FLAG_BACKUP_SEMANTICS, NULL);2121if (h == INVALID_HANDLE_VALUE) {2122failure_start(file, line, "Can't access %s\n", pathname);2123failure_finish(NULL);2124return (0);2125}21262127if (at > 0 || at_nsec > 0) {2128wintm.QuadPart = WINTIME(at, at_nsec);2129fatime.dwLowDateTime = wintm.LowPart;2130fatime.dwHighDateTime = wintm.HighPart;2131pat = &fatime;2132} else2133pat = NULL;2134if (mt > 0 || mt_nsec > 0) {2135wintm.QuadPart = WINTIME(mt, mt_nsec);2136fmtime.dwLowDateTime = wintm.LowPart;2137fmtime.dwHighDateTime = wintm.HighPart;2138pmt = &fmtime;2139} else2140pmt = NULL;2141if (pat != NULL || pmt != NULL)2142r = SetFileTime(h, NULL, pat, pmt);2143else2144r = 1;2145CloseHandle(h);2146if (r == 0) {2147failure_start(file, line, "Can't SetFileTime %s\n", pathname);2148failure_finish(NULL);2149return (0);2150}2151return (1);2152#else /* defined(_WIN32) && !defined(__CYGWIN__) */2153struct stat st;2154struct timeval times[2];21552156#if !defined(__FreeBSD__)2157mt_nsec = at_nsec = 0; /* Generic POSIX only has whole seconds. */2158#endif2159if (mt == 0 && mt_nsec == 0 && at == 0 && at_nsec == 0)2160return (1);21612162r = lstat(pathname, &st);2163if (r < 0) {2164failure_start(file, line, "Can't stat %s\n", pathname);2165failure_finish(NULL);2166return (0);2167}21682169if (mt == 0 && mt_nsec == 0) {2170mt = st.st_mtime;2171#if defined(__FreeBSD__)2172mt_nsec = st.st_mtimespec.tv_nsec;2173/* FreeBSD generally only stores to microsecond res, so round. */2174mt_nsec = (mt_nsec / 1000) * 1000;2175#endif2176}2177if (at == 0 && at_nsec == 0) {2178at = st.st_atime;2179#if defined(__FreeBSD__)2180at_nsec = st.st_atimespec.tv_nsec;2181/* FreeBSD generally only stores to microsecond res, so round. */2182at_nsec = (at_nsec / 1000) * 1000;2183#endif2184}21852186times[1].tv_sec = mt;2187times[1].tv_usec = mt_nsec / 1000;21882189times[0].tv_sec = at;2190times[0].tv_usec = at_nsec / 1000;21912192#ifdef HAVE_LUTIMES2193r = lutimes(pathname, times);2194#else2195r = utimes(pathname, times);2196#endif2197if (r < 0) {2198failure_start(file, line, "Can't utimes %s\n", pathname);2199failure_finish(NULL);2200return (0);2201}2202return (1);2203#endif /* defined(_WIN32) && !defined(__CYGWIN__) */2204}22052206/* Compare file flags */2207int2208assertion_compare_fflags(const char *file, int line, const char *patha,2209const char *pathb, int nomatch)2210{2211#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)2212struct stat sa, sb;22132214assertion_count(file, line);22152216if (stat(patha, &sa) < 0)2217return (0);2218if (stat(pathb, &sb) < 0)2219return (0);2220if (!nomatch && sa.st_flags != sb.st_flags) {2221failure_start(file, line, "File flags should be identical: "2222"%s=%#010x %s=%#010x", patha, sa.st_flags, pathb,2223sb.st_flags);2224failure_finish(NULL);2225return (0);2226}2227if (nomatch && sa.st_flags == sb.st_flags) {2228failure_start(file, line, "File flags should be different: "2229"%s=%#010x %s=%#010x", patha, sa.st_flags, pathb,2230sb.st_flags);2231failure_finish(NULL);2232return (0);2233}2234#elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) && \2235defined(FS_NODUMP_FL)) || \2236(defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \2237&& defined(EXT2_NODUMP_FL))2238int fd, r, flagsa, flagsb;22392240assertion_count(file, line);2241fd = open(patha, O_RDONLY | O_NONBLOCK);2242if (fd < 0) {2243failure_start(file, line, "Can't open %s\n", patha);2244failure_finish(NULL);2245return (0);2246}2247r = ioctl(fd,2248#ifdef FS_IOC_GETFLAGS2249FS_IOC_GETFLAGS,2250#else2251EXT2_IOC_GETFLAGS,2252#endif2253&flagsa);2254close(fd);2255if (r < 0) {2256failure_start(file, line, "Can't get flags %s\n", patha);2257failure_finish(NULL);2258return (0);2259}2260fd = open(pathb, O_RDONLY | O_NONBLOCK);2261if (fd < 0) {2262failure_start(file, line, "Can't open %s\n", pathb);2263failure_finish(NULL);2264return (0);2265}2266r = ioctl(fd,2267#ifdef FS_IOC_GETFLAGS2268FS_IOC_GETFLAGS,2269#else2270EXT2_IOC_GETFLAGS,2271#endif2272&flagsb);2273close(fd);2274if (r < 0) {2275failure_start(file, line, "Can't get flags %s\n", pathb);2276failure_finish(NULL);2277return (0);2278}2279if (!nomatch && flagsa != flagsb) {2280failure_start(file, line, "File flags should be identical: "2281"%s=%#010x %s=%#010x", patha, flagsa, pathb, flagsb);2282failure_finish(NULL);2283return (0);2284}2285if (nomatch && flagsa == flagsb) {2286failure_start(file, line, "File flags should be different: "2287"%s=%#010x %s=%#010x", patha, flagsa, pathb, flagsb);2288failure_finish(NULL);2289return (0);2290}2291#else2292(void)patha; /* UNUSED */2293(void)pathb; /* UNUSED */2294(void)nomatch; /* UNUSED */2295assertion_count(file, line);2296#endif2297return (1);2298}22992300/* Set nodump, report failures. */2301int2302assertion_set_nodump(const char *file, int line, const char *pathname)2303{2304#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)2305int r;23062307assertion_count(file, line);2308r = chflags(pathname, UF_NODUMP);2309if (r < 0) {2310failure_start(file, line, "Can't set nodump %s\n", pathname);2311failure_finish(NULL);2312return (0);2313}2314#elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) && \2315defined(FS_NODUMP_FL)) || \2316(defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \2317&& defined(EXT2_NODUMP_FL))2318int fd, r, flags;23192320assertion_count(file, line);2321fd = open(pathname, O_RDONLY | O_NONBLOCK);2322if (fd < 0) {2323failure_start(file, line, "Can't open %s\n", pathname);2324failure_finish(NULL);2325return (0);2326}2327r = ioctl(fd,2328#ifdef FS_IOC_GETFLAGS2329FS_IOC_GETFLAGS,2330#else2331EXT2_IOC_GETFLAGS,2332#endif2333&flags);2334if (r < 0) {2335failure_start(file, line, "Can't get flags %s\n", pathname);2336failure_finish(NULL);2337return (0);2338}2339#ifdef FS_NODUMP_FL2340flags |= FS_NODUMP_FL;2341#else2342flags |= EXT2_NODUMP_FL;2343#endif23442345r = ioctl(fd,2346#ifdef FS_IOC_SETFLAGS2347FS_IOC_SETFLAGS,2348#else2349EXT2_IOC_SETFLAGS,2350#endif2351&flags);2352if (r < 0) {2353failure_start(file, line, "Can't set nodump %s\n", pathname);2354failure_finish(NULL);2355return (0);2356}2357close(fd);2358#else2359(void)pathname; /* UNUSED */2360assertion_count(file, line);2361#endif2362return (1);2363}23642365#ifdef PROGRAM2366static void assert_version_id(char **qq, size_t *ss)2367{2368char *q = *qq;2369size_t s = *ss;23702371/* Version number is a series of digits and periods. */2372while (s > 0 && (*q == '.' || (*q >= '0' && *q <= '9'))) {2373++q;2374--s;2375}23762377if (q[0] == 'd' && q[1] == 'e' && q[2] == 'v') {2378q += 3;2379s -= 3;2380}23812382/* Skip a single trailing a,b,c, or d. */2383if (*q == 'a' || *q == 'b' || *q == 'c' || *q == 'd')2384++q;23852386/* Version number terminated by space. */2387failure("No space after version: ``%s''", q);2388assert(s > 1);2389failure("No space after version: ``%s''", q);2390assert(*q == ' ');23912392++q; --s;23932394*qq = q;2395*ss = s;2396}239723982399/*2400* Check program version2401*/2402void assertVersion(const char *prog, const char *base)2403{2404int r;2405char *p, *q;2406size_t s;2407size_t prog_len = strlen(base);24082409r = systemf("%s --version >version.stdout 2>version.stderr", prog);2410if (r != 0)2411r = systemf("%s -W version >version.stdout 2>version.stderr",2412prog);24132414failure("Unable to run either %s --version or %s -W version",2415prog, prog);2416if (!assert(r == 0))2417return;24182419/* --version should generate nothing to stdout. */2420assertEmptyFile("version.stderr");24212422/* Verify format of version message. */2423q = p = slurpfile(&s, "version.stdout");24242425/* Version message should start with name of program, then space. */2426assert(s > prog_len + 1);24272428failure("Version must start with '%s': ``%s''", base, p);2429if (!assertEqualMem(q, base, prog_len)) {2430free(p);2431return;2432}24332434q += prog_len; s -= prog_len;24352436assert(*q == ' ');2437q++; s--;24382439assert_version_id(&q, &s);24402441/* Separator. */2442failure("No `-' between program name and versions: ``%s''", p);2443assertEqualMem(q, "- ", 2);2444q += 2; s -= 2;24452446failure("Not long enough for libarchive version: ``%s''", p);2447assert(s > 11);24482449failure("Libarchive version must start with `libarchive': ``%s''", p);2450assertEqualMem(q, "libarchive ", 11);24512452q += 11; s -= 11;24532454assert_version_id(&q, &s);24552456/* Skip arbitrary third-party version numbers. */2457while (s > 0 && (*q == ' ' || *q == '-' || *q == '/' || *q == '.' ||2458*q == '_' || isalnum((unsigned char)*q))) {2459++q;2460--s;2461}24622463/* All terminated by end-of-line. */2464assert(s >= 1);24652466/* Skip an optional CR character (e.g., Windows) */2467failure("Version output must end with \\n or \\r\\n");24682469if (*q == '\r') { ++q; --s; }2470assertEqualMem(q, "\n", 1);24712472free(p);2473}2474#endif /* PROGRAM */24752476/*2477*2478* UTILITIES for use by tests.2479*2480*/24812482/*2483* Check whether platform supports symlinks. This is intended2484* for tests to use in deciding whether to bother testing symlink2485* support; if the platform doesn't support symlinks, there's no point2486* in checking whether the program being tested can create them.2487*2488* Note that the first time this test is called, we actually go out to2489* disk to create and verify a symlink. This is necessary because2490* symlink support is actually a property of a particular filesystem2491* and can thus vary between directories on a single system. After2492* the first call, this returns the cached result from memory, so it's2493* safe to call it as often as you wish.2494*/2495int2496canSymlink(void)2497{2498/* Remember the test result */2499static int value = 0, tested = 0;2500if (tested)2501return (value);25022503++tested;2504assertion_make_file(__FILE__, __LINE__, "canSymlink.0", 0644, 1, "a");2505/* Note: Cygwin has its own symlink() emulation that does not2506* use the Win32 CreateSymbolicLink() function. */2507#if defined(_WIN32) && !defined(__CYGWIN__)2508value = my_CreateSymbolicLinkA("canSymlink.1", "canSymlink.0", 0)2509&& is_symlink(__FILE__, __LINE__, "canSymlink.1", "canSymlink.0",25100);2511#elif HAVE_SYMLINK2512value = (0 == symlink("canSymlink.0", "canSymlink.1"))2513&& is_symlink(__FILE__, __LINE__, "canSymlink.1","canSymlink.0",25140);2515#endif2516return (value);2517}25182519/* Platform-dependent options for hiding the output of a subcommand. */2520#if defined(_WIN32) && !defined(__CYGWIN__)2521static const char *redirectArgs = ">NUL 2>NUL"; /* Win32 cmd.exe */2522#else2523static const char *redirectArgs = ">/dev/null 2>/dev/null"; /* POSIX 'sh' */2524#endif2525/*2526* Can this platform run the bzip2 program?2527*/2528int2529canBzip2(void)2530{2531static int tested = 0, value = 0;2532if (!tested) {2533tested = 1;2534if (systemf("bzip2 --help %s", redirectArgs) == 0)2535value = 1;2536}2537return (value);2538}25392540/*2541* Can this platform run the grzip program?2542*/2543int2544canGrzip(void)2545{2546static int tested = 0, value = 0;2547if (!tested) {2548tested = 1;2549if (systemf("grzip -V %s", redirectArgs) == 0)2550value = 1;2551}2552return (value);2553}25542555/*2556* Can this platform run the gzip program?2557*/2558int2559canGzip(void)2560{2561static int tested = 0, value = 0;2562if (!tested) {2563tested = 1;2564if (systemf("gzip --help %s", redirectArgs) == 0)2565value = 1;2566}2567return (value);2568}25692570/*2571* Can this platform run the lrzip program?2572*/2573int2574canRunCommand(const char *cmd)2575{2576static int tested = 0, value = 0;2577if (!tested) {2578tested = 1;2579if (systemf("%s %s", cmd, redirectArgs) == 0)2580value = 1;2581}2582return (value);2583}25842585int2586canLrzip(void)2587{2588static int tested = 0, value = 0;2589if (!tested) {2590tested = 1;2591if (systemf("lrzip -V %s", redirectArgs) == 0)2592value = 1;2593}2594return (value);2595}25962597/*2598* Can this platform run the lz4 program?2599*/2600int2601canLz4(void)2602{2603static int tested = 0, value = 0;2604if (!tested) {2605tested = 1;2606if (systemf("lz4 --help %s", redirectArgs) == 0)2607value = 1;2608}2609return (value);2610}26112612/*2613* Can this platform run the zstd program?2614*/2615int2616canZstd(void)2617{2618static int tested = 0, value = 0;2619if (!tested) {2620tested = 1;2621if (systemf("zstd --help %s", redirectArgs) == 0)2622value = 1;2623}2624return (value);2625}26262627/*2628* Can this platform run the lzip program?2629*/2630int2631canLzip(void)2632{2633static int tested = 0, value = 0;2634if (!tested) {2635tested = 1;2636if (systemf("lzip --help %s", redirectArgs) == 0)2637value = 1;2638}2639return (value);2640}26412642/*2643* Can this platform run the lzma program?2644*/2645int2646canLzma(void)2647{2648static int tested = 0, value = 0;2649if (!tested) {2650tested = 1;2651if (systemf("lzma --help %s", redirectArgs) == 0)2652value = 1;2653}2654return (value);2655}26562657/*2658* Can this platform run the lzop program?2659*/2660int2661canLzop(void)2662{2663static int tested = 0, value = 0;2664if (!tested) {2665tested = 1;2666if (systemf("lzop --help %s", redirectArgs) == 0)2667value = 1;2668}2669return (value);2670}26712672/*2673* Can this platform run the xz program?2674*/2675int2676canXz(void)2677{2678static int tested = 0, value = 0;2679if (!tested) {2680tested = 1;2681if (systemf("xz --help %s", redirectArgs) == 0)2682value = 1;2683}2684return (value);2685}26862687/*2688* Can this filesystem handle nodump flags.2689*/2690int2691canNodump(void)2692{2693#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)2694const char *path = "cannodumptest";2695struct stat sb;26962697assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);2698if (chflags(path, UF_NODUMP) < 0)2699return (0);2700if (stat(path, &sb) < 0)2701return (0);2702if (sb.st_flags & UF_NODUMP)2703return (1);2704#elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) \2705&& defined(FS_NODUMP_FL)) || \2706(defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \2707&& defined(EXT2_NODUMP_FL))2708const char *path = "cannodumptest";2709int fd, r, flags;27102711assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);2712fd = open(path, O_RDONLY | O_NONBLOCK);2713if (fd < 0)2714return (0);2715r = ioctl(fd,2716#ifdef FS_IOC_GETFLAGS2717FS_IOC_GETFLAGS,2718#else2719EXT2_IOC_GETFLAGS,2720#endif2721&flags);2722if (r < 0)2723return (0);2724#ifdef FS_NODUMP_FL2725flags |= FS_NODUMP_FL;2726#else2727flags |= EXT2_NODUMP_FL;2728#endif2729r = ioctl(fd,2730#ifdef FS_IOC_SETFLAGS2731FS_IOC_SETFLAGS,2732#else2733EXT2_IOC_SETFLAGS,2734#endif2735&flags);2736if (r < 0)2737return (0);2738close(fd);2739fd = open(path, O_RDONLY | O_NONBLOCK);2740if (fd < 0)2741return (0);2742r = ioctl(fd,2743#ifdef FS_IOC_GETFLAGS2744FS_IOC_GETFLAGS,2745#else2746EXT2_IOC_GETFLAGS,2747#endif2748&flags);2749if (r < 0)2750return (0);2751close(fd);2752#ifdef FS_NODUMP_FL2753if (flags & FS_NODUMP_FL)2754#else2755if (flags & EXT2_NODUMP_FL)2756#endif2757return (1);2758#endif2759return (0);2760}27612762/* Get extended attribute value from a path */2763void *2764getXattr(const char *path, const char *name, size_t *sizep)2765{2766void *value = NULL;2767#if ARCHIVE_XATTR_SUPPORT2768ssize_t size;2769#if ARCHIVE_XATTR_LINUX2770size = lgetxattr(path, name, NULL, 0);2771#elif ARCHIVE_XATTR_DARWIN2772size = getxattr(path, name, NULL, 0, 0, XATTR_NOFOLLOW);2773#elif ARCHIVE_XATTR_AIX2774size = lgetea(path, name, NULL, 0);2775#elif ARCHIVE_XATTR_FREEBSD2776size = extattr_get_link(path, EXTATTR_NAMESPACE_USER, name + 5,2777NULL, 0);2778#endif27792780if (size >= 0) {2781value = malloc(size);2782#if ARCHIVE_XATTR_LINUX2783size = lgetxattr(path, name, value, size);2784#elif ARCHIVE_XATTR_DARWIN2785size = getxattr(path, name, value, size, 0, XATTR_NOFOLLOW);2786#elif ARCHIVE_XATTR_AIX2787size = lgetea(path, name, value, size);2788#elif ARCHIVE_XATTR_FREEBSD2789size = extattr_get_link(path, EXTATTR_NAMESPACE_USER, name + 5,2790value, size);2791#endif2792if (size < 0) {2793free(value);2794value = NULL;2795}2796}2797if (size < 0)2798*sizep = 0;2799else2800*sizep = (size_t)size;2801#else /* !ARCHIVE_XATTR_SUPPORT */2802(void)path; /* UNUSED */2803(void)name; /* UNUSED */2804*sizep = 0;2805#endif /* !ARCHIVE_XATTR_SUPPORT */2806return (value);2807}28082809/*2810* Set extended attribute on a path2811* Returns 0 on error, 1 on success2812*/2813int2814setXattr(const char *path, const char *name, const void *value, size_t size)2815{2816#if ARCHIVE_XATTR_SUPPORT2817#if ARCHIVE_XATTR_LINUX2818if (lsetxattr(path, name, value, size, 0) == 0)2819#elif ARCHIVE_XATTR_DARWIN2820if (setxattr(path, name, value, size, 0, XATTR_NOFOLLOW) == 0)2821#elif ARCHIVE_XATTR_AIX2822if (lsetea(path, name, value, size, 0) == 0)2823#elif ARCHIVE_XATTR_FREEBSD2824if (extattr_set_link(path, EXTATTR_NAMESPACE_USER, name + 5, value,2825size) > -1)2826#else2827if (0)2828#endif2829return (1);2830#else /* !ARCHIVE_XATTR_SUPPORT */2831(void)path; /* UNUSED */2832(void)name; /* UNUSED */2833(void)value; /* UNUSED */2834(void)size; /* UNUSED */2835#endif /* !ARCHIVE_XATTR_SUPPORT */2836return (0);2837}28382839#if ARCHIVE_ACL_SUNOS2840/* Fetch ACLs on Solaris using acl() or facl() */2841void *2842sunacl_get(int cmd, int *aclcnt, int fd, const char *path)2843{2844int cnt, cntcmd;2845size_t size;2846void *aclp;28472848if (cmd == GETACL) {2849cntcmd = GETACLCNT;2850size = sizeof(aclent_t);2851}2852#if ARCHIVE_ACL_SUNOS_NFS42853else if (cmd == ACE_GETACL) {2854cntcmd = ACE_GETACLCNT;2855size = sizeof(ace_t);2856}2857#endif2858else {2859errno = EINVAL;2860*aclcnt = -1;2861return (NULL);2862}28632864aclp = NULL;2865cnt = -2;2866while (cnt == -2 || (cnt == -1 && errno == ENOSPC)) {2867if (path != NULL)2868cnt = acl(path, cntcmd, 0, NULL);2869else2870cnt = facl(fd, cntcmd, 0, NULL);28712872if (cnt > 0) {2873if (aclp == NULL)2874aclp = malloc(cnt * size);2875else2876aclp = realloc(NULL, cnt * size);2877if (aclp != NULL) {2878if (path != NULL)2879cnt = acl(path, cmd, cnt, aclp);2880else2881cnt = facl(fd, cmd, cnt, aclp);2882}2883} else {2884free(aclp);2885aclp = NULL;2886break;2887}2888}28892890*aclcnt = cnt;2891return (aclp);2892}2893#endif /* ARCHIVE_ACL_SUNOS */28942895/*2896* Set test ACLs on a path2897* Return values:2898* 0: error setting ACLs2899* ARCHIVE_TEST_ACL_TYPE_POSIX1E: POSIX.1E ACLs have been set2900* ARCHIVE_TEST_ACL_TYPE_NFS4: NFSv4 or extended ACLs have been set2901*/2902int2903setTestAcl(const char *path)2904{2905#if ARCHIVE_ACL_SUPPORT2906int r = 1;2907#if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_DARWIN2908acl_t acl;2909#endif2910#if ARCHIVE_ACL_LIBRICHACL2911struct richacl *richacl;2912#endif2913#if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_FREEBSD2914const char *acltext_posix1e = "user:1:rw-,"2915"group:15:r-x,"2916"user::rwx,"2917"group::rwx,"2918"other::r-x,"2919"mask::rwx";2920#elif ARCHIVE_ACL_SUNOS /* Solaris POSIX.1e */2921aclent_t aclp_posix1e[] = {2922{ USER_OBJ, -1, 4 | 2 | 1 },2923{ USER, 1, 4 | 2 },2924{ GROUP_OBJ, -1, 4 | 2 | 1 },2925{ GROUP, 15, 4 | 1 },2926{ CLASS_OBJ, -1, 4 | 2 | 1 },2927{ OTHER_OBJ, -1, 4 | 2 | 1 }2928};2929#endif2930#if ARCHIVE_ACL_FREEBSD /* FreeBSD NFS4 */2931const char *acltext_nfs4 = "user:1:rwpaRcs::allow:1,"2932"group:15:rxaRcs::allow:15,"2933"owner@:rwpxaARWcCos::allow,"2934"group@:rwpxaRcs::allow,"2935"everyone@:rxaRcs::allow";2936#elif ARCHIVE_ACL_LIBRICHACL2937const char *acltext_nfs4 = "owner:rwpxaARWcCoS::mask,"2938"group:rwpxaRcS::mask,"2939"other:rxaRcS::mask,"2940"user:1:rwpaRcS::allow,"2941"group:15:rxaRcS::allow,"2942"owner@:rwpxaARWcCoS::allow,"2943"group@:rwpxaRcS::allow,"2944"everyone@:rxaRcS::allow";2945#elif ARCHIVE_ACL_SUNOS_NFS4 /* Solaris NFS4 */2946ace_t aclp_nfs4[] = {2947{ 1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |2948ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS | ACE_READ_ACL |2949ACE_SYNCHRONIZE, 0, ACE_ACCESS_ALLOWED_ACE_TYPE },2950{ 15, ACE_READ_DATA | ACE_EXECUTE | ACE_READ_ATTRIBUTES |2951ACE_READ_NAMED_ATTRS | ACE_READ_ACL | ACE_SYNCHRONIZE,2952ACE_IDENTIFIER_GROUP, ACE_ACCESS_ALLOWED_ACE_TYPE },2953{ -1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |2954ACE_EXECUTE | ACE_READ_ATTRIBUTES | ACE_WRITE_ATTRIBUTES |2955ACE_READ_NAMED_ATTRS | ACE_WRITE_NAMED_ATTRS |2956ACE_READ_ACL | ACE_WRITE_ACL | ACE_WRITE_OWNER | ACE_SYNCHRONIZE,2957ACE_OWNER, ACE_ACCESS_ALLOWED_ACE_TYPE },2958{ -1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |2959ACE_EXECUTE | ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS |2960ACE_READ_ACL | ACE_SYNCHRONIZE, ACE_GROUP | ACE_IDENTIFIER_GROUP,2961ACE_ACCESS_ALLOWED_ACE_TYPE },2962{ -1, ACE_READ_DATA | ACE_EXECUTE | ACE_READ_ATTRIBUTES |2963ACE_READ_NAMED_ATTRS | ACE_READ_ACL | ACE_SYNCHRONIZE,2964ACE_EVERYONE, ACE_ACCESS_ALLOWED_ACE_TYPE }2965};2966#elif ARCHIVE_ACL_DARWIN /* Mac OS X */2967acl_entry_t aclent;2968acl_permset_t permset;2969const uid_t uid = 1;2970uuid_t uuid;2971const acl_perm_t acl_perms[] = {2972ACL_READ_DATA,2973ACL_WRITE_DATA,2974ACL_APPEND_DATA,2975ACL_EXECUTE,2976ACL_READ_ATTRIBUTES,2977ACL_READ_EXTATTRIBUTES,2978ACL_READ_SECURITY,2979#if HAVE_DECL_ACL_SYNCHRONIZE2980ACL_SYNCHRONIZE2981#endif2982};2983#endif /* ARCHIVE_ACL_DARWIN */29842985#if ARCHIVE_ACL_FREEBSD2986acl = acl_from_text(acltext_nfs4);2987failure("acl_from_text() error: %s", strerror(errno));2988if (assert(acl != NULL) == 0)2989return (0);2990#elif ARCHIVE_ACL_LIBRICHACL2991richacl = richacl_from_text(acltext_nfs4, NULL, NULL);2992failure("richacl_from_text() error: %s", strerror(errno));2993if (assert(richacl != NULL) == 0)2994return (0);2995#elif ARCHIVE_ACL_DARWIN2996acl = acl_init(1);2997failure("acl_init() error: %s", strerror(errno));2998if (assert(acl != NULL) == 0)2999return (0);3000r = acl_create_entry(&acl, &aclent);3001failure("acl_create_entry() error: %s", strerror(errno));3002if (assertEqualInt(r, 0) == 0)3003goto testacl_free;3004r = acl_set_tag_type(aclent, ACL_EXTENDED_ALLOW);3005failure("acl_set_tag_type() error: %s", strerror(errno));3006if (assertEqualInt(r, 0) == 0)3007goto testacl_free;3008r = acl_get_permset(aclent, &permset);3009failure("acl_get_permset() error: %s", strerror(errno));3010if (assertEqualInt(r, 0) == 0)3011goto testacl_free;3012for (size_t i = 0; i < nitems(acl_perms); i++) {3013r = acl_add_perm(permset, acl_perms[i]);3014failure("acl_add_perm() error: %s", strerror(errno));3015if (assertEqualInt(r, 0) == 0)3016goto testacl_free;3017}3018r = acl_set_permset(aclent, permset);3019failure("acl_set_permset() error: %s", strerror(errno));3020if (assertEqualInt(r, 0) == 0)3021goto testacl_free;3022r = mbr_uid_to_uuid(uid, uuid);3023failure("mbr_uid_to_uuid() error: %s", strerror(errno));3024if (assertEqualInt(r, 0) == 0)3025goto testacl_free;3026r = acl_set_qualifier(aclent, uuid);3027failure("acl_set_qualifier() error: %s", strerror(errno));3028if (assertEqualInt(r, 0) == 0)3029goto testacl_free;3030#endif /* ARCHIVE_ACL_DARWIN */30313032#if ARCHIVE_ACL_NFS43033#if ARCHIVE_ACL_FREEBSD3034r = acl_set_file(path, ACL_TYPE_NFS4, acl);3035acl_free(acl);3036#elif ARCHIVE_ACL_LIBRICHACL3037r = richacl_set_file(path, richacl);3038richacl_free(richacl);3039#elif ARCHIVE_ACL_SUNOS_NFS43040r = acl(path, ACE_SETACL,3041(int)(sizeof(aclp_nfs4)/sizeof(aclp_nfs4[0])), aclp_nfs4);3042#elif ARCHIVE_ACL_DARWIN3043r = acl_set_file(path, ACL_TYPE_EXTENDED, acl);3044acl_free(acl);3045#endif3046if (r == 0)3047return (ARCHIVE_TEST_ACL_TYPE_NFS4);3048#endif /* ARCHIVE_ACL_NFS4 */30493050#if ARCHIVE_ACL_POSIX1E3051#if ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_LIBACL3052acl = acl_from_text(acltext_posix1e);3053failure("acl_from_text() error: %s", strerror(errno));3054if (assert(acl != NULL) == 0)3055return (0);30563057r = acl_set_file(path, ACL_TYPE_ACCESS, acl);3058acl_free(acl);3059#elif ARCHIVE_ACL_SUNOS3060r = acl(path, SETACL,3061(int)(sizeof(aclp_posix1e)/sizeof(aclp_posix1e[0])), aclp_posix1e);3062#endif3063if (r == 0)3064return (ARCHIVE_TEST_ACL_TYPE_POSIX1E);3065else3066return (0);3067#endif /* ARCHIVE_ACL_POSIX1E */3068#if ARCHIVE_ACL_DARWIN3069testacl_free:3070acl_free(acl);3071#endif3072#endif /* ARCHIVE_ACL_SUPPORT */3073(void)path; /* UNUSED */3074return (0);3075}30763077/*3078* Sleep as needed; useful for verifying disk timestamp changes by3079* ensuring that the wall-clock time has actually changed before we3080* go back to re-read something from disk.3081*/3082void3083sleepUntilAfter(time_t t)3084{3085while (t >= time(NULL))3086#if defined(_WIN32) && !defined(__CYGWIN__)3087Sleep(500);3088#else3089sleep(1);3090#endif3091}30923093/*3094* Call standard system() call, but build up the command line using3095* sprintf() conventions.3096*/3097int3098systemf(const char *fmt, ...)3099{3100char buff[8192];3101va_list ap;3102int r;31033104va_start(ap, fmt);3105vsnprintf(buff, sizeof(buff), fmt, ap);3106if (verbosity > VERBOSITY_FULL)3107logprintf("Cmd: %s\n", buff);3108r = system(buff);3109va_end(ap);3110return (r);3111}31123113/*3114* Slurp a file into memory for ease of comparison and testing.3115* Returns size of file in 'sizep' if non-NULL, null-terminates3116* data in memory for ease of use.3117*/3118char *3119slurpfile(size_t * sizep, const char *fmt, ...)3120{3121char filename[8192];3122struct stat st;3123va_list ap;3124char *p;3125ssize_t bytes_read;3126FILE *f;3127int r;31283129va_start(ap, fmt);3130vsnprintf(filename, sizeof(filename), fmt, ap);3131va_end(ap);31323133f = fopen(filename, "rb");3134if (f == NULL) {3135/* Note: No error; non-existent file is okay here. */3136return (NULL);3137}3138r = fstat(fileno(f), &st);3139if (r != 0) {3140logprintf("Can't stat file %s\n", filename);3141fclose(f);3142return (NULL);3143}3144p = malloc((size_t)st.st_size + 1);3145if (p == NULL) {3146logprintf("Can't allocate %ld bytes of memory to read file %s\n",3147(long int)st.st_size, filename);3148fclose(f);3149return (NULL);3150}3151bytes_read = fread(p, 1, (size_t)st.st_size, f);3152if (bytes_read < st.st_size) {3153logprintf("Can't read file %s\n", filename);3154fclose(f);3155free(p);3156return (NULL);3157}3158p[st.st_size] = '\0';3159if (sizep != NULL)3160*sizep = (size_t)st.st_size;3161fclose(f);3162return (p);3163}31643165/*3166* Slurp a file into memory for ease of comparison and testing.3167* Returns size of file in 'sizep' if non-NULL, null-terminates3168* data in memory for ease of use.3169*/3170void3171dumpfile(const char *filename, void *data, size_t len)3172{3173ssize_t bytes_written;3174FILE *f;31753176f = fopen(filename, "wb");3177if (f == NULL) {3178logprintf("Can't open file %s for writing\n", filename);3179return;3180}3181bytes_written = fwrite(data, 1, len, f);3182if (bytes_written < (ssize_t)len)3183logprintf("Can't write file %s\n", filename);3184fclose(f);3185}31863187/* Read a uuencoded file from the reference directory, decode, and3188* write the result into the current directory. */3189#define VALID_UUDECODE(c) (c >= 32 && c <= 96)3190#define UUDECODE(c) (((c) - 0x20) & 0x3f)3191void3192extract_reference_file(const char *name)3193{3194char buff[1024];3195FILE *in, *out;31963197snprintf(buff, sizeof(buff), "%s/%s.uu", refdir, name);3198in = fopen(buff, "r");3199failure("Couldn't open reference file %s", buff);3200assert(in != NULL);3201if (in == NULL)3202return;3203/* Read up to and including the 'begin' line. */3204for (;;) {3205if (fgets(buff, sizeof(buff), in) == NULL) {3206/* TODO: This is a failure. */3207return;3208}3209if (memcmp(buff, "begin ", 6) == 0)3210break;3211}3212/* Now, decode the rest and write it. */3213out = fopen(name, "wb");3214while (fgets(buff, sizeof(buff), in) != NULL) {3215char *p = buff;3216int bytes;32173218if (memcmp(buff, "end", 3) == 0)3219break;32203221bytes = UUDECODE(*p++);3222while (bytes > 0) {3223int n = 0;3224/* Write out 1-3 bytes from that. */3225assert(VALID_UUDECODE(p[0]));3226assert(VALID_UUDECODE(p[1]));3227n = UUDECODE(*p++) << 18;3228n |= UUDECODE(*p++) << 12;3229fputc(n >> 16, out);3230--bytes;3231if (bytes > 0) {3232assert(VALID_UUDECODE(p[0]));3233n |= UUDECODE(*p++) << 6;3234fputc((n >> 8) & 0xFF, out);3235--bytes;3236}3237if (bytes > 0) {3238assert(VALID_UUDECODE(p[0]));3239n |= UUDECODE(*p++);3240fputc(n & 0xFF, out);3241--bytes;3242}3243}3244}3245fclose(out);3246fclose(in);3247}32483249void3250copy_reference_file(const char *name)3251{3252char buff[1024];3253FILE *in, *out;3254size_t rbytes;32553256snprintf(buff, sizeof(buff), "%s/%s", refdir, name);3257in = fopen(buff, "rb");3258failure("Couldn't open reference file %s", buff);3259assert(in != NULL);3260if (in == NULL)3261return;3262/* Now, decode the rest and write it. */3263/* Not a lot of error checking here; the input better be right. */3264out = fopen(name, "wb");3265while ((rbytes = fread(buff, 1, sizeof(buff), in)) > 0) {3266if (fwrite(buff, 1, rbytes, out) != rbytes) {3267logprintf("Error: fwrite\n");3268break;3269}3270}3271fclose(out);3272fclose(in);3273}32743275int3276is_LargeInode(const char *file)3277{3278#if defined(_WIN32) && !defined(__CYGWIN__)3279BY_HANDLE_FILE_INFORMATION bhfi;3280int r;32813282r = my_GetFileInformationByName(file, &bhfi);3283if (r != 0)3284return (0);3285return (bhfi.nFileIndexHigh & 0x0000FFFFUL);3286#else3287struct stat st;3288int64_t ino;32893290if (stat(file, &st) < 0)3291return (0);3292ino = (int64_t)st.st_ino;3293return (ino > 0xffffffff);3294#endif3295}32963297void3298extract_reference_files(const char **names)3299{3300while (names && *names)3301extract_reference_file(*names++);3302}33033304#ifndef PROGRAM3305/* Set ACLs */3306int3307assertion_entry_set_acls(const char *file, int line, struct archive_entry *ae,3308struct archive_test_acl_t *acls, int n)3309{3310int i, r, ret;33113312assertion_count(file, line);33133314ret = 0;3315archive_entry_acl_clear(ae);3316for (i = 0; i < n; i++) {3317r = archive_entry_acl_add_entry(ae,3318acls[i].type, acls[i].permset, acls[i].tag,3319acls[i].qual, acls[i].name);3320if (r != 0) {3321ret = 1;3322failure_start(file, line, "type=%#010x, "3323"permset=%#010x, tag=%d, qual=%d name=%s",3324(unsigned int)acls[i].type,3325(unsigned int)acls[i].permset, acls[i].tag,3326acls[i].qual, acls[i].name);3327failure_finish(NULL);3328}3329}33303331return (ret);3332}33333334static int3335archive_test_acl_match(struct archive_test_acl_t *acl, int type, int permset,3336int tag, int qual, const char *name)3337{3338if (type != acl->type)3339return (0);3340if (permset != acl->permset)3341return (0);3342if (tag != acl->tag)3343return (0);3344if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ)3345return (1);3346if (tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ)3347return (1);3348if (tag == ARCHIVE_ENTRY_ACL_EVERYONE)3349return (1);3350if (tag == ARCHIVE_ENTRY_ACL_OTHER)3351return (1);3352if (qual != acl->qual)3353return (0);3354if (name == NULL) {3355if (acl->name == NULL || acl->name[0] == '\0')3356return (1);3357return (0);3358}3359if (acl->name == NULL) {3360if (name[0] == '\0')3361return (1);3362return (0);3363}3364return (0 == strcmp(name, acl->name));3365}33663367/* Compare ACLs */3368int3369assertion_entry_compare_acls(const char *file, int line,3370struct archive_entry *ae, struct archive_test_acl_t *acls, int cnt,3371int want_type, int mode)3372{3373int *marker;3374int i, r, n, ret;3375int type, permset, tag, qual;3376int matched;3377const char *name;33783379assertion_count(file, line);33803381ret = 0;3382n = 0;3383marker = malloc(sizeof(marker[0]) * cnt);33843385for (i = 0; i < cnt; i++) {3386if ((acls[i].type & want_type) != 0) {3387marker[n] = i;3388n++;3389}3390}33913392if (n == 0) {3393failure_start(file, line, "No ACL's to compare, type mask: %d",3394want_type);3395return (1);3396}33973398while (0 == (r = archive_entry_acl_next(ae, want_type,3399&type, &permset, &tag, &qual, &name))) {3400for (i = 0, matched = 0; i < n && !matched; i++) {3401if (archive_test_acl_match(&acls[marker[i]], type,3402permset, tag, qual, name)) {3403/* We found a match; remove it. */3404marker[i] = marker[n - 1];3405n--;3406matched = 1;3407}3408}3409if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS3410&& tag == ARCHIVE_ENTRY_ACL_USER_OBJ) {3411if (!matched) {3412failure_start(file, line, "No match for "3413"user_obj perm");3414failure_finish(NULL);3415ret = 1;3416}3417if ((permset << 6) != (mode & 0700)) {3418failure_start(file, line, "USER_OBJ permset "3419"(%02o) != user mode (%02o)",3420(unsigned int)permset,3421(unsigned int)(07 & (mode >> 6)));3422failure_finish(NULL);3423ret = 1;3424}3425} else if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS3426&& tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ) {3427if (!matched) {3428failure_start(file, line, "No match for "3429"group_obj perm");3430failure_finish(NULL);3431ret = 1;3432}3433if ((permset << 3) != (mode & 0070)) {3434failure_start(file, line, "GROUP_OBJ permset "3435"(%02o) != group mode (%02o)",3436(unsigned int)permset,3437(unsigned int)(07 & (mode >> 3)));3438failure_finish(NULL);3439ret = 1;3440}3441} else if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS3442&& tag == ARCHIVE_ENTRY_ACL_OTHER) {3443if (!matched) {3444failure_start(file, line, "No match for "3445"other perm");3446failure_finish(NULL);3447ret = 1;3448}3449if ((permset << 0) != (mode & 0007)) {3450failure_start(file, line, "OTHER permset "3451"(%02o) != other mode (%02o)",3452(unsigned int)permset,3453(unsigned int)mode & 07);3454failure_finish(NULL);3455ret = 1;3456}3457} else if (matched != 1) {3458failure_start(file, line, "Could not find match for "3459"ACL (type=%#010x,permset=%#010x,tag=%d,qual=%d,"3460"name=``%s'')", (unsigned int)type,3461(unsigned int)permset, tag, qual, name);3462failure_finish(NULL);3463ret = 1;3464}3465}3466if (r != ARCHIVE_EOF) {3467failure_start(file, line, "Should not exit before EOF");3468failure_finish(NULL);3469ret = 1;3470}3471if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0 &&3472(mode_t)(mode & 0777) != (archive_entry_mode(ae) & 0777)) {3473failure_start(file, line, "Mode (%02o) and entry mode (%02o) "3474"mismatch", (unsigned int)mode,3475(unsigned int)archive_entry_mode(ae));3476failure_finish(NULL);3477ret = 1;3478}3479if (n != 0) {3480failure_start(file, line, "Could not find match for ACL "3481"(type=%#010x,permset=%#010x,tag=%d,qual=%d,name=``%s'')",3482(unsigned int)acls[marker[0]].type,3483(unsigned int)acls[marker[0]].permset,3484acls[marker[0]].tag, acls[marker[0]].qual,3485acls[marker[0]].name);3486failure_finish(NULL);3487ret = 1;3488/* Number of ACLs not matched should == 0 */3489}3490free(marker);3491return (ret);3492}3493#endif /* !defined(PROGRAM) */34943495/*3496*3497* TEST management3498*3499*/35003501/*3502* "list.h" is simply created by "grep DEFINE_TEST test_*.c"; it has3503* a line like3504* DEFINE_TEST(test_function)3505* for each test.3506*/3507struct test_list_t3508{3509void (*func)(void);3510const char *name;3511int failures;3512};35133514/* Use "list.h" to declare all of the test functions. */3515#undef DEFINE_TEST3516#define DEFINE_TEST(name) void name(void);3517#include "list.h"35183519/* Use "list.h" to create a list of all tests (functions and names). */3520#undef DEFINE_TEST3521#define DEFINE_TEST(n) { n, #n, 0 },3522static struct test_list_t tests[] = {3523#include "list.h"3524};35253526/*3527* Summarize repeated failures in the just-completed test.3528*/3529static void3530test_summarize(int failed, int skips_num)3531{3532unsigned int i;35333534switch (verbosity) {3535case VERBOSITY_SUMMARY_ONLY:3536printf(failed ? "E" : ".");3537fflush(stdout);3538break;3539case VERBOSITY_PASSFAIL:3540printf(failed ? "FAIL\n" : skips_num ? "skipped\n" : "ok\n");3541break;3542}35433544log_console = (verbosity == VERBOSITY_LIGHT_REPORT);35453546for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {3547if (failed_lines[i].count > 1 && !failed_lines[i].skip)3548logprintf("%s:%u: Summary: Failed %d times\n",3549failed_filename, i, failed_lines[i].count);3550}3551/* Clear the failure history for the next file. */3552failed_filename = NULL;3553memset(failed_lines, 0, sizeof(failed_lines));3554}35553556/*3557* Set or unset environment variable.3558*/3559static void3560set_environment(const char *key, const char *value)3561{35623563#if defined(_WIN32) && !defined(__CYGWIN__)3564if (!SetEnvironmentVariable(key, value)) {3565fprintf(stderr, "SetEnvironmentVariable failed with %d\n",3566(int)GetLastError());3567}3568#else3569if (value == NULL) {3570if (unsetenv(key) == -1)3571fprintf(stderr, "unsetenv: %s\n", strerror(errno));3572} else {3573if (setenv(key, value, 1) == -1)3574fprintf(stderr, "setenv: %s\n", strerror(errno));3575}3576#endif3577}35783579/*3580* Enforce C locale for (sub)processes.3581*/3582static void3583set_c_locale(void)3584{3585static const char *lcs[] = {3586"LC_ADDRESS",3587"LC_ALL",3588"LC_COLLATE",3589"LC_CTYPE",3590"LC_IDENTIFICATION",3591"LC_MEASUREMENT",3592"LC_MESSAGES",3593"LC_MONETARY",3594"LC_NAME",3595"LC_NUMERIC",3596"LC_PAPER",3597"LC_TELEPHONE",3598"LC_TIME",3599NULL3600};3601size_t i;36023603setlocale(LC_ALL, "C");3604set_environment("LANG", "C");3605for (i = 0; lcs[i] != NULL; i++)3606set_environment(lcs[i], NULL);3607}36083609/*3610* Actually run a single test, with appropriate setup and cleanup.3611*/3612static int3613test_run(int i, const char *tmpdir)3614{3615#ifdef PATH_MAX3616char workdir[PATH_MAX * 2];3617#else3618char workdir[1024 * 2];3619#endif3620char logfilename[256];3621int failures_before = failures;3622int skips_before = skips;3623int tmp;3624mode_t oldumask;36253626switch (verbosity) {3627case VERBOSITY_SUMMARY_ONLY: /* No per-test reports at all */3628break;3629case VERBOSITY_PASSFAIL: /* rest of line will include ok/FAIL marker */3630printf("%3d: %-64s", i, tests[i].name);3631fflush(stdout);3632break;3633default: /* Title of test, details will follow */3634printf("%3d: %s\n", i, tests[i].name);3635}36363637/* Chdir to the top-level work directory. */3638if (!assertChdir(tmpdir)) {3639fprintf(stderr,3640"ERROR: Can't chdir to top work dir %s\n", tmpdir);3641exit(1);3642}3643/* Create a log file for this test. */3644tmp = snprintf(logfilename, sizeof(logfilename), "%s.log", tests[i].name);3645if (tmp < 0) {3646fprintf(stderr,3647"ERROR can't create %s.log: %s\n",3648tests[i].name, strerror(errno));3649exit(1);3650}3651if ((size_t)tmp >= sizeof(logfilename)) {3652fprintf(stderr,3653"ERROR can't create %s.log: Name too long. "3654"Length %d; Max allowed length %zu\n",3655tests[i].name, tmp, sizeof(logfilename) - 1);3656exit(1);3657}3658logfile = fopen(logfilename, "w");3659fprintf(logfile, "%s\n\n", tests[i].name);3660/* Chdir() to a work dir for this specific test. */3661tmp = snprintf(workdir,3662sizeof(workdir), "%s/%s", tmpdir, tests[i].name);3663if (tmp < 0) {3664fprintf(stderr,3665"ERROR can't create %s/%s: %s\n",3666tmpdir, tests[i].name, strerror(errno));3667exit(1);3668}3669if ((size_t)tmp >= sizeof(workdir)) {3670fprintf(stderr,3671"ERROR can't create %s/%s: Path too long. "3672"Length %d; Max allowed length %zu\n",3673tmpdir, tests[i].name, tmp, sizeof(workdir) - 1);3674exit(1);3675}3676testworkdir = workdir;3677if (!assertMakeDir(testworkdir, 0755)3678|| !assertChdir(testworkdir)) {3679fprintf(stderr,3680"ERROR: Can't chdir to work dir %s\n", testworkdir);3681exit(1);3682}3683/* Explicitly reset the locale before each test. */3684set_c_locale();3685/* Record the umask before we run the test. */3686umask(oldumask = umask(0));3687/*3688* Run the actual test.3689*/3690(*tests[i].func)();3691/*3692* Clean up and report afterwards.3693*/3694testworkdir = NULL;3695/* Restore umask */3696umask(oldumask);3697/* Reset locale. */3698set_c_locale();3699/* Reset directory. */3700if (!assertChdir(tmpdir)) {3701fprintf(stderr, "ERROR: Couldn't chdir to temp dir %s\n",3702tmpdir);3703exit(1);3704}3705/* Report per-test summaries. */3706tests[i].failures = failures - failures_before;3707test_summarize(tests[i].failures, skips - skips_before);3708/* Close the per-test log file. */3709fclose(logfile);3710logfile = NULL;3711/* If there were no failures, we can remove the work dir and logfile. */3712if (tests[i].failures == 0) {3713if (!keep_temp_files && assertChdir(tmpdir)) {3714#if defined(_WIN32) && !defined(__CYGWIN__)3715/* Make sure not to leave empty directories.3716* Sometimes a processing of closing files used by tests3717* is not done, then rmdir will be failed and it will3718* leave a empty test directory. So we should wait a few3719* seconds and retry rmdir. */3720int r, t;3721for (t = 0; t < 10; t++) {3722if (t > 0)3723Sleep(1000);3724r = systemf("rmdir /S /Q %s", tests[i].name);3725if (r == 0)3726break;3727}3728systemf("del %s", logfilename);3729#else3730systemf("rm -rf %s", tests[i].name);3731systemf("rm %s", logfilename);3732#endif3733}3734}3735/* Return appropriate status. */3736return (tests[i].failures);3737}37383739/*3740*3741*3742* MAIN and support routines.3743*3744*3745*/37463747static void3748usage(const char *program)3749{3750static const int limit = nitems(tests);3751int i;37523753printf("Usage: %s [options] <test> <test> ...\n", program);3754printf("Default is to run all tests.\n");3755printf("Otherwise, specify the numbers of the tests you wish to run.\n");3756printf("Options:\n");3757printf(" -d Dump core after any failure, for debugging.\n");3758printf(" -k Keep all temp files.\n");3759printf(" Default: temp files for successful tests deleted.\n");3760#ifdef PROGRAM3761printf(" -p <path> Path to executable to be tested.\n");3762printf(" Default: path taken from " ENVBASE " environment variable.\n");3763#endif3764printf(" -q Quiet.\n");3765printf(" -r <dir> Path to dir containing reference files.\n");3766printf(" Default: Current directory.\n");3767printf(" -s Exit with code 2 if any tests were skipped.\n");3768printf(" -u Keep running specified tests until one fails.\n");3769printf(" -v Verbose.\n");3770printf("Available tests:\n");3771for (i = 0; i < limit; i++)3772printf(" %d: %s\n", i, tests[i].name);3773exit(1);3774}37753776static char *3777get_refdir(const char *d)3778{3779size_t tried_size, buff_size;3780char *buff, *tried, *pwd = NULL, *p = NULL;37813782#ifdef PATH_MAX3783buff_size = PATH_MAX;3784#else3785buff_size = 8192;3786#endif3787buff = calloc(buff_size, 1);3788if (buff == NULL) {3789fprintf(stderr, "Unable to allocate memory\n");3790exit(1);3791}37923793/* Allocate a buffer to hold the various directories we checked. */3794tried_size = buff_size * 2;3795tried = calloc(tried_size, 1);3796if (tried == NULL) {3797fprintf(stderr, "Unable to allocate memory\n");3798exit(1);3799}38003801/* If a dir was specified, try that */3802if (d != NULL) {3803pwd = NULL;3804snprintf(buff, buff_size, "%s", d);3805p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3806if (p != NULL) goto success;3807strncat(tried, buff, tried_size - strlen(tried) - 1);3808strncat(tried, "\n", tried_size - strlen(tried) - 1);3809goto failure;3810}38113812/* Get the current dir. */3813#if defined(PATH_MAX) && !defined(__GLIBC__)3814pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */3815#else3816pwd = getcwd(NULL, 0);3817#endif3818while (pwd[strlen(pwd) - 1] == '\n')3819pwd[strlen(pwd) - 1] = '\0';38203821/* Look for a known file. */3822snprintf(buff, buff_size, "%s", pwd);3823p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3824if (p != NULL) goto success;3825strncat(tried, buff, tried_size - strlen(tried) - 1);3826strncat(tried, "\n", tried_size - strlen(tried) - 1);38273828snprintf(buff, buff_size, "%s/test", pwd);3829p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3830if (p != NULL) goto success;3831strncat(tried, buff, tried_size - strlen(tried) - 1);3832strncat(tried, "\n", tried_size - strlen(tried) - 1);38333834#if defined(LIBRARY)3835snprintf(buff, buff_size, "%s/%s/test", pwd, LIBRARY);3836#else3837snprintf(buff, buff_size, "%s/%s/test", pwd, PROGRAM);3838#endif3839p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3840if (p != NULL) goto success;3841strncat(tried, buff, tried_size - strlen(tried) - 1);3842strncat(tried, "\n", tried_size - strlen(tried) - 1);38433844#if defined(PROGRAM_ALIAS)3845snprintf(buff, buff_size, "%s/%s/test", pwd, PROGRAM_ALIAS);3846p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3847if (p != NULL) goto success;3848strncat(tried, buff, tried_size - strlen(tried) - 1);3849strncat(tried, "\n", tried_size - strlen(tried) - 1);3850#endif38513852if (memcmp(pwd, "/usr/obj", 8) == 0) {3853snprintf(buff, buff_size, "%s", pwd + 8);3854p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3855if (p != NULL) goto success;3856strncat(tried, buff, tried_size - strlen(tried) - 1);3857strncat(tried, "\n", tried_size - strlen(tried) - 1);38583859snprintf(buff, buff_size, "%s/test", pwd + 8);3860p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3861if (p != NULL) goto success;3862strncat(tried, buff, tried_size - strlen(tried) - 1);3863strncat(tried, "\n", tried_size - strlen(tried) - 1);3864}38653866failure:3867printf("Unable to locate known reference file %s\n", KNOWNREF);3868printf(" Checked following directories:\n%s\n", tried);3869printf("Use -r option to specify full path to reference directory\n");3870#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)3871DebugBreak();3872#endif3873exit(1);38743875success:3876free(p);3877free(pwd);3878free(tried);38793880/* Copy result into a fresh buffer to reduce memory usage. */3881p = strdup(buff);3882free(buff);3883return p;3884}38853886/* Filter tests against a glob pattern. Returns non-zero if test matches3887* pattern, zero otherwise. A '^' at the beginning of the pattern negates3888* the return values (i.e. returns zero for a match, non-zero otherwise.3889*/3890static int3891test_filter(const char *pattern, const char *test)3892{3893int retval = 0;3894int negate = 0;3895const char *p = pattern;3896const char *t = test;38973898if (p[0] == '^')3899{3900negate = 1;3901p++;3902}39033904while (1)3905{3906if (p[0] == '\\')3907p++;3908else if (p[0] == '*')3909{3910while (p[0] == '*')3911p++;3912if (p[0] == '\\')3913p++;3914if ((t = strchr(t, p[0])) == 0)3915break;3916}3917if (p[0] != t[0])3918break;3919if (p[0] == '\0') {3920retval = 1;3921break;3922}3923p++;3924t++;3925}39263927return (negate) ? !retval : retval;3928}39293930static int3931get_test_set(int *test_set, int limit, const char *test)3932{3933int start, end;3934int idx = 0;39353936if (test == NULL) {3937/* Default: Run all tests. */3938for (;idx < limit; idx++)3939test_set[idx] = idx;3940return (limit);3941}3942if (*test >= '0' && *test <= '9') {3943const char *vp = test;3944start = 0;3945while (*vp >= '0' && *vp <= '9') {3946start *= 10;3947start += *vp - '0';3948++vp;3949}3950if (*vp == '\0') {3951end = start;3952} else if (*vp == '-') {3953++vp;3954if (*vp == '\0') {3955end = limit - 1;3956} else {3957end = 0;3958while (*vp >= '0' && *vp <= '9') {3959end *= 10;3960end += *vp - '0';3961++vp;3962}3963}3964} else3965return (-1);3966if (start < 0 || end >= limit || start > end)3967return (-1);3968while (start <= end)3969test_set[idx++] = start++;3970} else {3971for (start = 0; start < limit; ++start) {3972const char *name = tests[start].name;3973if (test_filter(test, name))3974test_set[idx++] = start;3975}3976}3977return ((idx == 0)?-1:idx);3978}39793980int3981main(int argc, char **argv)3982{3983static const int limit = nitems(tests);3984int test_set[nitems(tests)];3985int i = 0, j = 0, tests_run = 0, tests_failed = 0, option;3986size_t testprogdir_len;3987size_t tmplen;3988#ifdef PROGRAM3989size_t tmp2_len;3990#endif3991time_t now;3992struct tm *tmptr;3993#if defined(HAVE_LOCALTIME_R) || defined(HAVE_LOCALTIME_S)3994struct tm tmbuf;3995#endif3996char *refdir_alloc = NULL;3997const char *progname;3998char **saved_argv;3999const char *tmp, *option_arg, *p;4000#ifdef PATH_MAX4001char tmpdir[PATH_MAX];4002#else4003char tmpdir[256];4004#endif4005char *pwd, *testprogdir, *tmp2 = NULL, *vlevel = NULL;4006char tmpdir_timestamp[32];40074008(void)argc; /* UNUSED */40094010/* Get the current dir. */4011#if defined(PATH_MAX) && !defined(__GLIBC__)4012pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */4013#else4014pwd = getcwd(NULL, 0);4015#endif4016while (pwd[strlen(pwd) - 1] == '\n')4017pwd[strlen(pwd) - 1] = '\0';40184019#if defined(HAVE__CrtSetReportMode) && !defined(__WATCOMC__)4020/* To stop to run the default invalid parameter handler. */4021_set_invalid_parameter_handler(invalid_parameter_handler);4022/* Disable annoying assertion message box. */4023_CrtSetReportMode(_CRT_ASSERT, 0);4024#endif40254026/*4027* Name of this program, used to build root of our temp directory4028* tree.4029*/4030progname = p = argv[0];4031testprogdir_len = strlen(progname) + 1;4032if ((testprogdir = malloc(testprogdir_len)) == NULL)4033{4034fprintf(stderr, "ERROR: Out of memory.");4035exit(1);4036}4037strncpy(testprogdir, progname, testprogdir_len);4038while (*p != '\0') {4039/* Support \ or / dir separators for Windows compat. */4040if (*p == '/' || *p == '\\')4041{4042progname = p + 1;4043i = j;4044}4045++p;4046j++;4047}4048testprogdir[i] = '\0';4049#if defined(_WIN32) && !defined(__CYGWIN__)4050if (testprogdir[0] != '/' && testprogdir[0] != '\\' &&4051!(((testprogdir[0] >= 'a' && testprogdir[0] <= 'z') ||4052(testprogdir[0] >= 'A' && testprogdir[0] <= 'Z')) &&4053testprogdir[1] == ':' &&4054(testprogdir[2] == '/' || testprogdir[2] == '\\')))4055#else4056if (testprogdir[0] != '/')4057#endif4058{4059/* Fixup path for relative directories. */4060if ((testprogdir = realloc(testprogdir,4061strlen(pwd) + 1 + strlen(testprogdir) + 1)) == NULL)4062{4063fprintf(stderr, "ERROR: Out of memory.");4064exit(1);4065}4066memmove(testprogdir + strlen(pwd) + 1, testprogdir,4067strlen(testprogdir) + 1);4068memcpy(testprogdir, pwd, strlen(pwd));4069testprogdir[strlen(pwd)] = '/';4070}40714072#ifdef PROGRAM4073/* Get the target program from environment, if available. */4074testprogfile = getenv(ENVBASE);4075#endif40764077if (getenv("TMPDIR") != NULL)4078tmp = getenv("TMPDIR");4079else if (getenv("TMP") != NULL)4080tmp = getenv("TMP");4081else if (getenv("TEMP") != NULL)4082tmp = getenv("TEMP");4083else if (getenv("TEMPDIR") != NULL)4084tmp = getenv("TEMPDIR");4085else4086tmp = "/tmp";4087tmplen = strlen(tmp);4088while (tmplen > 0 && tmp[tmplen - 1] == '/')4089tmplen--;40904091/* Allow -d to be controlled through the environment. */4092if (getenv(ENVBASE "_DEBUG") != NULL)4093dump_on_failure = 1;40944095/* Allow -v to be controlled through the environment. */4096if (getenv("_VERBOSITY_LEVEL") != NULL)4097{4098vlevel = getenv("_VERBOSITY_LEVEL");4099verbosity = atoi(vlevel);4100if (verbosity < VERBOSITY_SUMMARY_ONLY || verbosity > VERBOSITY_FULL)4101{4102/* Unsupported verbosity levels are silently ignored */4103vlevel = NULL;4104verbosity = VERBOSITY_PASSFAIL;4105}4106}41074108/* Get the directory holding test files from environment. */4109refdir = getenv(ENVBASE "_TEST_FILES");41104111/*4112* Parse options, without using getopt(), which isn't available4113* on all platforms.4114*/4115++argv; /* Skip program name */4116while (*argv != NULL) {4117if (**argv != '-')4118break;4119p = *argv++;4120++p; /* Skip '-' */4121while (*p != '\0') {4122option = *p++;4123option_arg = NULL;4124/* If 'opt' takes an argument, parse that. */4125if (option == 'p' || option == 'r') {4126if (*p != '\0')4127option_arg = p;4128else if (*argv == NULL) {4129fprintf(stderr,4130"Option -%c requires argument.\n",4131option);4132usage(progname);4133} else4134option_arg = *argv++;4135p = ""; /* End of this option word. */4136}41374138/* Now, handle the option. */4139switch (option) {4140case 'd':4141dump_on_failure = 1;4142break;4143case 'k':4144keep_temp_files = 1;4145break;4146case 'p':4147#ifdef PROGRAM4148testprogfile = option_arg;4149#else4150fprintf(stderr, "-p option not permitted\n");4151usage(progname);4152#endif4153break;4154case 'q':4155if (!vlevel)4156verbosity--;4157break;4158case 'r':4159refdir = option_arg;4160break;4161case 's':4162fail_if_tests_skipped = 1;4163break;4164case 'u':4165until_failure++;4166break;4167case 'v':4168if (!vlevel)4169verbosity++;4170break;4171default:4172fprintf(stderr, "Unrecognized option '%c'\n",4173option);4174usage(progname);4175}4176}4177}41784179/*4180* Sanity-check that our options make sense.4181*/4182#ifdef PROGRAM4183if (testprogfile == NULL)4184{4185tmp2_len = strlen(testprogdir) + 1 + strlen(PROGRAM) + 1;4186if ((tmp2 = malloc(tmp2_len)) == NULL)4187{4188fprintf(stderr, "ERROR: Out of memory.");4189exit(1);4190}4191strncpy(tmp2, testprogdir, tmp2_len);4192strncat(tmp2, "/", tmp2_len);4193strncat(tmp2, PROGRAM, tmp2_len);4194testprogfile = tmp2;4195}41964197{4198char *testprg;4199size_t testprg_len;4200#if defined(_WIN32) && !defined(__CYGWIN__)4201/* Command.com sometimes rejects '/' separators. */4202testprg = strdup(testprogfile);4203for (i = 0; testprg[i] != '\0'; i++) {4204if (testprg[i] == '/')4205testprg[i] = '\\';4206}4207testprogfile = testprg;4208#endif4209/* Quote the name that gets put into shell command lines. */4210testprg_len = strlen(testprogfile) + 3;4211testprg = malloc(testprg_len);4212strncpy(testprg, "\"", testprg_len);4213strncat(testprg, testprogfile, testprg_len);4214strncat(testprg, "\"", testprg_len);4215testprog = testprg;4216}42174218/* Sanity check: reject a relative path for refdir. */4219if (refdir != NULL) {4220#if defined(_WIN32) && !defined(__CYGWIN__)4221/* TODO: probably use PathIsRelative() from <shlwapi.h>. */4222#else4223if (refdir[0] != '/') {4224fprintf(stderr,4225"ERROR: Cannot use relative path for refdir\n");4226exit(1);4227}4228#endif4229}4230#endif42314232#if !defined(_WIN32) && defined(SIGPIPE)4233{ /* Ignore SIGPIPE signals */4234struct sigaction sa;4235sa.sa_handler = SIG_IGN;4236sigemptyset(&sa.sa_mask);4237sa.sa_flags = 0;4238sigaction(SIGPIPE, &sa, NULL);4239}4240#endif42414242/*4243* Create a temp directory for the following tests.4244* Include the time the tests started as part of the name,4245* to make it easier to track the results of multiple tests.4246*/4247now = time(NULL);4248for (i = 0; ; i++) {4249#if defined(HAVE_LOCALTIME_S)4250tmptr = localtime_s(&tmbuf, &now) ? NULL : &tmbuf;4251#elif defined(HAVE_LOCALTIME_R)4252tmptr = localtime_r(&now, &tmbuf);4253#else4254tmptr = localtime(&now);4255#endif4256strftime(tmpdir_timestamp, sizeof(tmpdir_timestamp),4257"%Y-%m-%dT%H.%M.%S", tmptr);4258if (tmplen + 1 + strlen(progname) + 1 +4259strlen(tmpdir_timestamp) + 1 + 3 >=4260nitems(tmpdir)) {4261fprintf(stderr,4262"ERROR: Temp directory pathname too long\n");4263exit(1);4264}4265snprintf(tmpdir, sizeof(tmpdir), "%.*s/%s.%s-%03d",4266(int)tmplen, tmp, progname, tmpdir_timestamp, i);4267if (assertMakeDir(tmpdir, 0755))4268break;4269if (i >= 999) {4270fprintf(stderr,4271"ERROR: Unable to create temp directory %s\n",4272tmpdir);4273exit(1);4274}4275}42764277/*4278* If the user didn't specify a directory for locating4279* reference files, try to find the reference files in4280* the "usual places."4281*/4282refdir = refdir_alloc = get_refdir(refdir);42834284/*4285* Banner with basic information.4286*/4287printf("\n");4288printf("If tests fail or crash, details will be in:\n");4289printf(" %s\n", tmpdir);4290printf("\n");4291if (verbosity > VERBOSITY_SUMMARY_ONLY) {4292printf("Reference files will be read from: %s\n", refdir);4293#ifdef PROGRAM4294printf("Running tests on: %s\n", testprog);4295#endif4296printf("Exercising: ");4297fflush(stdout);4298printf("%s\n", EXTRA_VERSION);4299} else {4300printf("Running ");4301fflush(stdout);4302}43034304/*4305* Run some or all of the individual tests.4306*/4307saved_argv = argv;4308do {4309argv = saved_argv;4310do {4311int test_num;43124313test_num = get_test_set(test_set, limit, *argv);4314if (test_num < 0) {4315printf("*** INVALID Test %s\n", *argv);4316free(refdir_alloc);4317free(testprogdir);4318usage(progname);4319}4320for (i = 0; i < test_num; i++) {4321tests_run++;4322if (test_run(test_set[i], tmpdir)) {4323tests_failed++;4324if (until_failure)4325goto finish;4326}4327}4328if (*argv != NULL)4329argv++;4330} while (*argv != NULL);4331} while (until_failure);43324333finish:4334/* Must be freed after all tests run */4335free(tmp2);4336free(testprogdir);4337free(pwd);43384339/*4340* Report summary statistics.4341*/4342if (verbosity > VERBOSITY_SUMMARY_ONLY) {4343printf("\n");4344printf("Totals:\n");4345printf(" Tests run: %8d\n", tests_run);4346printf(" Tests failed: %8d\n", tests_failed);4347printf(" Assertions checked:%8d\n", assertions);4348printf(" Assertions failed: %8d\n", failures);4349printf(" Skips reported: %8d\n", skips);4350}4351if (failures) {4352printf("\n");4353printf("Failing tests:\n");4354for (i = 0; i < limit; ++i) {4355if (tests[i].failures)4356printf(" %d: %s (%d failures)\n", i,4357tests[i].name, tests[i].failures);4358}4359printf("\n");4360printf("Details for failing tests: %s\n", tmpdir);4361printf("\n");4362} else {4363if (verbosity == VERBOSITY_SUMMARY_ONLY)4364printf("\n");4365printf("%d tests passed, no failures\n", tests_run);4366}43674368free(refdir_alloc);43694370/* If the final tmpdir is empty, we can remove it. */4371/* This should be the usual case when all tests succeed. */4372assertChdir("..");4373rmdir(tmpdir);43744375if (tests_failed) return 1;43764377if (fail_if_tests_skipped == 1 && skips > 0) return 2;43784379return 0;4380}438143824383