Path: blob/main/contrib/libarchive/test_utils/test_main.c
105174 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#endif86#if !defined(_WIN32) || defined(__CYGWIN__)87# if HAVE_POSIX_SPAWN88# if HAVE_SYS_WAIT_H89# include <sys/wait.h>90# endif91# if HAVE_SPAWN_H92# include <spawn.h>93# endif94extern char **environ;95# define USE_POSIX_SPAWN 196# endif97#endif9899#ifndef nitems100#define nitems(arr) (sizeof(arr) / sizeof((arr)[0]))101#endif102103/*104*105* Windows support routines106*107* Note: Configuration is a tricky issue. Using HAVE_* feature macros108* in the test harness is dangerous because they cover up109* configuration errors. The classic example of this is omitting a110* configure check. If libarchive and libarchive_test both look for111* the same feature macro, such errors are hard to detect. Platform112* macros (e.g., _WIN32 or __GNUC__) are a little better, but can113* easily lead to very messy code. It's best to limit yourself114* to only the most generic programming techniques in the test harness115* and thus avoid conditionals altogether. Where that's not possible,116* try to minimize conditionals by grouping platform-specific tests in117* one place (e.g., test_acl_freebsd) or by adding new assert()118* functions (e.g., assertMakeHardlink()) to cover up platform119* differences. Platform-specific coding in libarchive_test is often120* a symptom that some capability is missing from libarchive itself.121*/122#if defined(_WIN32) && !defined(__CYGWIN__)123#include <io.h>124#include <direct.h>125#include <windows.h>126#ifndef F_OK127#define F_OK (0)128#endif129#ifndef S_ISDIR130#define S_ISDIR(m) ((m) & _S_IFDIR)131#endif132#ifndef S_ISREG133#define S_ISREG(m) ((m) & _S_IFREG)134#endif135#if !defined(__BORLANDC__)136#define access _access137#undef chdir138#define chdir _chdir139#undef chmod140#define chmod _chmod141#endif142#ifndef fileno143#define fileno _fileno144#endif145/*#define fstat _fstat64*/146#if !defined(__BORLANDC__)147#define getcwd _getcwd148#endif149#define lstat stat150/*#define lstat _stat64*/151/*#define stat _stat64*/152#define rmdir _rmdir153#if !defined(__BORLANDC__)154#define strdup _strdup155#define umask _umask156#endif157#define int64_t __int64158#endif159160#if defined(HAVE__CrtSetReportMode)161# include <crtdbg.h>162#endif163164mode_t umasked(mode_t expected_mode)165{166mode_t mode = umask(0);167umask(mode);168return expected_mode & ~mode;169}170171/* Path to working directory for current test */172const char *testworkdir;173#ifdef PROGRAM174/* Pathname of exe to be tested. */175const char *testprogfile;176/* Name of exe to use in printf-formatted command strings. */177/* On Windows, this includes leading/trailing quotes. */178const char *testprog;179#endif180181#if defined(_WIN32) && !defined(__CYGWIN__)182static void *GetFunctionKernel32(const char *);183static int my_CreateSymbolicLinkA(const char *, const char *, int);184static int my_CreateHardLinkA(const char *, const char *);185static int my_GetFileInformationByName(const char *,186BY_HANDLE_FILE_INFORMATION *);187188typedef struct _REPARSE_DATA_BUFFER {189ULONG ReparseTag;190USHORT ReparseDataLength;191USHORT Reserved;192union {193struct {194USHORT SubstituteNameOffset;195USHORT SubstituteNameLength;196USHORT PrintNameOffset;197USHORT PrintNameLength;198ULONG Flags;199WCHAR PathBuffer[1];200} SymbolicLinkReparseBuffer;201struct {202USHORT SubstituteNameOffset;203USHORT SubstituteNameLength;204USHORT PrintNameOffset;205USHORT PrintNameLength;206WCHAR PathBuffer[1];207} MountPointReparseBuffer;208struct {209UCHAR DataBuffer[1];210} GenericReparseBuffer;211} DUMMYUNIONNAME;212} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;213214static void *215GetFunctionKernel32(const char *name)216{217static HINSTANCE lib;218static int set;219if (!set) {220set = 1;221lib = LoadLibrary("kernel32.dll");222}223if (lib == NULL) {224fprintf(stderr, "Can't load kernel32.dll?!\n");225exit(1);226}227return (void *)GetProcAddress(lib, name);228}229230static int231my_CreateSymbolicLinkA(const char *linkname, const char *target,232int targetIsDir)233{234static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, DWORD);235DWORD attrs;236static int set;237int ret, tmpflags;238size_t llen, tlen;239int flags = 0;240char *src, *tgt, *p;241if (!set) {242set = 1;243f = GetFunctionKernel32("CreateSymbolicLinkA");244}245if (f == NULL)246return (0);247248tlen = strlen(target);249llen = strlen(linkname);250251if (tlen == 0 || llen == 0)252return (0);253254tgt = malloc(tlen + 1);255if (tgt == NULL)256return (0);257src = malloc(llen + 1);258if (src == NULL) {259free(tgt);260return (0);261}262263/*264* Translate slashes to backslashes265*/266p = src;267while(*linkname != '\0') {268if (*linkname == '/')269*p = '\\';270else271*p = *linkname;272linkname++;273p++;274}275*p = '\0';276277p = tgt;278while(*target != '\0') {279if (*target == '/')280*p = '\\';281else282*p = *target;283target++;284p++;285}286*p = '\0';287288/*289* Each test has to specify if a file or a directory symlink290* should be created.291*/292if (targetIsDir) {293#if defined(SYMBOLIC_LINK_FLAG_DIRECTORY)294flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;295#else296flags |= 0x1;297#endif298}299300#if defined(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)301tmpflags = flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;302#else303tmpflags = flags | 0x2;304#endif305/*306* Windows won't overwrite existing links307*/308attrs = GetFileAttributesA(linkname);309if (attrs != INVALID_FILE_ATTRIBUTES) {310if (attrs & FILE_ATTRIBUTE_DIRECTORY)311RemoveDirectoryA(linkname);312else313DeleteFileA(linkname);314}315316ret = (*f)(src, tgt, tmpflags);317/*318* Prior to Windows 10 the SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE319* is not understood320*/321if (!ret)322ret = (*f)(src, tgt, flags);323324free(src);325free(tgt);326return (ret);327}328329static int330my_CreateHardLinkA(const char *linkname, const char *target)331{332static BOOLEAN (WINAPI *f)(LPCSTR, LPCSTR, LPSECURITY_ATTRIBUTES);333static int set;334if (!set) {335set = 1;336f = GetFunctionKernel32("CreateHardLinkA");337}338return f == NULL ? 0 : (*f)(linkname, target, NULL);339}340341static int342my_GetFileInformationByName(const char *path, BY_HANDLE_FILE_INFORMATION *bhfi)343{344HANDLE h;345int r;346347memset(bhfi, 0, sizeof(*bhfi));348h = CreateFileA(path, FILE_READ_ATTRIBUTES, 0, NULL,349OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);350if (h == INVALID_HANDLE_VALUE)351return (0);352r = GetFileInformationByHandle(h, bhfi);353CloseHandle(h);354return (r);355}356#endif357358#if defined(HAVE__CrtSetReportMode) && !defined(__WATCOMC__)359static void360invalid_parameter_handler(const wchar_t * expression,361const wchar_t * function, const wchar_t * file,362unsigned int line, uintptr_t pReserved)363{364/* nop */365// Silence unused-parameter compiler warnings.366(void)expression;367(void)function;368(void)file;369(void)line;370(void)pReserved;371}372#endif373374/*375*376* OPTIONS FLAGS377*378*/379380/* Enable core dump on failure. */381static int dump_on_failure = 0;382/* Default is to remove temp dirs and log data for successful tests. */383static int keep_temp_files = 0;384/* 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. */385static int fail_if_tests_skipped = 0;386/* Default is to run the specified tests once and report errors. */387static int until_failure = 0;388/* Default is to just report pass/fail for each test. */389static int verbosity = 0;390#define VERBOSITY_SUMMARY_ONLY -1 /* -q */391#define VERBOSITY_PASSFAIL 0 /* Default */392#define VERBOSITY_LIGHT_REPORT 1 /* -v */393#define VERBOSITY_FULL 2 /* -vv */394/* A few places generate even more output for verbosity > VERBOSITY_FULL,395* mostly for debugging the test harness itself. */396/* Cumulative count of assertion failures. */397static int failures = 0;398/* Cumulative count of reported skips. */399static int skips = 0;400/* Cumulative count of assertions checked. */401static int assertions = 0;402403/* Directory where uuencoded reference files can be found. */404static const char *refdir;405406/*407* Report log information selectively to console and/or disk log.408*/409static int log_console = 0;410static FILE *logfile;411static void __LA_PRINTFLIKE(1, 0)412vlogprintf(const char *fmt, va_list ap)413{414#ifdef va_copy415va_list lfap;416va_copy(lfap, ap);417#endif418if (log_console)419vfprintf(stdout, fmt, ap);420if (logfile != NULL)421#ifdef va_copy422vfprintf(logfile, fmt, lfap);423va_end(lfap);424#else425vfprintf(logfile, fmt, ap);426#endif427}428429static void __LA_PRINTFLIKE(1, 2)430logprintf(const char *fmt, ...)431{432va_list ap;433va_start(ap, fmt);434vlogprintf(fmt, ap);435va_end(ap);436}437438/* Set up a message to display only if next assertion fails. */439static char msgbuff[4096];440static const char *msg, *nextmsg;441void442failure(const char *fmt, ...)443{444va_list ap;445if (fmt == NULL) {446nextmsg = NULL;447} else {448va_start(ap, fmt);449vsnprintf(msgbuff, sizeof(msgbuff), fmt, ap);450va_end(ap);451nextmsg = msgbuff;452}453}454455/*456* Copy arguments into file-local variables.457* This was added to permit vararg assert() functions without needing458* variadic wrapper macros. Turns out that the vararg capability is almost459* never used, so almost all of the vararg assertions can be simplified460* by removing the vararg capability and reworking the wrapper macro to461* pass __FILE__, __LINE__ directly into the function instead of using462* this hook. I suspect this machinery is used so rarely that we463* would be better off just removing it entirely. That would simplify464* the code here noticeably.465*/466static const char *skipping_filename;467static int skipping_line;468void skipping_setup(const char *filename, int line)469{470skipping_filename = filename;471skipping_line = line;472}473474/* Called at the beginning of each assert() function. */475static void476assertion_count(const char *file, int line)477{478(void)file; /* UNUSED */479(void)line; /* UNUSED */480++assertions;481/* Proper handling of "failure()" message. */482msg = nextmsg;483nextmsg = NULL;484/* Uncomment to print file:line after every assertion.485* Verbose, but occasionally useful in tracking down crashes. */486/* printf("Checked %s:%d\n", file, line); */487}488489/*490* For each test source file, we remember how many times each491* assertion was reported. Cleared before each new test,492* used by test_summarize().493*/494static struct line {495int count;496int skip;497} failed_lines[10000];498static const char *failed_filename;499500/* Count this failure, setup up log destination and handle initial report. */501static void __LA_PRINTFLIKE(3, 4)502failure_start(const char *filename, int line, const char *fmt, ...)503{504va_list ap;505506/* Record another failure for this line. */507++failures;508failed_filename = filename;509failed_lines[line].count++;510511/* Determine whether to log header to console. */512switch (verbosity) {513case VERBOSITY_LIGHT_REPORT:514log_console = (failed_lines[line].count < 2);515break;516default:517log_console = (verbosity >= VERBOSITY_FULL);518}519520/* Log file:line header for this failure */521va_start(ap, fmt);522#if _MSC_VER523logprintf("%s(%d): ", filename, line);524#else525logprintf("%s:%d: ", filename, line);526#endif527vlogprintf(fmt, ap);528va_end(ap);529logprintf("\n");530531if (msg != NULL && msg[0] != '\0') {532logprintf(" Description: %s\n", msg);533msg = NULL;534}535536/* Determine whether to log details to console. */537if (verbosity == VERBOSITY_LIGHT_REPORT)538log_console = 0;539}540541/* Complete reporting of failed tests. */542/*543* The 'extra' hook here is used by libarchive to include libarchive544* error messages with assertion failures. It could also be used545* to add strerror() output, for example. Just define the EXTRA_DUMP()546* macro appropriately.547*/548static void549failure_finish(void *extra)550{551(void)extra; /* UNUSED (maybe) */552#ifdef EXTRA_DUMP553if (extra != NULL) {554logprintf(" errno: %d\n", EXTRA_ERRNO(extra));555logprintf(" detail: %s\n", EXTRA_DUMP(extra));556}557#endif558559if (dump_on_failure) {560fprintf(stderr,561" *** forcing core dump so failure can be debugged ***\n");562abort();563}564}565566/* Inform user that we're skipping some checks. */567void568test_skipping(const char *fmt, ...)569{570char buff[1024];571va_list ap;572573va_start(ap, fmt);574vsnprintf(buff, sizeof(buff), fmt, ap);575va_end(ap);576/* Use failure() message if set. */577msg = nextmsg;578nextmsg = NULL;579/* failure_start() isn't quite right, but is awfully convenient. */580failure_start(skipping_filename, skipping_line, "SKIPPING: %s", buff);581--failures; /* Undo failures++ in failure_start() */582/* Don't failure_finish() here. */583/* Mark as skip, so doesn't count as failed test. */584failed_lines[skipping_line].skip = 1;585++skips;586}587588/*589*590* ASSERTIONS591*592*/593594/* Generic assert() just displays the failed condition. */595int596assertion_assert(const char *file, int line, int value,597const char *condition, void *extra)598{599assertion_count(file, line);600if (!value) {601failure_start(file, line, "Assertion failed: %s", condition);602failure_finish(extra);603}604return (value);605}606607/* chdir() and report any errors */608int609assertion_chdir(const char *file, int line, const char *pathname)610{611assertion_count(file, line);612if (chdir(pathname) == 0)613return (1);614failure_start(file, line, "chdir(\"%s\")", pathname);615failure_finish(NULL);616return (0);617618}619620/* change file/directory permissions and errors if it fails */621int622assertion_chmod(const char *file, int line, const char *pathname, int mode)623{624assertion_count(file, line);625if (chmod(pathname, (mode_t)mode) == 0)626return (1);627failure_start(file, line, "chmod(\"%s\", %4.o)", pathname,628(unsigned int)mode);629failure_finish(NULL);630return (0);631632}633634/* Verify two integers are equal. */635int636assertion_equal_int(const char *file, int line,637long long v1, const char *e1, long long v2, const char *e2, void *extra)638{639assertion_count(file, line);640if (v1 == v2)641return (1);642failure_start(file, line, "%s != %s", e1, e2);643logprintf(" %s=%lld (0x%llx, 0%llo)\n", e1, v1,644(unsigned long long)v1, (unsigned long long)v1);645logprintf(" %s=%lld (0x%llx, 0%llo)\n", e2, v2,646(unsigned long long)v2, (unsigned long long)v2);647failure_finish(extra);648return (0);649}650651/* Verify two pointers are equal. */652int653assertion_equal_address(const char *file, int line,654const void *v1, const char *e1, const void *v2, const char *e2, void *extra)655{656assertion_count(file, line);657if (v1 == v2)658return (1);659failure_start(file, line, "%s != %s", e1, e2);660logprintf(" %s=0x%llx\n", e1, (unsigned long long)(uintptr_t)v1);661logprintf(" %s=0x%llx\n", e2, (unsigned long long)(uintptr_t)v2);662failure_finish(extra);663return (0);664}665666/*667* Utility to convert a single UTF-8 sequence.668*/669static int670_utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)671{672static const char utf8_count[256] = {6731, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */6741, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */6751, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */6761, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */6771, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */6781, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */6791, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */6801, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */6810, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */6820, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */6830, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */6840, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */6850, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */6862, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */6873, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */6884, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */689};690int ch;691int cnt;692uint32_t wc;693694*pwc = 0;695696/* Sanity check. */697if (n == 0)698return (0);699/*700* Decode 1-4 bytes depending on the value of the first byte.701*/702ch = (unsigned char)*s;703if (ch == 0)704return (0); /* Standard: return 0 for end-of-string. */705cnt = utf8_count[ch];706707/* Invalid sequence or there are not plenty bytes. */708if (n < (size_t)cnt)709return (-1);710711/* Make a Unicode code point from a single UTF-8 sequence. */712switch (cnt) {713case 1: /* 1 byte sequence. */714*pwc = ch & 0x7f;715return (cnt);716case 2: /* 2 bytes sequence. */717if ((s[1] & 0xc0) != 0x80) return (-1);718*pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);719return (cnt);720case 3: /* 3 bytes sequence. */721if ((s[1] & 0xc0) != 0x80) return (-1);722if ((s[2] & 0xc0) != 0x80) return (-1);723wc = ((ch & 0x0f) << 12)724| ((s[1] & 0x3f) << 6)725| (s[2] & 0x3f);726if (wc < 0x800)727return (-1);/* Overlong sequence. */728break;729case 4: /* 4 bytes sequence. */730if (n < 4)731return (-1);732if ((s[1] & 0xc0) != 0x80) return (-1);733if ((s[2] & 0xc0) != 0x80) return (-1);734if ((s[3] & 0xc0) != 0x80) return (-1);735wc = ((ch & 0x07) << 18)736| ((s[1] & 0x3f) << 12)737| ((s[2] & 0x3f) << 6)738| (s[3] & 0x3f);739if (wc < 0x10000)740return (-1);/* Overlong sequence. */741break;742default:743return (-1);744}745746/* The code point larger than 0x10FFFF is not legal747* Unicode values. */748if (wc > 0x10FFFF)749return (-1);750/* Correctly gets a Unicode, returns used bytes. */751*pwc = wc;752return (cnt);753}754755static void strdump(const char *e, const char *p, int ewidth, int utf8)756{757const char *q = p;758759logprintf(" %*s = ", ewidth, e);760if (p == NULL) {761logprintf("NULL\n");762return;763}764logprintf("\"");765while (*p != '\0') {766unsigned int c = 0xff & *p++;767switch (c) {768case '\a': logprintf("\\a"); break;769case '\b': logprintf("\\b"); break;770case '\n': logprintf("\\n"); break;771case '\r': logprintf("\\r"); break;772default:773if (c >= 32 && c < 127)774logprintf("%c", (int)c);775else776logprintf("\\x%02X", c);777}778}779logprintf("\"");780logprintf(" (length %d)", q == NULL ? -1 : (int)strlen(q));781782/*783* If the current string is UTF-8, dump its code points.784*/785if (utf8) {786size_t len;787uint32_t uc;788int n;789int cnt = 0;790791p = q;792len = strlen(p);793logprintf(" [");794while ((n = _utf8_to_unicode(&uc, p, len)) > 0) {795if (p != q)796logprintf(" ");797logprintf("%04X", uc);798p += n;799len -= n;800cnt++;801}802logprintf("]");803logprintf(" (count %d", cnt);804if (n < 0) {805logprintf(",unknown %zu bytes", len);806}807logprintf(")");808809}810logprintf("\n");811}812813/* Verify two strings are equal, dump them if not. */814int815assertion_equal_string(const char *file, int line,816const char *v1, const char *e1,817const char *v2, const char *e2,818void *extra, int utf8)819{820int l1, l2;821822assertion_count(file, line);823if (v1 == v2 || (v1 != NULL && v2 != NULL && strcmp(v1, v2) == 0))824return (1);825failure_start(file, line, "%s != %s", e1, e2);826l1 = (int)strlen(e1);827l2 = (int)strlen(e2);828if (l1 < l2)829l1 = l2;830strdump(e1, v1, l1, utf8);831strdump(e2, v2, l1, utf8);832failure_finish(extra);833return (0);834}835836static void837wcsdump(const char *e, const wchar_t *w)838{839logprintf(" %s = ", e);840if (w == NULL) {841logprintf("(null)");842return;843}844logprintf("\"");845while (*w != L'\0') {846unsigned int c = *w++;847if (c >= 32 && c < 127)848logprintf("%c", (int)c);849else if (c < 256)850logprintf("\\x%02X", c);851else if (c < 0x10000)852logprintf("\\u%04X", c);853else854logprintf("\\U%08X", c);855}856logprintf("\"\n");857}858859#ifndef HAVE_WCSCMP860static int861wcscmp(const wchar_t *s1, const wchar_t *s2)862{863864while (*s1 == *s2++) {865if (*s1++ == L'\0')866return 0;867}868if (*s1 > *--s2)869return 1;870else871return -1;872}873#endif874875/* Verify that two wide strings are equal, dump them if not. */876int877assertion_equal_wstring(const char *file, int line,878const wchar_t *v1, const char *e1,879const wchar_t *v2, const char *e2,880void *extra)881{882assertion_count(file, line);883if (v1 == v2)884return (1);885if (v1 != NULL && v2 != NULL && wcscmp(v1, v2) == 0)886return (1);887failure_start(file, line, "%s != %s", e1, e2);888wcsdump(e1, v1);889wcsdump(e2, v2);890failure_finish(extra);891return (0);892}893894/*895* Pretty standard hexdump routine. As a bonus, if ref != NULL, then896* any bytes in p that differ from ref will be highlighted with '_'897* before and after the hex value.898*/899static void900hexdump(const char *p, const char *ref, size_t l, size_t offset)901{902size_t i, j;903char sep;904905if (p == NULL) {906logprintf("(null)\n");907return;908}909for(i=0; i < l; i+=16) {910logprintf("%04x", (unsigned)(i + offset));911sep = ' ';912for (j = 0; j < 16 && i + j < l; j++) {913if (ref != NULL && p[i + j] != ref[i + j])914sep = '_';915logprintf("%c%02x", sep, 0xff & (unsigned int)p[i+j]);916if (ref != NULL && p[i + j] == ref[i + j])917sep = ' ';918}919for (; j < 16; j++) {920logprintf("%c ", sep);921sep = ' ';922}923logprintf("%c", sep);924for (j=0; j < 16 && i + j < l; j++) {925int c = p[i + j];926if (c >= ' ' && c <= 126)927logprintf("%c", c);928else929logprintf(".");930}931logprintf("\n");932}933}934935/* Verify that two blocks of memory are the same, display the first936* block of differences if they're not. */937int938assertion_equal_mem(const char *file, int line,939const void *_v1, const char *e1,940const void *_v2, const char *e2,941size_t l, const char *ld, void *extra)942{943const char *v1 = (const char *)_v1;944const char *v2 = (const char *)_v2;945size_t offset;946947assertion_count(file, line);948if (v1 == v2 || (v1 != NULL && v2 != NULL && memcmp(v1, v2, l) == 0))949return (1);950if (v1 == NULL || v2 == NULL)951return (0);952953failure_start(file, line, "%s != %s", e1, e2);954logprintf(" size %s = %d\n", ld, (int)l);955/* Dump 48 bytes (3 lines) so that the first difference is956* in the second line. */957offset = 0;958while (l > 64 && memcmp(v1, v2, 32) == 0) {959/* Two lines agree, so step forward one line. */960v1 += 16;961v2 += 16;962l -= 16;963offset += 16;964}965logprintf(" Dump of %s\n", e1);966hexdump(v1, v2, l < 128 ? l : 128, offset);967logprintf(" Dump of %s\n", e2);968hexdump(v2, v1, l < 128 ? l : 128, offset);969logprintf("\n");970failure_finish(extra);971return (0);972}973974/* Verify that a block of memory is filled with the specified byte. */975int976assertion_memory_filled_with(const char *file, int line,977const void *_v1, const char *vd,978size_t l, const char *ld,979char b, const char *bd, void *extra)980{981const char *v1 = (const char *)_v1;982size_t c = 0;983size_t i;984(void)ld; /* UNUSED */985986assertion_count(file, line);987988for (i = 0; i < l; ++i) {989if (v1[i] == b) {990++c;991}992}993if (c == l)994return (1);995996failure_start(file, line, "%s (size %d) not filled with %s", vd, (int)l, bd);997logprintf(" Only %d bytes were correct\n", (int)c);998failure_finish(extra);999return (0);1000}10011002/* Verify that the named file exists and is empty. */1003int1004assertion_empty_file(const char *filename, int line, const char *f1)1005{1006char buff[1024];1007struct stat st;1008ssize_t s;1009FILE *f;10101011assertion_count(filename, line);10121013if (stat(f1, &st) != 0) {1014failure_start(filename, line, "Stat failed: %s", f1);1015failure_finish(NULL);1016return (0);1017}1018if (st.st_size == 0)1019return (1);10201021failure_start(filename, line, "File should be empty: %s", f1);1022logprintf(" File size: %d\n", (int)st.st_size);1023logprintf(" Contents:\n");1024f = fopen(f1, "rb");1025if (f == NULL) {1026logprintf(" Unable to open %s\n", f1);1027} else {1028s = ((off_t)sizeof(buff) < st.st_size) ?1029(ssize_t)sizeof(buff) : (ssize_t)st.st_size;1030s = fread(buff, 1, s, f);1031hexdump(buff, NULL, s, 0);1032fclose(f);1033}1034failure_finish(NULL);1035return (0);1036}10371038/* Verify that the named file exists and is not empty. */1039int1040assertion_non_empty_file(const char *filename, int line, const char *f1)1041{1042struct stat st;10431044assertion_count(filename, line);10451046if (stat(f1, &st) != 0) {1047failure_start(filename, line, "Stat failed: %s", f1);1048failure_finish(NULL);1049return (0);1050}1051if (st.st_size == 0) {1052failure_start(filename, line, "File empty: %s", f1);1053failure_finish(NULL);1054return (0);1055}1056return (1);1057}10581059/* Verify that two files have the same contents. */1060/* TODO: hexdump the first bytes that actually differ. */1061int1062assertion_equal_file(const char *filename, int line, const char *fn1, const char *fn2)1063{1064char buff1[1024];1065char buff2[1024];1066FILE *f1, *f2;1067int n1, n2;10681069assertion_count(filename, line);10701071f1 = fopen(fn1, "rb");1072f2 = fopen(fn2, "rb");1073if (f1 == NULL || f2 == NULL) {1074if (f1) fclose(f1);1075if (f2) fclose(f2);1076return (0);1077}1078for (;;) {1079n1 = (int)fread(buff1, 1, sizeof(buff1), f1);1080n2 = (int)fread(buff2, 1, sizeof(buff2), f2);1081if (n1 != n2)1082break;1083if (n1 == 0 && n2 == 0) {1084fclose(f1);1085fclose(f2);1086return (1);1087}1088if (memcmp(buff1, buff2, n1) != 0)1089break;1090}1091fclose(f1);1092fclose(f2);1093failure_start(filename, line, "Files not identical");1094logprintf(" file1=\"%s\"\n", fn1);1095logprintf(" file2=\"%s\"\n", fn2);1096failure_finish(NULL);1097return (0);1098}10991100/* Verify that the named file does exist. */1101int1102assertion_file_exists(const char *filename, int line, const char *f)1103{1104assertion_count(filename, line);11051106#if defined(_WIN32) && !defined(__CYGWIN__)1107if (!_access(f, 0))1108return (1);1109#else1110if (!access(f, F_OK))1111return (1);1112#endif1113failure_start(filename, line, "File should exist: %s", f);1114failure_finish(NULL);1115return (0);1116}11171118/* Verify that the named file doesn't exist. */1119int1120assertion_file_not_exists(const char *filename, int line, const char *f)1121{1122assertion_count(filename, line);11231124#if defined(_WIN32) && !defined(__CYGWIN__)1125if (_access(f, 0))1126return (1);1127#else1128if (access(f, F_OK))1129return (1);1130#endif1131failure_start(filename, line, "File should not exist: %s", f);1132failure_finish(NULL);1133return (0);1134}11351136/* Compare the contents of a file to a block of memory. */1137int1138assertion_file_contents(const char *filename, int line, const void *buff, int s, const char *fn)1139{1140char *contents;1141FILE *f;1142int n;11431144assertion_count(filename, line);11451146f = fopen(fn, "rb");1147if (f == NULL) {1148failure_start(filename, line,1149"File should exist: %s", fn);1150failure_finish(NULL);1151return (0);1152}1153contents = malloc(s * 2);1154n = (int)fread(contents, 1, s * 2, f);1155fclose(f);1156if (n == s && memcmp(buff, contents, s) == 0) {1157free(contents);1158return (1);1159}1160failure_start(filename, line, "File contents don't match");1161logprintf(" file=\"%s\"\n", fn);1162if (n > 0)1163hexdump(contents, buff, n > 512 ? 512 : n, 0);1164else {1165logprintf(" File empty, contents should be:\n");1166hexdump(buff, NULL, s > 512 ? 512 : s, 0);1167}1168failure_finish(NULL);1169free(contents);1170return (0);1171}11721173/* Check the contents of a text file, being tolerant of line endings. */1174int1175assertion_text_file_contents(const char *filename, int line, const char *buff, const char *fn)1176{1177char *contents;1178const char *btxt, *ftxt;1179FILE *f;1180int n, s;11811182assertion_count(filename, line);1183f = fopen(fn, "r");1184if (f == NULL) {1185failure_start(filename, line,1186"File doesn't exist: %s", fn);1187failure_finish(NULL);1188return (0);1189}1190s = (int)strlen(buff);1191contents = malloc(s * 2 + 128);1192n = (int)fread(contents, 1, s * 2 + 128 - 1, f);1193if (n >= 0)1194contents[n] = '\0';1195fclose(f);1196/* Compare texts. */1197btxt = buff;1198ftxt = (const char *)contents;1199while (*btxt != '\0' && *ftxt != '\0') {1200if (*btxt == *ftxt) {1201++btxt;1202++ftxt;1203continue;1204}1205if (btxt[0] == '\n' && ftxt[0] == '\r' && ftxt[1] == '\n') {1206/* Pass over different new line characters. */1207++btxt;1208ftxt += 2;1209continue;1210}1211break;1212}1213if (*btxt == '\0' && *ftxt == '\0') {1214free(contents);1215return (1);1216}1217failure_start(filename, line, "Contents don't match");1218logprintf(" file=\"%s\"\n", fn);1219if (n > 0) {1220hexdump(contents, buff, n, 0);1221logprintf(" expected\n");1222hexdump(buff, contents, s, 0);1223} else {1224logprintf(" File empty, contents should be:\n");1225hexdump(buff, NULL, s, 0);1226}1227failure_finish(NULL);1228free(contents);1229return (0);1230}12311232/* Verify that a text file contains the specified lines, regardless of order */1233/* This could be more efficient if we sorted both sets of lines, etc, but1234* since this is used only for testing and only ever deals with a dozen or so1235* lines at a time, this relatively crude approach is just fine. */1236int1237assertion_file_contains_lines_any_order(const char *file, int line,1238const char *pathname, const char *lines[])1239{1240char *buff;1241size_t buff_size;1242size_t expected_count, actual_count, i, j;1243char **expected = NULL;1244char *p, **actual = NULL;1245char c;1246int expected_failure = 0, actual_failure = 0;12471248assertion_count(file, line);12491250buff = slurpfile(&buff_size, "%s", pathname);1251if (buff == NULL) {1252failure_start(pathname, line, "Can't read file: %s", pathname);1253failure_finish(NULL);1254return (0);1255}12561257/* Make a copy of the provided lines and count up the expected1258* file size. */1259for (i = 0; lines[i] != NULL; ++i) {1260}1261expected_count = i;1262if (expected_count) {1263expected = calloc(expected_count, sizeof(*expected));1264if (expected == NULL) {1265failure_start(pathname, line, "Can't allocate memory");1266failure_finish(NULL);1267goto cleanup;1268}1269for (i = 0; lines[i] != NULL; ++i) {1270expected[i] = strdup(lines[i]);1271if (expected[i] == NULL) {1272failure_start(pathname, line, "Can't allocate memory");1273failure_finish(NULL);1274goto cleanup;1275}1276}1277}12781279/* Break the file into lines */1280actual_count = 0;1281for (c = '\0', p = buff; p < buff + buff_size; ++p) {1282if (*p == '\x0d' || *p == '\x0a')1283*p = '\0';1284if (c == '\0' && *p != '\0')1285++actual_count;1286c = *p;1287}1288if (actual_count) {1289actual = calloc(actual_count, sizeof(char *));1290if (actual == NULL) {1291failure_start(pathname, line, "Can't allocate memory");1292failure_finish(NULL);1293goto cleanup;1294}1295for (j = 0, p = buff; p < buff + buff_size;1296p += 1 + strlen(p)) {1297if (*p != '\0') {1298actual[j] = p;1299++j;1300}1301}1302}13031304/* Erase matching lines from both lists */1305for (i = 0; i < expected_count; ++i) {1306for (j = 0; j < actual_count; ++j) {1307if (actual[j] == NULL)1308continue;1309if (strcmp(expected[i], actual[j]) == 0) {1310free(expected[i]);1311expected[i] = NULL;1312actual[j] = NULL;1313break;1314}1315}1316}13171318/* If there's anything left, it's a failure */1319for (i = 0; i < expected_count; ++i) {1320if (expected[i] != NULL)1321++expected_failure;1322}1323for (j = 0; j < actual_count; ++j) {1324if (actual[j] != NULL)1325++actual_failure;1326}1327if (expected_failure == 0 && actual_failure == 0) {1328free(actual);1329free(expected);1330free(buff);1331return (1);1332}1333failure_start(file, line, "File doesn't match: %s", pathname);1334for (i = 0; i < expected_count; ++i) {1335if (expected[i] != NULL) {1336logprintf(" Expected but not present: %s\n", expected[i]);1337free(expected[i]);1338expected[i] = NULL;1339}1340}1341for (j = 0; j < actual_count; ++j) {1342if (actual[j] != NULL)1343logprintf(" Present but not expected: %s\n", actual[j]);1344}1345failure_finish(NULL);1346cleanup:1347free(actual);1348if (expected != NULL) {1349for (i = 0; i < expected_count; ++i)1350if (expected[i] != NULL)1351free(expected[i]);1352free(expected);1353}1354free(buff);1355return (0);1356}13571358/* Verify that a text file does not contains the specified strings */1359int1360assertion_file_contains_no_invalid_strings(const char *file, int line,1361const char *pathname, const char *strings[])1362{1363char *buff;1364int i;13651366buff = slurpfile(NULL, "%s", pathname);1367if (buff == NULL) {1368failure_start(file, line, "Can't read file: %s", pathname);1369failure_finish(NULL);1370return (0);1371}13721373for (i = 0; strings[i] != NULL; ++i) {1374if (strstr(buff, strings[i]) != NULL) {1375failure_start(file, line, "Invalid string in %s: %s", pathname,1376strings[i]);1377failure_finish(NULL);1378free(buff);1379return(0);1380}1381}13821383free(buff);1384return (0);1385}13861387/* Test that two paths point to the same file. */1388/* As a side-effect, asserts that both files exist. */1389static int1390is_hardlink(const char *file, int line,1391const char *path1, const char *path2)1392{1393#if defined(_WIN32) && !defined(__CYGWIN__)1394BY_HANDLE_FILE_INFORMATION bhfi1, bhfi2;1395int r;13961397assertion_count(file, line);1398r = my_GetFileInformationByName(path1, &bhfi1);1399if (r == 0) {1400failure_start(file, line, "File %s can't be inspected?", path1);1401failure_finish(NULL);1402return (0);1403}1404r = my_GetFileInformationByName(path2, &bhfi2);1405if (r == 0) {1406failure_start(file, line, "File %s can't be inspected?", path2);1407failure_finish(NULL);1408return (0);1409}1410return (bhfi1.dwVolumeSerialNumber == bhfi2.dwVolumeSerialNumber1411&& bhfi1.nFileIndexHigh == bhfi2.nFileIndexHigh1412&& bhfi1.nFileIndexLow == bhfi2.nFileIndexLow);1413#else1414struct stat st1, st2;1415int r;14161417assertion_count(file, line);1418r = lstat(path1, &st1);1419if (r != 0) {1420failure_start(file, line, "File should exist: %s", path1);1421failure_finish(NULL);1422return (0);1423}1424r = lstat(path2, &st2);1425if (r != 0) {1426failure_start(file, line, "File should exist: %s", path2);1427failure_finish(NULL);1428return (0);1429}1430return (st1.st_ino == st2.st_ino && st1.st_dev == st2.st_dev);1431#endif1432}14331434int1435assertion_is_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 are not hardlinked", path1, path2);1442failure_finish(NULL);1443return (0);1444}14451446int1447assertion_is_not_hardlink(const char *file, int line,1448const char *path1, const char *path2)1449{1450if (!is_hardlink(file, line, path1, path2))1451return (1);1452failure_start(file, line,1453"Files %s and %s should not be hardlinked", path1, path2);1454failure_finish(NULL);1455return (0);1456}14571458/* Verify a/b/mtime of 'pathname'. */1459/* If 'recent', verify that it's within last 10 seconds. */1460static int1461assertion_file_time(const char *file, int line,1462const char *pathname, long t, long nsec, char type, int recent)1463{1464long long filet, filet_nsec;1465int r;14661467#if defined(_WIN32) && !defined(__CYGWIN__)1468#define EPOC_TIME (116444736000000000ULL)1469FILETIME fxtime, fbirthtime, fatime, fmtime;1470ULARGE_INTEGER wintm;1471HANDLE h;1472fxtime.dwLowDateTime = 0;1473fxtime.dwHighDateTime = 0;14741475assertion_count(file, line);1476/* Note: FILE_FLAG_BACKUP_SEMANTICS applies to open1477* a directory file. If not, CreateFile() will fail when1478* the pathname is a directory. */1479h = CreateFileA(pathname, FILE_READ_ATTRIBUTES, 0, NULL,1480OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);1481if (h == INVALID_HANDLE_VALUE) {1482failure_start(file, line, "Can't access %s\n", pathname);1483failure_finish(NULL);1484return (0);1485}1486r = GetFileTime(h, &fbirthtime, &fatime, &fmtime);1487switch (type) {1488case 'a': fxtime = fatime; break;1489case 'b': fxtime = fbirthtime; break;1490case 'm': fxtime = fmtime; break;1491}1492CloseHandle(h);1493if (r == 0) {1494failure_start(file, line, "Can't GetFileTime %s\n", pathname);1495failure_finish(NULL);1496return (0);1497}1498wintm.LowPart = fxtime.dwLowDateTime;1499wintm.HighPart = fxtime.dwHighDateTime;1500filet = (wintm.QuadPart - EPOC_TIME) / 10000000;1501filet_nsec = ((wintm.QuadPart - EPOC_TIME) % 10000000) * 100;1502nsec = (nsec / 100) * 100; /* Round the request */1503#else1504struct stat st;15051506assertion_count(file, line);1507r = lstat(pathname, &st);1508if (r != 0) {1509failure_start(file, line, "Can't stat %s\n", pathname);1510failure_finish(NULL);1511return (0);1512}1513switch (type) {1514case 'a': filet = st.st_atime; break;1515case 'm': filet = st.st_mtime; break;1516case 'b': filet = 0; break;1517default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);1518exit(1);1519}1520#if defined(__FreeBSD__)1521switch (type) {1522case 'a': filet_nsec = st.st_atimespec.tv_nsec; break;1523case 'b': filet = st.st_birthtime;1524/* FreeBSD filesystems that don't support birthtime1525* (e.g., UFS1) always return -1 here. */1526if (filet == -1) {1527return (1);1528}1529filet_nsec = st.st_birthtimespec.tv_nsec; break;1530case 'm': filet_nsec = st.st_mtimespec.tv_nsec; break;1531default: fprintf(stderr, "INTERNAL: Bad type %c for file time", type);1532exit(1);1533}1534/* FreeBSD generally only stores to microsecond res, so round. */1535filet_nsec = (filet_nsec / 1000) * 1000;1536nsec = (nsec / 1000) * 1000;1537#else1538filet_nsec = nsec = 0; /* Generic POSIX only has whole seconds. */1539if (type == 'b') return (1); /* Generic POSIX doesn't have birthtime */1540#if defined(__HAIKU__)1541if (type == 'a') return (1); /* Haiku doesn't have atime. */1542#endif1543#endif1544#endif1545if (recent) {1546/* Check that requested time is up-to-date. */1547time_t now = time(NULL);1548if (filet < now - 10 || filet > now + 1) {1549failure_start(file, line,1550"File %s has %ctime %lld, %lld seconds ago\n",1551pathname, type, filet, now - filet);1552failure_finish(NULL);1553return (0);1554}1555} else if (filet != t || filet_nsec != nsec) {1556failure_start(file, line,1557"File %s has %ctime %lld.%09lld, expected %ld.%09ld",1558pathname, type, filet, filet_nsec, t, nsec);1559failure_finish(NULL);1560return (0);1561}1562return (1);1563}15641565/* Verify atime of 'pathname'. */1566int1567assertion_file_atime(const char *file, int line,1568const char *pathname, long t, long nsec)1569{1570return assertion_file_time(file, line, pathname, t, nsec, 'a', 0);1571}15721573/* Verify atime of 'pathname' is up-to-date. */1574int1575assertion_file_atime_recent(const char *file, int line, const char *pathname)1576{1577return assertion_file_time(file, line, pathname, 0, 0, 'a', 1);1578}15791580/* Verify birthtime of 'pathname'. */1581int1582assertion_file_birthtime(const char *file, int line,1583const char *pathname, long t, long nsec)1584{1585return assertion_file_time(file, line, pathname, t, nsec, 'b', 0);1586}15871588/* Verify birthtime of 'pathname' is up-to-date. */1589int1590assertion_file_birthtime_recent(const char *file, int line,1591const char *pathname)1592{1593return assertion_file_time(file, line, pathname, 0, 0, 'b', 1);1594}15951596/* Verify mode of 'pathname'. */1597int1598assertion_file_mode(const char *file, int line, const char *pathname, int expected_mode)1599{1600int mode;1601int r;16021603assertion_count(file, line);1604#if defined(_WIN32) && !defined(__CYGWIN__)1605failure_start(file, line, "assertFileMode not yet implemented for Windows");1606(void)mode; /* UNUSED */1607(void)r; /* UNUSED */1608(void)pathname; /* UNUSED */1609(void)expected_mode; /* UNUSED */1610#else1611{1612struct stat st;1613r = lstat(pathname, &st);1614mode = (int)(st.st_mode & 0777);1615}1616if (r == 0 && mode == expected_mode)1617return (1);1618failure_start(file, line, "File %s has mode %o, expected %o",1619pathname, (unsigned int)mode, (unsigned int)expected_mode);1620#endif1621failure_finish(NULL);1622return (0);1623}16241625/* Verify mtime of 'pathname'. */1626int1627assertion_file_mtime(const char *file, int line,1628const char *pathname, long t, long nsec)1629{1630return assertion_file_time(file, line, pathname, t, nsec, 'm', 0);1631}16321633/* Verify mtime of 'pathname' is up-to-date. */1634int1635assertion_file_mtime_recent(const char *file, int line, const char *pathname)1636{1637return assertion_file_time(file, line, pathname, 0, 0, 'm', 1);1638}16391640/* Verify number of links to 'pathname'. */1641int1642assertion_file_nlinks(const char *file, int line,1643const char *pathname, int nlinks)1644{1645#if defined(_WIN32) && !defined(__CYGWIN__)1646BY_HANDLE_FILE_INFORMATION bhfi;1647int r;16481649assertion_count(file, line);1650r = my_GetFileInformationByName(pathname, &bhfi);1651if (r != 0 && bhfi.nNumberOfLinks == (DWORD)nlinks)1652return (1);1653failure_start(file, line, "File %s has %jd links, expected %d",1654pathname, (intmax_t)bhfi.nNumberOfLinks, nlinks);1655failure_finish(NULL);1656return (0);1657#else1658struct stat st;1659int r;16601661assertion_count(file, line);1662r = lstat(pathname, &st);1663if (r == 0 && (int)st.st_nlink == nlinks)1664return (1);1665failure_start(file, line, "File %s has %jd links, expected %d",1666pathname, (intmax_t)st.st_nlink, nlinks);1667failure_finish(NULL);1668return (0);1669#endif1670}16711672/* Verify size of 'pathname'. */1673int1674assertion_file_size(const char *file, int line, const char *pathname, long size)1675{1676int64_t filesize;1677int r;16781679assertion_count(file, line);1680#if defined(_WIN32) && !defined(__CYGWIN__)1681{1682BY_HANDLE_FILE_INFORMATION bhfi;1683r = !my_GetFileInformationByName(pathname, &bhfi);1684filesize = ((int64_t)bhfi.nFileSizeHigh << 32) + bhfi.nFileSizeLow;1685}1686#else1687{1688struct stat st;1689r = lstat(pathname, &st);1690filesize = st.st_size;1691}1692#endif1693if (r == 0 && filesize == size)1694return (1);1695failure_start(file, line, "File %s has size %ld, expected %ld",1696pathname, (long)filesize, (long)size);1697failure_finish(NULL);1698return (0);1699}17001701/* Assert that 'pathname' is a dir. If mode >= 0, verify that too. */1702int1703assertion_is_dir(const char *file, int line, const char *pathname, int mode)1704{1705struct stat st;1706int r;17071708#if defined(_WIN32) && !defined(__CYGWIN__)1709(void)mode; /* UNUSED */1710#endif1711assertion_count(file, line);1712r = lstat(pathname, &st);1713if (r != 0) {1714failure_start(file, line, "Dir should exist: %s", pathname);1715failure_finish(NULL);1716return (0);1717}1718if (!S_ISDIR(st.st_mode)) {1719failure_start(file, line, "%s is not a dir", pathname);1720failure_finish(NULL);1721return (0);1722}1723#if !defined(_WIN32) || defined(__CYGWIN__)1724/* Windows doesn't handle permissions the same way as POSIX,1725* so just ignore the mode tests. */1726/* TODO: Can we do better here? */1727if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {1728failure_start(file, line, "Dir %s has wrong mode", pathname);1729logprintf(" Expected: 0%3o\n", (unsigned int)mode);1730logprintf(" Found: 0%3o\n", (unsigned int)st.st_mode & 07777);1731failure_finish(NULL);1732return (0);1733}1734#endif1735return (1);1736}17371738/* Verify that 'pathname' is a regular file. If 'mode' is >= 0,1739* verify that too. */1740int1741assertion_is_reg(const char *file, int line, const char *pathname, int mode)1742{1743struct stat st;1744int r;17451746#if defined(_WIN32) && !defined(__CYGWIN__)1747(void)mode; /* UNUSED */1748#endif1749assertion_count(file, line);1750r = lstat(pathname, &st);1751if (r != 0 || !S_ISREG(st.st_mode)) {1752failure_start(file, line, "File should exist: %s", pathname);1753failure_finish(NULL);1754return (0);1755}1756#if !defined(_WIN32) || defined(__CYGWIN__)1757/* Windows doesn't handle permissions the same way as POSIX,1758* so just ignore the mode tests. */1759/* TODO: Can we do better here? */1760if (mode >= 0 && (mode_t)mode != (st.st_mode & 07777)) {1761failure_start(file, line, "File %s has wrong mode", pathname);1762logprintf(" Expected: 0%3o\n", (unsigned int)mode);1763logprintf(" Found: 0%3o\n", (unsigned int)st.st_mode & 07777);1764failure_finish(NULL);1765return (0);1766}1767#endif1768return (1);1769}17701771/*1772* Check whether 'pathname' is a symbolic link. If 'contents' is1773* non-NULL, verify that the symlink has those contents.1774*1775* On platforms with directory symlinks, set isdir to 0 to test for a file1776* symlink and to 1 to test for a directory symlink. On other platforms1777* the variable is ignored.1778*/1779static int1780is_symlink(const char *file, int line,1781const char *pathname, const char *contents, int isdir)1782{1783#if defined(_WIN32) && !defined(__CYGWIN__)1784HANDLE h;1785DWORD inbytes;1786REPARSE_DATA_BUFFER *buf;1787BY_HANDLE_FILE_INFORMATION st;1788size_t len, len2;1789wchar_t *linknamew, *contentsw;1790const char *p;1791char *s, *pn;1792int ret = 0;1793BYTE *indata;1794const DWORD flag = FILE_FLAG_BACKUP_SEMANTICS |1795FILE_FLAG_OPEN_REPARSE_POINT;17961797/* Replace slashes with backslashes in pathname */1798pn = malloc(strlen(pathname) + 1);1799if (pn == NULL) {1800failure_start(file, line, "Can't allocate memory");1801failure_finish(NULL);1802return (0);1803}1804for (p = pathname, s = pn; *p != '\0'; p++, s++) {1805if (*p == '/')1806*s = '\\';1807else1808*s = *p;1809}1810*s = '\0';18111812h = CreateFileA(pn, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,1813flag, NULL);1814free(pn);1815if (h == INVALID_HANDLE_VALUE) {1816failure_start(file, line, "Can't access %s\n", pathname);1817failure_finish(NULL);1818return (0);1819}1820ret = GetFileInformationByHandle(h, &st);1821if (ret == 0) {1822failure_start(file, line,1823"Can't stat: %s", pathname);1824failure_finish(NULL);1825} else if ((st.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) {1826failure_start(file, line,1827"Not a symlink: %s", pathname);1828failure_finish(NULL);1829ret = 0;1830}1831if (isdir && ((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) {1832failure_start(file, line,1833"Not a directory symlink: %s", pathname);1834failure_finish(NULL);1835ret = 0;1836}1837if (!isdir &&1838((st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)) {1839failure_start(file, line,1840"Not a file symlink: %s", pathname);1841failure_finish(NULL);1842ret = 0;1843}1844if (ret == 0) {1845CloseHandle(h);1846return (0);1847}18481849indata = malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);1850ret = DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, NULL, 0, indata,18511024, &inbytes, NULL);1852CloseHandle(h);1853if (ret == 0) {1854free(indata);1855failure_start(file, line,1856"Could not retrieve symlink target: %s", pathname);1857failure_finish(NULL);1858return (0);1859}18601861buf = (REPARSE_DATA_BUFFER *) indata;1862if (buf->ReparseTag != IO_REPARSE_TAG_SYMLINK) {1863free(indata);1864/* File is not a symbolic link */1865failure_start(file, line,1866"Not a symlink: %s", pathname);1867failure_finish(NULL);1868return (0);1869}18701871if (contents == NULL) {1872free(indata);1873return (1);1874}18751876len = buf->SymbolicLinkReparseBuffer.SubstituteNameLength;18771878linknamew = malloc(len + sizeof(wchar_t));1879if (linknamew == NULL) {1880free(indata);1881return (0);1882}18831884memcpy(linknamew, &((BYTE *)buf->SymbolicLinkReparseBuffer.PathBuffer)1885[buf->SymbolicLinkReparseBuffer.SubstituteNameOffset], len);1886free(indata);18871888linknamew[len / sizeof(wchar_t)] = L'\0';18891890contentsw = malloc(len + sizeof(wchar_t));1891if (contentsw == NULL) {1892free(linknamew);1893return (0);1894}18951896len2 = mbsrtowcs(contentsw, &contents, (len + sizeof(wchar_t)1897/ sizeof(wchar_t)), NULL);18981899if (len2 > 0 && wcscmp(linknamew, contentsw) != 0)1900ret = 1;19011902free(linknamew);1903free(contentsw);1904return (ret);1905#else1906char buff[300];1907struct stat st;1908ssize_t linklen;1909int r;19101911(void)isdir; /* UNUSED */1912assertion_count(file, line);1913r = lstat(pathname, &st);1914if (r != 0) {1915failure_start(file, line,1916"Symlink should exist: %s", pathname);1917failure_finish(NULL);1918return (0);1919}1920if (!S_ISLNK(st.st_mode))1921return (0);1922if (contents == NULL)1923return (1);1924linklen = readlink(pathname, buff, sizeof(buff) - 1);1925if (linklen < 0) {1926failure_start(file, line, "Can't read symlink %s", pathname);1927failure_finish(NULL);1928return (0);1929}1930buff[linklen] = '\0';1931if (strcmp(buff, contents) != 0)1932return (0);1933return (1);1934#endif1935}19361937/* Assert that path is a symlink that (optionally) contains contents. */1938int1939assertion_is_symlink(const char *file, int line,1940const char *path, const char *contents, int isdir)1941{1942if (is_symlink(file, line, path, contents, isdir))1943return (1);1944if (contents)1945failure_start(file, line, "File %s is not a symlink to %s",1946path, contents);1947else1948failure_start(file, line, "File %s is not a symlink", path);1949failure_finish(NULL);1950return (0);1951}195219531954/* Create a directory and report any errors. */1955int1956assertion_make_dir(const char *file, int line, const char *dirname, int mode)1957{1958assertion_count(file, line);1959#if defined(_WIN32) && !defined(__CYGWIN__)1960(void)mode; /* UNUSED */1961if (0 == _mkdir(dirname))1962return (1);1963#else1964if (0 == mkdir(dirname, (mode_t)mode)) {1965if (0 == chmod(dirname, (mode_t)mode)) {1966assertion_file_mode(file, line, dirname, mode);1967return (1);1968}1969}1970#endif1971failure_start(file, line, "Could not create directory %s", dirname);1972failure_finish(NULL);1973return(0);1974}19751976/* Create a file with the specified contents and report any failures. */1977int1978assertion_make_file(const char *file, int line,1979const char *path, int mode, int csize, const void *contents)1980{1981#if defined(_WIN32) && !defined(__CYGWIN__)1982/* TODO: Rework this to set file mode as well. */1983FILE *f;1984(void)mode; /* UNUSED */1985assertion_count(file, line);1986f = fopen(path, "wb");1987if (f == NULL) {1988failure_start(file, line, "Could not create file %s", path);1989failure_finish(NULL);1990return (0);1991}1992if (contents != NULL) {1993size_t wsize;19941995if (csize < 0)1996wsize = strlen(contents);1997else1998wsize = (size_t)csize;1999if (wsize != fwrite(contents, 1, wsize, f)) {2000fclose(f);2001failure_start(file, line,2002"Could not write file %s", path);2003failure_finish(NULL);2004return (0);2005}2006}2007fclose(f);2008return (1);2009#else2010int fd;2011assertion_count(file, line);2012fd = open(path, O_CREAT | O_WRONLY, mode >= 0 ? mode : 0644);2013if (fd < 0) {2014failure_start(file, line, "Could not create %s", path);2015failure_finish(NULL);2016return (0);2017}2018#ifdef HAVE_FCHMOD2019if (0 != fchmod(fd, (mode_t)mode))2020#else2021if (0 != chmod(path, (mode_t)mode))2022#endif2023{2024failure_start(file, line, "Could not chmod %s", path);2025failure_finish(NULL);2026close(fd);2027return (0);2028}2029if (contents != NULL) {2030ssize_t wsize;20312032if (csize < 0)2033wsize = (ssize_t)strlen(contents);2034else2035wsize = (ssize_t)csize;2036if (wsize != write(fd, contents, wsize)) {2037close(fd);2038failure_start(file, line,2039"Could not write to %s", path);2040failure_finish(NULL);2041close(fd);2042return (0);2043}2044}2045close(fd);2046assertion_file_mode(file, line, path, mode);2047return (1);2048#endif2049}20502051/* Create a hardlink and report any failures. */2052int2053assertion_make_hardlink(const char *file, int line,2054const char *newpath, const char *linkto)2055{2056int succeeded;20572058assertion_count(file, line);2059#if defined(_WIN32) && !defined(__CYGWIN__)2060succeeded = my_CreateHardLinkA(newpath, linkto);2061#elif HAVE_LINK2062succeeded = !link(linkto, newpath);2063#else2064succeeded = 0;2065#endif2066if (succeeded)2067return (1);2068failure_start(file, line, "Could not create hardlink");2069logprintf(" New link: %s\n", newpath);2070logprintf(" Old name: %s\n", linkto);2071failure_finish(NULL);2072return(0);2073}20742075/*2076* Create a symlink and report any failures.2077*2078* Windows symlinks need to know if the target is a directory.2079*/2080int2081assertion_make_symlink(const char *file, int line,2082const char *newpath, const char *linkto, int targetIsDir)2083{2084#if defined(_WIN32) && !defined(__CYGWIN__)2085assertion_count(file, line);2086if (my_CreateSymbolicLinkA(newpath, linkto, targetIsDir))2087return (1);2088#elif HAVE_SYMLINK2089(void)targetIsDir; /* UNUSED */2090assertion_count(file, line);2091if (0 == symlink(linkto, newpath))2092return (1);2093#else2094(void)targetIsDir; /* UNUSED */2095#endif2096failure_start(file, line, "Could not create symlink");2097logprintf(" New link: %s\n", newpath);2098logprintf(" Old name: %s\n", linkto);2099failure_finish(NULL);2100return(0);2101}21022103/* Set umask, report failures. */2104int2105assertion_umask(const char *file, int line, int mask)2106{2107assertion_count(file, line);2108(void)file; /* UNUSED */2109(void)line; /* UNUSED */2110umask((mode_t)mask);2111return (1);2112}21132114/* Set times, report failures. */2115int2116assertion_utimes(const char *file, int line, const char *pathname,2117time_t at, suseconds_t at_nsec, time_t mt, suseconds_t mt_nsec)2118{2119int r;21202121#if defined(_WIN32) && !defined(__CYGWIN__)2122#define WINTIME(sec, nsec) (((sec * 10000000LL) + EPOC_TIME)\2123+ (((nsec)/1000)*10))2124HANDLE h;2125ULARGE_INTEGER wintm;2126FILETIME fatime, fmtime;2127FILETIME *pat, *pmt;21282129assertion_count(file, line);2130h = CreateFileA(pathname,GENERIC_READ | GENERIC_WRITE,2131FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,2132FILE_FLAG_BACKUP_SEMANTICS, NULL);2133if (h == INVALID_HANDLE_VALUE) {2134failure_start(file, line, "Can't access %s\n", pathname);2135failure_finish(NULL);2136return (0);2137}21382139if (at > 0 || at_nsec > 0) {2140wintm.QuadPart = WINTIME(at, at_nsec);2141fatime.dwLowDateTime = wintm.LowPart;2142fatime.dwHighDateTime = wintm.HighPart;2143pat = &fatime;2144} else2145pat = NULL;2146if (mt > 0 || mt_nsec > 0) {2147wintm.QuadPart = WINTIME(mt, mt_nsec);2148fmtime.dwLowDateTime = wintm.LowPart;2149fmtime.dwHighDateTime = wintm.HighPart;2150pmt = &fmtime;2151} else2152pmt = NULL;2153if (pat != NULL || pmt != NULL)2154r = SetFileTime(h, NULL, pat, pmt);2155else2156r = 1;2157CloseHandle(h);2158if (r == 0) {2159failure_start(file, line, "Can't SetFileTime %s\n", pathname);2160failure_finish(NULL);2161return (0);2162}2163return (1);2164#else /* defined(_WIN32) && !defined(__CYGWIN__) */2165struct stat st;2166struct timeval times[2];21672168#if !defined(__FreeBSD__)2169mt_nsec = at_nsec = 0; /* Generic POSIX only has whole seconds. */2170#endif2171if (mt == 0 && mt_nsec == 0 && at == 0 && at_nsec == 0)2172return (1);21732174r = lstat(pathname, &st);2175if (r < 0) {2176failure_start(file, line, "Can't stat %s\n", pathname);2177failure_finish(NULL);2178return (0);2179}21802181if (mt == 0 && mt_nsec == 0) {2182mt = st.st_mtime;2183#if defined(__FreeBSD__)2184mt_nsec = st.st_mtimespec.tv_nsec;2185/* FreeBSD generally only stores to microsecond res, so round. */2186mt_nsec = (mt_nsec / 1000) * 1000;2187#endif2188}2189if (at == 0 && at_nsec == 0) {2190at = st.st_atime;2191#if defined(__FreeBSD__)2192at_nsec = st.st_atimespec.tv_nsec;2193/* FreeBSD generally only stores to microsecond res, so round. */2194at_nsec = (at_nsec / 1000) * 1000;2195#endif2196}21972198times[1].tv_sec = mt;2199times[1].tv_usec = mt_nsec / 1000;22002201times[0].tv_sec = at;2202times[0].tv_usec = at_nsec / 1000;22032204#ifdef HAVE_LUTIMES2205r = lutimes(pathname, times);2206#else2207r = utimes(pathname, times);2208#endif2209if (r < 0) {2210failure_start(file, line, "Can't utimes %s\n", pathname);2211failure_finish(NULL);2212return (0);2213}2214return (1);2215#endif /* defined(_WIN32) && !defined(__CYGWIN__) */2216}22172218/* Compare file flags */2219int2220assertion_compare_fflags(const char *file, int line, const char *patha,2221const char *pathb, int nomatch)2222{2223#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)2224struct stat sa, sb;22252226assertion_count(file, line);22272228if (stat(patha, &sa) < 0)2229return (0);2230if (stat(pathb, &sb) < 0)2231return (0);2232if (!nomatch && sa.st_flags != sb.st_flags) {2233failure_start(file, line, "File flags should be identical: "2234"%s=%#010x %s=%#010x", patha, sa.st_flags, pathb,2235sb.st_flags);2236failure_finish(NULL);2237return (0);2238}2239if (nomatch && sa.st_flags == sb.st_flags) {2240failure_start(file, line, "File flags should be different: "2241"%s=%#010x %s=%#010x", patha, sa.st_flags, pathb,2242sb.st_flags);2243failure_finish(NULL);2244return (0);2245}2246#elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) && \2247defined(FS_NODUMP_FL)) || \2248(defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \2249&& defined(EXT2_NODUMP_FL))2250int fd, r, flagsa, flagsb;22512252assertion_count(file, line);2253fd = open(patha, O_RDONLY | O_NONBLOCK);2254if (fd < 0) {2255failure_start(file, line, "Can't open %s\n", patha);2256failure_finish(NULL);2257return (0);2258}2259r = ioctl(fd,2260#ifdef FS_IOC_GETFLAGS2261FS_IOC_GETFLAGS,2262#else2263EXT2_IOC_GETFLAGS,2264#endif2265&flagsa);2266close(fd);2267if (r < 0) {2268failure_start(file, line, "Can't get flags %s\n", patha);2269failure_finish(NULL);2270return (0);2271}2272fd = open(pathb, O_RDONLY | O_NONBLOCK);2273if (fd < 0) {2274failure_start(file, line, "Can't open %s\n", pathb);2275failure_finish(NULL);2276return (0);2277}2278r = ioctl(fd,2279#ifdef FS_IOC_GETFLAGS2280FS_IOC_GETFLAGS,2281#else2282EXT2_IOC_GETFLAGS,2283#endif2284&flagsb);2285close(fd);2286if (r < 0) {2287failure_start(file, line, "Can't get flags %s\n", pathb);2288failure_finish(NULL);2289return (0);2290}2291if (!nomatch && flagsa != flagsb) {2292failure_start(file, line, "File flags should be identical: "2293"%s=%#010x %s=%#010x", patha, flagsa, pathb, flagsb);2294failure_finish(NULL);2295return (0);2296}2297if (nomatch && flagsa == flagsb) {2298failure_start(file, line, "File flags should be different: "2299"%s=%#010x %s=%#010x", patha, flagsa, pathb, flagsb);2300failure_finish(NULL);2301return (0);2302}2303#else2304(void)patha; /* UNUSED */2305(void)pathb; /* UNUSED */2306(void)nomatch; /* UNUSED */2307assertion_count(file, line);2308#endif2309return (1);2310}23112312/* Set nodump, report failures. */2313int2314assertion_set_nodump(const char *file, int line, const char *pathname)2315{2316#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)2317int r;23182319assertion_count(file, line);2320r = chflags(pathname, UF_NODUMP);2321if (r < 0) {2322failure_start(file, line, "Can't set nodump %s\n", pathname);2323failure_finish(NULL);2324return (0);2325}2326#elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) && \2327defined(FS_NODUMP_FL)) || \2328(defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \2329&& defined(EXT2_NODUMP_FL))2330int fd, r, flags;23312332assertion_count(file, line);2333fd = open(pathname, O_RDONLY | O_NONBLOCK);2334if (fd < 0) {2335failure_start(file, line, "Can't open %s\n", pathname);2336failure_finish(NULL);2337return (0);2338}2339r = ioctl(fd,2340#ifdef FS_IOC_GETFLAGS2341FS_IOC_GETFLAGS,2342#else2343EXT2_IOC_GETFLAGS,2344#endif2345&flags);2346if (r < 0) {2347failure_start(file, line, "Can't get flags %s\n", pathname);2348failure_finish(NULL);2349return (0);2350}2351#ifdef FS_NODUMP_FL2352flags |= FS_NODUMP_FL;2353#else2354flags |= EXT2_NODUMP_FL;2355#endif23562357r = ioctl(fd,2358#ifdef FS_IOC_SETFLAGS2359FS_IOC_SETFLAGS,2360#else2361EXT2_IOC_SETFLAGS,2362#endif2363&flags);2364if (r < 0) {2365failure_start(file, line, "Can't set nodump %s\n", pathname);2366failure_finish(NULL);2367return (0);2368}2369close(fd);2370#else2371(void)pathname; /* UNUSED */2372assertion_count(file, line);2373#endif2374return (1);2375}23762377#ifdef PROGRAM2378static void assert_version_id(char **qq, size_t *ss)2379{2380char *q = *qq;2381size_t s = *ss;23822383/* Version number is a series of digits and periods. */2384while (s > 0 && (*q == '.' || (*q >= '0' && *q <= '9'))) {2385++q;2386--s;2387}23882389if (q[0] == 'd' && q[1] == 'e' && q[2] == 'v') {2390q += 3;2391s -= 3;2392}23932394/* Skip a single trailing a,b,c, or d. */2395if (*q == 'a' || *q == 'b' || *q == 'c' || *q == 'd')2396++q;23972398/* Version number terminated by space. */2399failure("No space after version: ``%s''", q);2400assert(s > 1);2401failure("No space after version: ``%s''", q);2402assert(*q == ' ');24032404++q; --s;24052406*qq = q;2407*ss = s;2408}240924102411/*2412* Check program version2413*/2414void assertVersion(const char *prog, const char *base)2415{2416int r;2417char *p, *q;2418size_t s;2419size_t prog_len = strlen(base);24202421r = systemf("%s --version >version.stdout 2>version.stderr", prog);2422if (r != 0)2423r = systemf("%s -W version >version.stdout 2>version.stderr",2424prog);24252426failure("Unable to run either %s --version or %s -W version",2427prog, prog);2428if (!assert(r == 0))2429return;24302431/* --version should generate nothing to stdout. */2432assertEmptyFile("version.stderr");24332434/* Verify format of version message. */2435q = p = slurpfile(&s, "version.stdout");24362437/* Version message should start with name of program, then space. */2438assert(s > prog_len + 1);24392440failure("Version must start with '%s': ``%s''", base, p);2441if (!assertEqualMem(q, base, prog_len)) {2442free(p);2443return;2444}24452446q += prog_len; s -= prog_len;24472448assert(*q == ' ');2449q++; s--;24502451assert_version_id(&q, &s);24522453/* Separator. */2454failure("No `-' between program name and versions: ``%s''", p);2455assertEqualMem(q, "- ", 2);2456q += 2; s -= 2;24572458failure("Not long enough for libarchive version: ``%s''", p);2459assert(s > 11);24602461failure("Libarchive version must start with `libarchive': ``%s''", p);2462assertEqualMem(q, "libarchive ", 11);24632464q += 11; s -= 11;24652466assert_version_id(&q, &s);24672468/* Skip arbitrary third-party version numbers. */2469while (s > 0 && (*q == ' ' || *q == '-' || *q == '/' || *q == '.' ||2470*q == '_' || isalnum((unsigned char)*q))) {2471++q;2472--s;2473}24742475/* All terminated by end-of-line. */2476assert(s >= 1);24772478/* Skip an optional CR character (e.g., Windows) */2479failure("Version output must end with \\n or \\r\\n");24802481if (*q == '\r') { ++q; --s; }2482assertEqualMem(q, "\n", 1);24832484free(p);2485}2486#endif /* PROGRAM */24872488/*2489*2490* UTILITIES for use by tests.2491*2492*/24932494/*2495* Check whether platform supports symlinks. This is intended2496* for tests to use in deciding whether to bother testing symlink2497* support; if the platform doesn't support symlinks, there's no point2498* in checking whether the program being tested can create them.2499*2500* Note that the first time this test is called, we actually go out to2501* disk to create and verify a symlink. This is necessary because2502* symlink support is actually a property of a particular filesystem2503* and can thus vary between directories on a single system. After2504* the first call, this returns the cached result from memory, so it's2505* safe to call it as often as you wish.2506*/2507int2508canSymlink(void)2509{2510/* Remember the test result */2511static int value = 0, tested = 0;2512if (tested)2513return (value);25142515++tested;2516assertion_make_file(__FILE__, __LINE__, "canSymlink.0", 0644, 1, "a");2517/* Note: Cygwin has its own symlink() emulation that does not2518* use the Win32 CreateSymbolicLink() function. */2519#if defined(_WIN32) && !defined(__CYGWIN__)2520value = my_CreateSymbolicLinkA("canSymlink.1", "canSymlink.0", 0)2521&& is_symlink(__FILE__, __LINE__, "canSymlink.1", "canSymlink.0",25220);2523#elif HAVE_SYMLINK2524value = (0 == symlink("canSymlink.0", "canSymlink.1"))2525&& is_symlink(__FILE__, __LINE__, "canSymlink.1","canSymlink.0",25260);2527#endif2528return (value);2529}25302531/* Platform-dependent options for hiding the output of a subcommand. */2532#if defined(_WIN32) && !defined(__CYGWIN__)2533static const char *redirectArgs = ">NUL 2>NUL"; /* Win32 cmd.exe */2534#else2535static const char *redirectArgs = ">/dev/null 2>/dev/null"; /* POSIX 'sh' */2536#endif25372538/*2539* Can this platform run the specified command?2540*/2541int2542canRunCommand(const char *cmd, int *tested)2543{2544int value = tested ? *tested : 0;2545if (!value) {2546value = systemf("%s %s", cmd, redirectArgs) ? -1 : +1;2547if (tested)2548*tested = value;2549}2550return (value > 0);2551}25522553#define CAN_RUN_FUNC(Program, Command) \2554int can##Program(void) { \2555static int tested = 0; \2556return canRunCommand((Command), &tested); \2557}25582559/*2560* Can this platform run the bzip2 program?2561*/2562CAN_RUN_FUNC(Bzip2, "bzip2 --help")25632564/*2565* Can this platform run the grzip program?2566*/2567CAN_RUN_FUNC(Grzip, "grzip -V")25682569/*2570* Can this platform run the gzip program?2571*/2572CAN_RUN_FUNC(Gzip, "gzip --help")25732574/*2575* Can this platform run the lrzip program?2576*/2577CAN_RUN_FUNC(Lrzip, "lrzip -V")25782579/*2580* Can this platform run the lz4 program?2581*/2582CAN_RUN_FUNC(Lz4, "lz4 --help")25832584/*2585* Can this platform run the zstd program?2586*/2587CAN_RUN_FUNC(Zstd, "zstd --help")25882589/*2590* Can this platform run the lzip program?2591*/2592CAN_RUN_FUNC(Lzip, "lzip --help")25932594/*2595* Can this platform run the lzma program?2596*/2597CAN_RUN_FUNC(Lzma, "lzma --help")25982599/*2600* Can this platform run the lzop program?2601*/2602CAN_RUN_FUNC(Lzop, "lzop --help")26032604/*2605* Can this platform run the xz program?2606*/2607CAN_RUN_FUNC(Xz, "xz --help")26082609/*2610* Can this filesystem handle nodump flags.2611*/2612int2613canNodump(void)2614{2615#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)2616const char *path = "cannodumptest";2617struct stat sb;26182619assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);2620if (chflags(path, UF_NODUMP) < 0)2621return (0);2622if (stat(path, &sb) < 0)2623return (0);2624if (sb.st_flags & UF_NODUMP)2625return (1);2626#elif (defined(FS_IOC_GETFLAGS) && defined(HAVE_WORKING_FS_IOC_GETFLAGS) \2627&& defined(FS_NODUMP_FL)) || \2628(defined(EXT2_IOC_GETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS) \2629&& defined(EXT2_NODUMP_FL))2630const char *path = "cannodumptest";2631int fd, r, flags;26322633assertion_make_file(__FILE__, __LINE__, path, 0644, 0, NULL);2634fd = open(path, O_RDONLY | O_NONBLOCK);2635if (fd < 0)2636return (0);2637r = ioctl(fd,2638#ifdef FS_IOC_GETFLAGS2639FS_IOC_GETFLAGS,2640#else2641EXT2_IOC_GETFLAGS,2642#endif2643&flags);2644if (r < 0)2645return (0);2646#ifdef FS_NODUMP_FL2647flags |= FS_NODUMP_FL;2648#else2649flags |= EXT2_NODUMP_FL;2650#endif2651r = ioctl(fd,2652#ifdef FS_IOC_SETFLAGS2653FS_IOC_SETFLAGS,2654#else2655EXT2_IOC_SETFLAGS,2656#endif2657&flags);2658if (r < 0)2659return (0);2660close(fd);2661fd = open(path, O_RDONLY | O_NONBLOCK);2662if (fd < 0)2663return (0);2664r = ioctl(fd,2665#ifdef FS_IOC_GETFLAGS2666FS_IOC_GETFLAGS,2667#else2668EXT2_IOC_GETFLAGS,2669#endif2670&flags);2671if (r < 0)2672return (0);2673close(fd);2674#ifdef FS_NODUMP_FL2675if (flags & FS_NODUMP_FL)2676#else2677if (flags & EXT2_NODUMP_FL)2678#endif2679return (1);2680#endif2681return (0);2682}26832684/* Get extended attribute value from a path */2685void *2686getXattr(const char *path, const char *name, size_t *sizep)2687{2688void *value = NULL;2689#if ARCHIVE_XATTR_SUPPORT2690ssize_t size;2691#if ARCHIVE_XATTR_LINUX2692size = lgetxattr(path, name, NULL, 0);2693#elif ARCHIVE_XATTR_DARWIN2694size = getxattr(path, name, NULL, 0, 0, XATTR_NOFOLLOW);2695#elif ARCHIVE_XATTR_AIX2696size = lgetea(path, name, NULL, 0);2697#elif ARCHIVE_XATTR_FREEBSD2698size = extattr_get_link(path, EXTATTR_NAMESPACE_USER, name + 5,2699NULL, 0);2700#endif27012702if (size >= 0) {2703value = malloc(size);2704#if ARCHIVE_XATTR_LINUX2705size = lgetxattr(path, name, value, size);2706#elif ARCHIVE_XATTR_DARWIN2707size = getxattr(path, name, value, size, 0, XATTR_NOFOLLOW);2708#elif ARCHIVE_XATTR_AIX2709size = lgetea(path, name, value, size);2710#elif ARCHIVE_XATTR_FREEBSD2711size = extattr_get_link(path, EXTATTR_NAMESPACE_USER, name + 5,2712value, size);2713#endif2714if (size < 0) {2715free(value);2716value = NULL;2717}2718}2719if (size < 0)2720*sizep = 0;2721else2722*sizep = (size_t)size;2723#else /* !ARCHIVE_XATTR_SUPPORT */2724(void)path; /* UNUSED */2725(void)name; /* UNUSED */2726*sizep = 0;2727#endif /* !ARCHIVE_XATTR_SUPPORT */2728return (value);2729}27302731/*2732* Set extended attribute on a path2733* Returns 0 on error, 1 on success2734*/2735int2736setXattr(const char *path, const char *name, const void *value, size_t size)2737{2738#if ARCHIVE_XATTR_SUPPORT2739#if ARCHIVE_XATTR_LINUX2740if (lsetxattr(path, name, value, size, 0) == 0)2741#elif ARCHIVE_XATTR_DARWIN2742if (setxattr(path, name, value, size, 0, XATTR_NOFOLLOW) == 0)2743#elif ARCHIVE_XATTR_AIX2744if (lsetea(path, name, value, size, 0) == 0)2745#elif ARCHIVE_XATTR_FREEBSD2746if (extattr_set_link(path, EXTATTR_NAMESPACE_USER, name + 5, value,2747size) > -1)2748#else2749if (0)2750#endif2751return (1);2752#else /* !ARCHIVE_XATTR_SUPPORT */2753(void)path; /* UNUSED */2754(void)name; /* UNUSED */2755(void)value; /* UNUSED */2756(void)size; /* UNUSED */2757#endif /* !ARCHIVE_XATTR_SUPPORT */2758return (0);2759}27602761#if ARCHIVE_ACL_SUNOS2762/* Fetch ACLs on Solaris using acl() or facl() */2763void *2764sunacl_get(int cmd, int *aclcnt, int fd, const char *path)2765{2766int cnt, cntcmd;2767size_t size;2768void *aclp;27692770if (cmd == GETACL) {2771cntcmd = GETACLCNT;2772size = sizeof(aclent_t);2773}2774#if ARCHIVE_ACL_SUNOS_NFS42775else if (cmd == ACE_GETACL) {2776cntcmd = ACE_GETACLCNT;2777size = sizeof(ace_t);2778}2779#endif2780else {2781errno = EINVAL;2782*aclcnt = -1;2783return (NULL);2784}27852786aclp = NULL;2787cnt = -2;2788while (cnt == -2 || (cnt == -1 && errno == ENOSPC)) {2789if (path != NULL)2790cnt = acl(path, cntcmd, 0, NULL);2791else2792cnt = facl(fd, cntcmd, 0, NULL);27932794if (cnt > 0) {2795if (aclp == NULL)2796aclp = malloc(cnt * size);2797else2798aclp = realloc(NULL, cnt * size);2799if (aclp != NULL) {2800if (path != NULL)2801cnt = acl(path, cmd, cnt, aclp);2802else2803cnt = facl(fd, cmd, cnt, aclp);2804}2805} else {2806free(aclp);2807aclp = NULL;2808break;2809}2810}28112812*aclcnt = cnt;2813return (aclp);2814}2815#endif /* ARCHIVE_ACL_SUNOS */28162817/*2818* Set test ACLs on a path2819* Return values:2820* 0: error setting ACLs2821* ARCHIVE_TEST_ACL_TYPE_POSIX1E: POSIX.1E ACLs have been set2822* ARCHIVE_TEST_ACL_TYPE_NFS4: NFSv4 or extended ACLs have been set2823*/2824int2825setTestAcl(const char *path)2826{2827#if ARCHIVE_ACL_SUPPORT2828int r = 1;2829#if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_DARWIN2830acl_t acl;2831#endif2832#if ARCHIVE_ACL_LIBRICHACL2833struct richacl *richacl;2834#endif2835#if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_FREEBSD2836const char *acltext_posix1e = "user:1:rw-,"2837"group:15:r-x,"2838"user::rwx,"2839"group::rwx,"2840"other::r-x,"2841"mask::rwx";2842#elif ARCHIVE_ACL_SUNOS /* Solaris POSIX.1e */2843aclent_t aclp_posix1e[] = {2844{ USER_OBJ, -1, 4 | 2 | 1 },2845{ USER, 1, 4 | 2 },2846{ GROUP_OBJ, -1, 4 | 2 | 1 },2847{ GROUP, 15, 4 | 1 },2848{ CLASS_OBJ, -1, 4 | 2 | 1 },2849{ OTHER_OBJ, -1, 4 | 2 | 1 }2850};2851#endif2852#if ARCHIVE_ACL_FREEBSD /* FreeBSD NFS4 */2853const char *acltext_nfs4 = "user:1:rwpaRcs::allow:1,"2854"group:15:rxaRcs::allow:15,"2855"owner@:rwpxaARWcCos::allow,"2856"group@:rwpxaRcs::allow,"2857"everyone@:rxaRcs::allow";2858#elif ARCHIVE_ACL_LIBRICHACL2859const char *acltext_nfs4 = "owner:rwpxaARWcCoS::mask,"2860"group:rwpxaRcS::mask,"2861"other:rxaRcS::mask,"2862"user:1:rwpaRcS::allow,"2863"group:15:rxaRcS::allow,"2864"owner@:rwpxaARWcCoS::allow,"2865"group@:rwpxaRcS::allow,"2866"everyone@:rxaRcS::allow";2867#elif ARCHIVE_ACL_SUNOS_NFS4 /* Solaris NFS4 */2868ace_t aclp_nfs4[] = {2869{ 1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |2870ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS | ACE_READ_ACL |2871ACE_SYNCHRONIZE, 0, ACE_ACCESS_ALLOWED_ACE_TYPE },2872{ 15, ACE_READ_DATA | ACE_EXECUTE | ACE_READ_ATTRIBUTES |2873ACE_READ_NAMED_ATTRS | ACE_READ_ACL | ACE_SYNCHRONIZE,2874ACE_IDENTIFIER_GROUP, ACE_ACCESS_ALLOWED_ACE_TYPE },2875{ -1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |2876ACE_EXECUTE | ACE_READ_ATTRIBUTES | ACE_WRITE_ATTRIBUTES |2877ACE_READ_NAMED_ATTRS | ACE_WRITE_NAMED_ATTRS |2878ACE_READ_ACL | ACE_WRITE_ACL | ACE_WRITE_OWNER | ACE_SYNCHRONIZE,2879ACE_OWNER, ACE_ACCESS_ALLOWED_ACE_TYPE },2880{ -1, ACE_READ_DATA | ACE_WRITE_DATA | ACE_APPEND_DATA |2881ACE_EXECUTE | ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS |2882ACE_READ_ACL | ACE_SYNCHRONIZE, ACE_GROUP | ACE_IDENTIFIER_GROUP,2883ACE_ACCESS_ALLOWED_ACE_TYPE },2884{ -1, ACE_READ_DATA | ACE_EXECUTE | ACE_READ_ATTRIBUTES |2885ACE_READ_NAMED_ATTRS | ACE_READ_ACL | ACE_SYNCHRONIZE,2886ACE_EVERYONE, ACE_ACCESS_ALLOWED_ACE_TYPE }2887};2888#elif ARCHIVE_ACL_DARWIN /* Mac OS X */2889acl_entry_t aclent;2890acl_permset_t permset;2891const uid_t uid = 1;2892uuid_t uuid;2893const acl_perm_t acl_perms[] = {2894ACL_READ_DATA,2895ACL_WRITE_DATA,2896ACL_APPEND_DATA,2897ACL_EXECUTE,2898ACL_READ_ATTRIBUTES,2899ACL_READ_EXTATTRIBUTES,2900ACL_READ_SECURITY,2901#if HAVE_DECL_ACL_SYNCHRONIZE2902ACL_SYNCHRONIZE2903#endif2904};2905#endif /* ARCHIVE_ACL_DARWIN */29062907#if ARCHIVE_ACL_FREEBSD2908acl = acl_from_text(acltext_nfs4);2909failure("acl_from_text() error: %s", strerror(errno));2910if (assert(acl != NULL) == 0)2911return (0);2912#elif ARCHIVE_ACL_LIBRICHACL2913richacl = richacl_from_text(acltext_nfs4, NULL, NULL);2914failure("richacl_from_text() error: %s", strerror(errno));2915if (assert(richacl != NULL) == 0)2916return (0);2917#elif ARCHIVE_ACL_DARWIN2918acl = acl_init(1);2919failure("acl_init() error: %s", strerror(errno));2920if (assert(acl != NULL) == 0)2921return (0);2922r = acl_create_entry(&acl, &aclent);2923failure("acl_create_entry() error: %s", strerror(errno));2924if (assertEqualInt(r, 0) == 0)2925goto testacl_free;2926r = acl_set_tag_type(aclent, ACL_EXTENDED_ALLOW);2927failure("acl_set_tag_type() error: %s", strerror(errno));2928if (assertEqualInt(r, 0) == 0)2929goto testacl_free;2930r = acl_get_permset(aclent, &permset);2931failure("acl_get_permset() error: %s", strerror(errno));2932if (assertEqualInt(r, 0) == 0)2933goto testacl_free;2934for (size_t i = 0; i < nitems(acl_perms); i++) {2935r = acl_add_perm(permset, acl_perms[i]);2936failure("acl_add_perm() error: %s", strerror(errno));2937if (assertEqualInt(r, 0) == 0)2938goto testacl_free;2939}2940r = acl_set_permset(aclent, permset);2941failure("acl_set_permset() error: %s", strerror(errno));2942if (assertEqualInt(r, 0) == 0)2943goto testacl_free;2944r = mbr_uid_to_uuid(uid, uuid);2945failure("mbr_uid_to_uuid() error: %s", strerror(errno));2946if (assertEqualInt(r, 0) == 0)2947goto testacl_free;2948r = acl_set_qualifier(aclent, uuid);2949failure("acl_set_qualifier() error: %s", strerror(errno));2950if (assertEqualInt(r, 0) == 0)2951goto testacl_free;2952#endif /* ARCHIVE_ACL_DARWIN */29532954#if ARCHIVE_ACL_NFS42955#if ARCHIVE_ACL_FREEBSD2956r = acl_set_file(path, ACL_TYPE_NFS4, acl);2957acl_free(acl);2958#elif ARCHIVE_ACL_LIBRICHACL2959r = richacl_set_file(path, richacl);2960richacl_free(richacl);2961#elif ARCHIVE_ACL_SUNOS_NFS42962r = acl(path, ACE_SETACL,2963(int)(sizeof(aclp_nfs4)/sizeof(aclp_nfs4[0])), aclp_nfs4);2964#elif ARCHIVE_ACL_DARWIN2965r = acl_set_file(path, ACL_TYPE_EXTENDED, acl);2966acl_free(acl);2967#endif2968if (r == 0)2969return (ARCHIVE_TEST_ACL_TYPE_NFS4);2970#endif /* ARCHIVE_ACL_NFS4 */29712972#if ARCHIVE_ACL_POSIX1E2973#if ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_LIBACL2974acl = acl_from_text(acltext_posix1e);2975failure("acl_from_text() error: %s", strerror(errno));2976if (assert(acl != NULL) == 0)2977return (0);29782979r = acl_set_file(path, ACL_TYPE_ACCESS, acl);2980acl_free(acl);2981#elif ARCHIVE_ACL_SUNOS2982r = acl(path, SETACL,2983(int)(sizeof(aclp_posix1e)/sizeof(aclp_posix1e[0])), aclp_posix1e);2984#endif2985if (r == 0)2986return (ARCHIVE_TEST_ACL_TYPE_POSIX1E);2987else2988return (0);2989#endif /* ARCHIVE_ACL_POSIX1E */2990#if ARCHIVE_ACL_DARWIN2991testacl_free:2992acl_free(acl);2993#endif2994#endif /* ARCHIVE_ACL_SUPPORT */2995(void)path; /* UNUSED */2996return (0);2997}29982999/*3000* Sleep as needed; useful for verifying disk timestamp changes by3001* ensuring that the wall-clock time has actually changed before we3002* go back to re-read something from disk.3003*/3004void3005sleepUntilAfter(time_t t)3006{3007while (t >= time(NULL))3008#if defined(_WIN32) && !defined(__CYGWIN__)3009Sleep(500);3010#else3011sleep(1);3012#endif3013}30143015/*3016* Call standard system() call, but build up the command line using3017* sprintf() conventions.3018*/3019int3020systemf(const char *fmt, ...)3021{3022char buff[8192];3023#if USE_POSIX_SPAWN3024char *argv[] = { "/bin/sh", "-c", buff, NULL };3025pid_t pid;3026#endif3027va_list ap;3028int r;30293030va_start(ap, fmt);3031vsnprintf(buff, sizeof(buff), fmt, ap);3032va_end(ap);3033if (verbosity > VERBOSITY_FULL)3034logprintf("Cmd: %s\n", buff);3035#if USE_POSIX_SPAWN3036if ((r = posix_spawn(&pid, *argv, NULL, NULL, argv, environ)) == 0) {3037while (waitpid(pid, &r, 0) == -1) {3038if (errno != EINTR)3039return (-1);3040}3041}3042#else3043r = system(buff);3044#endif3045return (r);3046}30473048/*3049* Slurp a file into memory for ease of comparison and testing.3050* Returns size of file in 'sizep' if non-NULL, null-terminates3051* data in memory for ease of use.3052*/3053char *3054slurpfile(size_t * sizep, const char *fmt, ...)3055{3056char filename[8192];3057struct stat st;3058va_list ap;3059char *p;3060ssize_t bytes_read;3061FILE *f;3062int r;30633064va_start(ap, fmt);3065vsnprintf(filename, sizeof(filename), fmt, ap);3066va_end(ap);30673068f = fopen(filename, "rb");3069if (f == NULL) {3070/* Note: No error; non-existent file is okay here. */3071return (NULL);3072}3073r = fstat(fileno(f), &st);3074if (r != 0) {3075logprintf("Can't stat file %s\n", filename);3076fclose(f);3077return (NULL);3078}3079p = malloc((size_t)st.st_size + 1);3080if (p == NULL) {3081logprintf("Can't allocate %ld bytes of memory to read file %s\n",3082(long int)st.st_size, filename);3083fclose(f);3084return (NULL);3085}3086bytes_read = fread(p, 1, (size_t)st.st_size, f);3087if (bytes_read < st.st_size) {3088logprintf("Can't read file %s\n", filename);3089fclose(f);3090free(p);3091return (NULL);3092}3093p[st.st_size] = '\0';3094if (sizep != NULL)3095*sizep = (size_t)st.st_size;3096fclose(f);3097return (p);3098}30993100/*3101* Slurp a file into memory for ease of comparison and testing.3102* Returns size of file in 'sizep' if non-NULL, null-terminates3103* data in memory for ease of use.3104*/3105void3106dumpfile(const char *filename, void *data, size_t len)3107{3108ssize_t bytes_written;3109FILE *f;31103111f = fopen(filename, "wb");3112if (f == NULL) {3113logprintf("Can't open file %s for writing\n", filename);3114return;3115}3116bytes_written = fwrite(data, 1, len, f);3117if (bytes_written < (ssize_t)len)3118logprintf("Can't write file %s\n", filename);3119fclose(f);3120}31213122/* Read a uuencoded file from the reference directory, decode, and3123* write the result into the current directory. */3124#define VALID_UUDECODE(c) (c >= 32 && c <= 96)3125#define UUDECODE(c) (((c) - 0x20) & 0x3f)3126void3127extract_reference_file(const char *name)3128{3129char buff[1024];3130FILE *in, *out;31313132snprintf(buff, sizeof(buff), "%s/%s.uu", refdir, name);3133in = fopen(buff, "r");3134failure("Couldn't open reference file %s", buff);3135assert(in != NULL);3136if (in == NULL)3137return;3138/* Read up to and including the 'begin' line. */3139for (;;) {3140if (fgets(buff, sizeof(buff), in) == NULL) {3141/* TODO: This is a failure. */3142return;3143}3144if (memcmp(buff, "begin ", 6) == 0)3145break;3146}3147/* Now, decode the rest and write it. */3148out = fopen(name, "wb");3149while (fgets(buff, sizeof(buff), in) != NULL) {3150char *p = buff;3151int bytes;31523153if (memcmp(buff, "end", 3) == 0)3154break;31553156bytes = UUDECODE(*p++);3157while (bytes > 0) {3158int n = 0;3159/* Write out 1-3 bytes from that. */3160assert(VALID_UUDECODE(p[0]));3161assert(VALID_UUDECODE(p[1]));3162n = UUDECODE(*p++) << 18;3163n |= UUDECODE(*p++) << 12;3164fputc(n >> 16, out);3165--bytes;3166if (bytes > 0) {3167assert(VALID_UUDECODE(p[0]));3168n |= UUDECODE(*p++) << 6;3169fputc((n >> 8) & 0xFF, out);3170--bytes;3171}3172if (bytes > 0) {3173assert(VALID_UUDECODE(p[0]));3174n |= UUDECODE(*p++);3175fputc(n & 0xFF, out);3176--bytes;3177}3178}3179}3180fclose(out);3181fclose(in);3182}31833184void3185copy_reference_file(const char *name)3186{3187char buff[1024];3188FILE *in, *out;3189size_t rbytes;31903191snprintf(buff, sizeof(buff), "%s/%s", refdir, name);3192in = fopen(buff, "rb");3193failure("Couldn't open reference file %s", buff);3194assert(in != NULL);3195if (in == NULL)3196return;3197/* Now, decode the rest and write it. */3198/* Not a lot of error checking here; the input better be right. */3199out = fopen(name, "wb");3200while ((rbytes = fread(buff, 1, sizeof(buff), in)) > 0) {3201if (fwrite(buff, 1, rbytes, out) != rbytes) {3202logprintf("Error: fwrite\n");3203break;3204}3205}3206fclose(out);3207fclose(in);3208}32093210int3211is_LargeInode(const char *file)3212{3213#if defined(_WIN32) && !defined(__CYGWIN__)3214BY_HANDLE_FILE_INFORMATION bhfi;3215int r;32163217r = my_GetFileInformationByName(file, &bhfi);3218if (r != 0)3219return (0);3220return (bhfi.nFileIndexHigh & 0x0000FFFFUL);3221#else3222struct stat st;3223int64_t ino;32243225if (stat(file, &st) < 0)3226return (0);3227ino = (int64_t)st.st_ino;3228return (ino > 0xffffffff);3229#endif3230}32313232void3233extract_reference_files(const char **names)3234{3235while (names && *names)3236extract_reference_file(*names++);3237}32383239#ifndef PROGRAM3240/* Set ACLs */3241int3242assertion_entry_set_acls(const char *file, int line, struct archive_entry *ae,3243struct archive_test_acl_t *acls, int n)3244{3245int i, r, ret;32463247assertion_count(file, line);32483249ret = 0;3250archive_entry_acl_clear(ae);3251for (i = 0; i < n; i++) {3252r = archive_entry_acl_add_entry(ae,3253acls[i].type, acls[i].permset, acls[i].tag,3254acls[i].qual, acls[i].name);3255if (r != 0) {3256ret = 1;3257failure_start(file, line, "type=%#010x, "3258"permset=%#010x, tag=%d, qual=%d name=%s",3259(unsigned int)acls[i].type,3260(unsigned int)acls[i].permset, acls[i].tag,3261acls[i].qual, acls[i].name);3262failure_finish(NULL);3263}3264}32653266return (ret);3267}32683269static int3270archive_test_acl_match(struct archive_test_acl_t *acl, int type, int permset,3271int tag, int qual, const char *name)3272{3273if (type != acl->type)3274return (0);3275if (permset != acl->permset)3276return (0);3277if (tag != acl->tag)3278return (0);3279if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ)3280return (1);3281if (tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ)3282return (1);3283if (tag == ARCHIVE_ENTRY_ACL_EVERYONE)3284return (1);3285if (tag == ARCHIVE_ENTRY_ACL_OTHER)3286return (1);3287if (qual != acl->qual)3288return (0);3289if (name == NULL) {3290if (acl->name == NULL || acl->name[0] == '\0')3291return (1);3292return (0);3293}3294if (acl->name == NULL) {3295if (name[0] == '\0')3296return (1);3297return (0);3298}3299return (0 == strcmp(name, acl->name));3300}33013302/* Compare ACLs */3303int3304assertion_entry_compare_acls(const char *file, int line,3305struct archive_entry *ae, struct archive_test_acl_t *acls, int cnt,3306int want_type, int mode)3307{3308int *marker;3309int i, r, n, ret;3310int type, permset, tag, qual;3311int matched;3312const char *name;33133314assertion_count(file, line);33153316ret = 0;3317n = 0;3318marker = malloc(sizeof(marker[0]) * cnt);33193320for (i = 0; i < cnt; i++) {3321if ((acls[i].type & want_type) != 0) {3322marker[n] = i;3323n++;3324}3325}33263327if (n == 0) {3328failure_start(file, line, "No ACL's to compare, type mask: %d",3329want_type);3330return (1);3331}33323333while (0 == (r = archive_entry_acl_next(ae, want_type,3334&type, &permset, &tag, &qual, &name))) {3335for (i = 0, matched = 0; i < n && !matched; i++) {3336if (archive_test_acl_match(&acls[marker[i]], type,3337permset, tag, qual, name)) {3338/* We found a match; remove it. */3339marker[i] = marker[n - 1];3340n--;3341matched = 1;3342}3343}3344if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS3345&& tag == ARCHIVE_ENTRY_ACL_USER_OBJ) {3346if (!matched) {3347failure_start(file, line, "No match for "3348"user_obj perm");3349failure_finish(NULL);3350ret = 1;3351}3352if ((permset << 6) != (mode & 0700)) {3353failure_start(file, line, "USER_OBJ permset "3354"(%02o) != user mode (%02o)",3355(unsigned int)permset,3356(unsigned int)(07 & (mode >> 6)));3357failure_finish(NULL);3358ret = 1;3359}3360} else if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS3361&& tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ) {3362if (!matched) {3363failure_start(file, line, "No match for "3364"group_obj perm");3365failure_finish(NULL);3366ret = 1;3367}3368if ((permset << 3) != (mode & 0070)) {3369failure_start(file, line, "GROUP_OBJ permset "3370"(%02o) != group mode (%02o)",3371(unsigned int)permset,3372(unsigned int)(07 & (mode >> 3)));3373failure_finish(NULL);3374ret = 1;3375}3376} else if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS3377&& tag == ARCHIVE_ENTRY_ACL_OTHER) {3378if (!matched) {3379failure_start(file, line, "No match for "3380"other perm");3381failure_finish(NULL);3382ret = 1;3383}3384if ((permset << 0) != (mode & 0007)) {3385failure_start(file, line, "OTHER permset "3386"(%02o) != other mode (%02o)",3387(unsigned int)permset,3388(unsigned int)mode & 07);3389failure_finish(NULL);3390ret = 1;3391}3392} else if (matched != 1) {3393failure_start(file, line, "Could not find match for "3394"ACL (type=%#010x,permset=%#010x,tag=%d,qual=%d,"3395"name=``%s'')", (unsigned int)type,3396(unsigned int)permset, tag, qual, name);3397failure_finish(NULL);3398ret = 1;3399}3400}3401if (r != ARCHIVE_EOF) {3402failure_start(file, line, "Should not exit before EOF");3403failure_finish(NULL);3404ret = 1;3405}3406if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0 &&3407(mode_t)(mode & 0777) != (archive_entry_mode(ae) & 0777)) {3408failure_start(file, line, "Mode (%02o) and entry mode (%02o) "3409"mismatch", (unsigned int)mode,3410(unsigned int)archive_entry_mode(ae));3411failure_finish(NULL);3412ret = 1;3413}3414if (n != 0) {3415failure_start(file, line, "Could not find match for ACL "3416"(type=%#010x,permset=%#010x,tag=%d,qual=%d,name=``%s'')",3417(unsigned int)acls[marker[0]].type,3418(unsigned int)acls[marker[0]].permset,3419acls[marker[0]].tag, acls[marker[0]].qual,3420acls[marker[0]].name);3421failure_finish(NULL);3422ret = 1;3423/* Number of ACLs not matched should == 0 */3424}3425free(marker);3426return (ret);3427}3428#endif /* !defined(PROGRAM) */34293430/*3431*3432* TEST management3433*3434*/34353436/*3437* "list.h" is simply created by "grep DEFINE_TEST test_*.c"; it has3438* a line like3439* DEFINE_TEST(test_function)3440* for each test.3441*/3442struct test_list_t3443{3444void (*func)(void);3445const char *name;3446int failures;3447};34483449/* Use "list.h" to declare all of the test functions. */3450#undef DEFINE_TEST3451#define DEFINE_TEST(name) void name(void);3452#include "list.h"34533454/* Use "list.h" to create a list of all tests (functions and names). */3455#undef DEFINE_TEST3456#define DEFINE_TEST(n) { n, #n, 0 },3457static struct test_list_t tests[] = {3458#include "list.h"3459};34603461/*3462* Summarize repeated failures in the just-completed test.3463*/3464static void3465test_summarize(int failed, int skips_num)3466{3467unsigned int i;34683469switch (verbosity) {3470case VERBOSITY_SUMMARY_ONLY:3471printf(failed ? "E" : ".");3472fflush(stdout);3473break;3474case VERBOSITY_PASSFAIL:3475printf(failed ? "FAIL\n" : skips_num ? "skipped\n" : "ok\n");3476break;3477}34783479log_console = (verbosity == VERBOSITY_LIGHT_REPORT);34803481for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {3482if (failed_lines[i].count > 1 && !failed_lines[i].skip)3483logprintf("%s:%u: Summary: Failed %d times\n",3484failed_filename, i, failed_lines[i].count);3485}3486/* Clear the failure history for the next file. */3487failed_filename = NULL;3488memset(failed_lines, 0, sizeof(failed_lines));3489}34903491/*3492* Set or unset environment variable.3493*/3494static void3495set_environment(const char *key, const char *value)3496{34973498#if defined(_WIN32) && !defined(__CYGWIN__)3499if (!SetEnvironmentVariable(key, value)) {3500fprintf(stderr, "SetEnvironmentVariable failed with %d\n",3501(int)GetLastError());3502}3503#else3504if (value == NULL) {3505if (unsetenv(key) == -1)3506fprintf(stderr, "unsetenv: %s\n", strerror(errno));3507} else {3508if (setenv(key, value, 1) == -1)3509fprintf(stderr, "setenv: %s\n", strerror(errno));3510}3511#endif3512}35133514/*3515* Enforce C locale for (sub)processes.3516*/3517static void3518set_c_locale(void)3519{3520static const char *lcs[] = {3521"LC_ADDRESS",3522"LC_ALL",3523"LC_COLLATE",3524"LC_CTYPE",3525"LC_IDENTIFICATION",3526"LC_MEASUREMENT",3527"LC_MESSAGES",3528"LC_MONETARY",3529"LC_NAME",3530"LC_NUMERIC",3531"LC_PAPER",3532"LC_TELEPHONE",3533"LC_TIME",3534NULL3535};3536size_t i;35373538setlocale(LC_ALL, "C");3539set_environment("LANG", "C");3540for (i = 0; lcs[i] != NULL; i++)3541set_environment(lcs[i], NULL);3542}35433544/*3545* Actually run a single test, with appropriate setup and cleanup.3546*/3547static int3548test_run(int i, const char *tmpdir)3549{3550#ifdef PATH_MAX3551char workdir[PATH_MAX * 2];3552#else3553char workdir[1024 * 2];3554#endif3555char logfilename[256];3556int failures_before = failures;3557int skips_before = skips;3558int tmp;3559mode_t oldumask;35603561switch (verbosity) {3562case VERBOSITY_SUMMARY_ONLY: /* No per-test reports at all */3563break;3564case VERBOSITY_PASSFAIL: /* rest of line will include ok/FAIL marker */3565printf("%3d: %-64s", i, tests[i].name);3566fflush(stdout);3567break;3568default: /* Title of test, details will follow */3569printf("%3d: %s\n", i, tests[i].name);3570}35713572/* Chdir to the top-level work directory. */3573if (!assertChdir(tmpdir)) {3574fprintf(stderr,3575"ERROR: Can't chdir to top work dir %s\n", tmpdir);3576exit(1);3577}3578/* Create a log file for this test. */3579tmp = snprintf(logfilename, sizeof(logfilename), "%s.log", tests[i].name);3580if (tmp < 0) {3581fprintf(stderr,3582"ERROR can't create %s.log: %s\n",3583tests[i].name, strerror(errno));3584exit(1);3585}3586if ((size_t)tmp >= sizeof(logfilename)) {3587fprintf(stderr,3588"ERROR can't create %s.log: Name too long. "3589"Length %d; Max allowed length %zu\n",3590tests[i].name, tmp, sizeof(logfilename) - 1);3591exit(1);3592}3593logfile = fopen(logfilename, "w");3594fprintf(logfile, "%s\n\n", tests[i].name);3595/* Chdir() to a work dir for this specific test. */3596tmp = snprintf(workdir,3597sizeof(workdir), "%s/%s", tmpdir, tests[i].name);3598if (tmp < 0) {3599fprintf(stderr,3600"ERROR can't create %s/%s: %s\n",3601tmpdir, tests[i].name, strerror(errno));3602exit(1);3603}3604if ((size_t)tmp >= sizeof(workdir)) {3605fprintf(stderr,3606"ERROR can't create %s/%s: Path too long. "3607"Length %d; Max allowed length %zu\n",3608tmpdir, tests[i].name, tmp, sizeof(workdir) - 1);3609exit(1);3610}3611testworkdir = workdir;3612if (!assertMakeDir(testworkdir, 0755)3613|| !assertChdir(testworkdir)) {3614fprintf(stderr,3615"ERROR: Can't chdir to work dir %s\n", testworkdir);3616exit(1);3617}3618/* Explicitly reset the locale before each test. */3619set_c_locale();3620/* Record the umask before we run the test. */3621umask(oldumask = umask(0));3622/*3623* Run the actual test.3624*/3625(*tests[i].func)();3626/*3627* Clean up and report afterwards.3628*/3629testworkdir = NULL;3630/* Restore umask */3631umask(oldumask);3632/* Reset locale. */3633set_c_locale();3634/* Reset directory. */3635if (!assertChdir(tmpdir)) {3636fprintf(stderr, "ERROR: Couldn't chdir to temp dir %s\n",3637tmpdir);3638exit(1);3639}3640/* Report per-test summaries. */3641tests[i].failures = failures - failures_before;3642test_summarize(tests[i].failures, skips - skips_before);3643/* Close the per-test log file. */3644fclose(logfile);3645logfile = NULL;3646/* If there were no failures, we can remove the work dir and logfile. */3647if (tests[i].failures == 0) {3648if (!keep_temp_files && assertChdir(tmpdir)) {3649#if defined(_WIN32) && !defined(__CYGWIN__)3650/* Make sure not to leave empty directories.3651* Sometimes a processing of closing files used by tests3652* is not done, then rmdir will be failed and it will3653* leave a empty test directory. So we should wait a few3654* seconds and retry rmdir. */3655int r, t;3656for (t = 0; t < 10; t++) {3657if (t > 0)3658Sleep(1000);3659r = systemf("rmdir /S /Q %s", tests[i].name);3660if (r == 0)3661break;3662}3663systemf("del %s", logfilename);3664#else3665systemf("rm -rf %s", tests[i].name);3666systemf("rm %s", logfilename);3667#endif3668}3669}3670/* Return appropriate status. */3671return (tests[i].failures);3672}36733674/*3675*3676*3677* MAIN and support routines.3678*3679*3680*/36813682static void3683list_tests(void)3684{3685static const int limit = nitems(tests);3686int i;36873688for (i = 0; i < limit; i++)3689printf(" %d: %s\n", i, tests[i].name);3690}36913692static void3693usage(const char *program)3694{36953696printf("Usage: %s [options] <test> <test> ...\n", program);3697printf("Default is to run all tests.\n");3698printf("Otherwise, specify the numbers of the tests you wish to run.\n");3699printf("Options:\n");3700printf(" -d Dump core after any failure, for debugging.\n");3701printf(" -k Keep all temp files.\n");3702printf(" Default: temp files for successful tests deleted.\n");3703printf(" -l List available tests and exit, ignoring all other.\n");3704printf(" options and arguments.\n");3705#ifdef PROGRAM3706printf(" -p <path> Path to executable to be tested.\n");3707printf(" Default: path taken from " ENVBASE " environment variable.\n");3708#endif3709printf(" -q Quiet.\n");3710printf(" -r <dir> Path to dir containing reference files.\n");3711printf(" Default: Current directory.\n");3712printf(" -s Exit with code 2 if any tests were skipped.\n");3713printf(" -u Keep running specified tests until one fails.\n");3714printf(" -v Verbose.\n");3715printf("Available tests:\n");3716list_tests();3717exit(1);3718}37193720static char *3721get_refdir(const char *d)3722{3723size_t tried_size, buff_size;3724char *buff, *tried, *pwd = NULL, *p = NULL;37253726#ifdef PATH_MAX3727buff_size = PATH_MAX;3728#else3729buff_size = 8192;3730#endif3731buff = calloc(buff_size, 1);3732if (buff == NULL) {3733fprintf(stderr, "Unable to allocate memory\n");3734exit(1);3735}37363737/* Allocate a buffer to hold the various directories we checked. */3738tried_size = buff_size * 2;3739tried = calloc(tried_size, 1);3740if (tried == NULL) {3741fprintf(stderr, "Unable to allocate memory\n");3742exit(1);3743}37443745/* If a dir was specified, try that */3746if (d != NULL) {3747pwd = NULL;3748snprintf(buff, buff_size, "%s", d);3749p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3750if (p != NULL) goto success;3751strncat(tried, buff, tried_size - strlen(tried) - 1);3752strncat(tried, "\n", tried_size - strlen(tried) - 1);3753goto failure;3754}37553756/* Get the current dir. */3757#if defined(PATH_MAX) && !defined(__GLIBC__)3758pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */3759#else3760pwd = getcwd(NULL, 0);3761#endif3762while (pwd[strlen(pwd) - 1] == '\n')3763pwd[strlen(pwd) - 1] = '\0';37643765/* Look for a known file. */3766snprintf(buff, buff_size, "%s", pwd);3767p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3768if (p != NULL) goto success;3769strncat(tried, buff, tried_size - strlen(tried) - 1);3770strncat(tried, "\n", tried_size - strlen(tried) - 1);37713772snprintf(buff, buff_size, "%s/test", pwd);3773p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3774if (p != NULL) goto success;3775strncat(tried, buff, tried_size - strlen(tried) - 1);3776strncat(tried, "\n", tried_size - strlen(tried) - 1);37773778#if defined(LIBRARY)3779snprintf(buff, buff_size, "%s/%s/test", pwd, LIBRARY);3780#else3781snprintf(buff, buff_size, "%s/%s/test", pwd, PROGRAM);3782#endif3783p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3784if (p != NULL) goto success;3785strncat(tried, buff, tried_size - strlen(tried) - 1);3786strncat(tried, "\n", tried_size - strlen(tried) - 1);37873788#if defined(PROGRAM_ALIAS)3789snprintf(buff, buff_size, "%s/%s/test", pwd, PROGRAM_ALIAS);3790p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3791if (p != NULL) goto success;3792strncat(tried, buff, tried_size - strlen(tried) - 1);3793strncat(tried, "\n", tried_size - strlen(tried) - 1);3794#endif37953796if (memcmp(pwd, "/usr/obj", 8) == 0) {3797snprintf(buff, buff_size, "%s", pwd + 8);3798p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3799if (p != NULL) goto success;3800strncat(tried, buff, tried_size - strlen(tried) - 1);3801strncat(tried, "\n", tried_size - strlen(tried) - 1);38023803snprintf(buff, buff_size, "%s/test", pwd + 8);3804p = slurpfile(NULL, "%s/%s", buff, KNOWNREF);3805if (p != NULL) goto success;3806strncat(tried, buff, tried_size - strlen(tried) - 1);3807strncat(tried, "\n", tried_size - strlen(tried) - 1);3808}38093810failure:3811printf("Unable to locate known reference file %s\n", KNOWNREF);3812printf(" Checked following directories:\n%s\n", tried);3813printf("Use -r option to specify full path to reference directory\n");3814#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)3815DebugBreak();3816#endif3817exit(1);38183819success:3820free(p);3821free(pwd);3822free(tried);38233824/* Copy result into a fresh buffer to reduce memory usage. */3825p = strdup(buff);3826free(buff);3827return p;3828}38293830/* Filter tests against a glob pattern. Returns non-zero if test matches3831* pattern, zero otherwise. A '^' at the beginning of the pattern negates3832* the return values (i.e. returns zero for a match, non-zero otherwise.3833*/3834static int3835test_filter(const char *pattern, const char *test)3836{3837int retval = 0;3838int negate = 0;3839const char *p = pattern;3840const char *t = test;38413842if (p[0] == '^')3843{3844negate = 1;3845p++;3846}38473848while (1)3849{3850if (p[0] == '\\')3851p++;3852else if (p[0] == '*')3853{3854while (p[0] == '*')3855p++;3856if (p[0] == '\\')3857p++;3858if ((t = strchr(t, p[0])) == 0)3859break;3860}3861if (p[0] != t[0])3862break;3863if (p[0] == '\0') {3864retval = 1;3865break;3866}3867p++;3868t++;3869}38703871return (negate) ? !retval : retval;3872}38733874static int3875get_test_set(int *test_set, int limit, const char *test)3876{3877int start, end;3878int idx = 0;38793880if (test == NULL) {3881/* Default: Run all tests. */3882for (;idx < limit; idx++)3883test_set[idx] = idx;3884return (limit);3885}3886if (*test >= '0' && *test <= '9') {3887const char *vp = test;3888start = 0;3889while (*vp >= '0' && *vp <= '9') {3890start *= 10;3891start += *vp - '0';3892++vp;3893}3894if (*vp == '\0') {3895end = start;3896} else if (*vp == '-') {3897++vp;3898if (*vp == '\0') {3899end = limit - 1;3900} else {3901end = 0;3902while (*vp >= '0' && *vp <= '9') {3903end *= 10;3904end += *vp - '0';3905++vp;3906}3907}3908} else3909return (-1);3910if (start < 0 || end >= limit || start > end)3911return (-1);3912while (start <= end)3913test_set[idx++] = start++;3914} else {3915for (start = 0; start < limit; ++start) {3916const char *name = tests[start].name;3917if (test_filter(test, name))3918test_set[idx++] = start;3919}3920}3921return ((idx == 0)?-1:idx);3922}39233924int3925main(int argc, char **argv)3926{3927static const int limit = nitems(tests);3928int test_set[nitems(tests)];3929int i = 0, j = 0, tests_run = 0, tests_failed = 0, option;3930size_t testprogdir_len;3931size_t tmplen;3932#ifdef PROGRAM3933size_t tmp2_len;3934#endif3935time_t now;3936struct tm *tmptr;3937#if defined(HAVE_LOCALTIME_R) || defined(HAVE_LOCALTIME_S)3938struct tm tmbuf;3939#endif3940char *refdir_alloc = NULL;3941const char *progname;3942char **saved_argv;3943const char *tmp, *option_arg, *p;3944#ifdef PATH_MAX3945char tmpdir[PATH_MAX];3946#else3947char tmpdir[256];3948#endif3949char *pwd, *testprogdir, *tmp2 = NULL, *vlevel = NULL;3950char tmpdir_timestamp[32];39513952(void)argc; /* UNUSED */39533954/* Get the current dir. */3955#if defined(PATH_MAX) && !defined(__GLIBC__)3956pwd = getcwd(NULL, PATH_MAX);/* Solaris getcwd needs the size. */3957#else3958pwd = getcwd(NULL, 0);3959#endif3960while (pwd[strlen(pwd) - 1] == '\n')3961pwd[strlen(pwd) - 1] = '\0';39623963#if defined(HAVE__CrtSetReportMode) && !defined(__WATCOMC__)3964/* To stop to run the default invalid parameter handler. */3965_set_invalid_parameter_handler(invalid_parameter_handler);3966/* Disable annoying assertion message box. */3967_CrtSetReportMode(_CRT_ASSERT, 0);3968#endif39693970/*3971* Name of this program, used to build root of our temp directory3972* tree.3973*/3974progname = p = argv[0];3975testprogdir_len = strlen(progname) + 1;3976if ((testprogdir = malloc(testprogdir_len)) == NULL)3977{3978fprintf(stderr, "ERROR: Out of memory.");3979exit(1);3980}3981strncpy(testprogdir, progname, testprogdir_len);3982while (*p != '\0') {3983/* Support \ or / dir separators for Windows compat. */3984if (*p == '/' || *p == '\\')3985{3986progname = p + 1;3987i = j;3988}3989++p;3990j++;3991}3992testprogdir[i] = '\0';3993#if defined(_WIN32) && !defined(__CYGWIN__)3994if (testprogdir[0] != '/' && testprogdir[0] != '\\' &&3995!(((testprogdir[0] >= 'a' && testprogdir[0] <= 'z') ||3996(testprogdir[0] >= 'A' && testprogdir[0] <= 'Z')) &&3997testprogdir[1] == ':' &&3998(testprogdir[2] == '/' || testprogdir[2] == '\\')))3999#else4000if (testprogdir[0] != '/')4001#endif4002{4003/* Fixup path for relative directories. */4004if ((testprogdir = realloc(testprogdir,4005strlen(pwd) + 1 + strlen(testprogdir) + 1)) == NULL)4006{4007fprintf(stderr, "ERROR: Out of memory.");4008exit(1);4009}4010memmove(testprogdir + strlen(pwd) + 1, testprogdir,4011strlen(testprogdir) + 1);4012memcpy(testprogdir, pwd, strlen(pwd));4013testprogdir[strlen(pwd)] = '/';4014}40154016#ifdef PROGRAM4017/* Get the target program from environment, if available. */4018testprogfile = getenv(ENVBASE);4019#endif40204021if (getenv("TMPDIR") != NULL)4022tmp = getenv("TMPDIR");4023else if (getenv("TMP") != NULL)4024tmp = getenv("TMP");4025else if (getenv("TEMP") != NULL)4026tmp = getenv("TEMP");4027else if (getenv("TEMPDIR") != NULL)4028tmp = getenv("TEMPDIR");4029else4030tmp = "/tmp";4031tmplen = strlen(tmp);4032while (tmplen > 0 && tmp[tmplen - 1] == '/')4033tmplen--;40344035/* Allow -d to be controlled through the environment. */4036if (getenv(ENVBASE "_DEBUG") != NULL)4037dump_on_failure = 1;40384039/* Allow -v to be controlled through the environment. */4040if (getenv("_VERBOSITY_LEVEL") != NULL)4041{4042vlevel = getenv("_VERBOSITY_LEVEL");4043verbosity = atoi(vlevel);4044if (verbosity < VERBOSITY_SUMMARY_ONLY || verbosity > VERBOSITY_FULL)4045{4046/* Unsupported verbosity levels are silently ignored */4047vlevel = NULL;4048verbosity = VERBOSITY_PASSFAIL;4049}4050}40514052/* Get the directory holding test files from environment. */4053refdir = getenv(ENVBASE "_TEST_FILES");40544055/*4056* Parse options, without using getopt(), which isn't available4057* on all platforms.4058*/4059++argv; /* Skip program name */4060while (*argv != NULL) {4061if (**argv != '-')4062break;4063p = *argv++;4064++p; /* Skip '-' */4065while (*p != '\0') {4066option = *p++;4067option_arg = NULL;4068/* If 'opt' takes an argument, parse that. */4069if (option == 'p' || option == 'r') {4070if (*p != '\0')4071option_arg = p;4072else if (*argv == NULL) {4073fprintf(stderr,4074"Option -%c requires argument.\n",4075option);4076usage(progname);4077} else4078option_arg = *argv++;4079p = ""; /* End of this option word. */4080}40814082/* Now, handle the option. */4083switch (option) {4084case 'd':4085dump_on_failure = 1;4086break;4087case 'k':4088keep_temp_files = 1;4089break;4090case 'l':4091list_tests();4092exit(0);4093break;4094case 'p':4095#ifdef PROGRAM4096testprogfile = option_arg;4097#else4098fprintf(stderr, "-p option not permitted\n");4099usage(progname);4100#endif4101break;4102case 'q':4103if (!vlevel)4104verbosity--;4105break;4106case 'r':4107refdir = option_arg;4108break;4109case 's':4110fail_if_tests_skipped = 1;4111break;4112case 'u':4113until_failure++;4114break;4115case 'v':4116if (!vlevel)4117verbosity++;4118break;4119default:4120fprintf(stderr, "Unrecognized option '%c'\n",4121option);4122usage(progname);4123}4124}4125}41264127/*4128* Sanity-check that our options make sense.4129*/4130#ifdef PROGRAM4131if (testprogfile == NULL)4132{4133tmp2_len = strlen(testprogdir) + 1 + strlen(PROGRAM) + 1;4134#if defined(_WIN32) && !defined(__CYGWIN__)4135tmp2_len += 4;4136#endif4137if ((tmp2 = malloc(tmp2_len)) == NULL)4138{4139fprintf(stderr, "ERROR: Out of memory.");4140exit(1);4141}4142strncpy(tmp2, testprogdir, tmp2_len);4143strncat(tmp2, "/", tmp2_len);4144strncat(tmp2, PROGRAM, tmp2_len);4145#if defined(_WIN32) && !defined(__CYGWIN__)4146strncat(tmp2, ".exe", tmp2_len);4147#endif4148testprogfile = tmp2;4149}41504151{4152char *testprg;4153size_t testprg_len;4154#if defined(_WIN32) && !defined(__CYGWIN__)4155/* Command.com sometimes rejects '/' separators. */4156testprg = strdup(testprogfile);4157for (i = 0; testprg[i] != '\0'; i++) {4158if (testprg[i] == '/')4159testprg[i] = '\\';4160}4161testprogfile = testprg;4162#endif4163/* Quote the name that gets put into shell command lines. */4164testprg_len = strlen(testprogfile) + 3;4165testprg = malloc(testprg_len);4166strncpy(testprg, "\"", testprg_len);4167strncat(testprg, testprogfile, testprg_len);4168strncat(testprg, "\"", testprg_len);4169testprog = testprg;4170}41714172/* Sanity check: reject a relative path for refdir. */4173if (refdir != NULL) {4174#if defined(_WIN32) && !defined(__CYGWIN__)4175/* TODO: probably use PathIsRelative() from <shlwapi.h>. */4176#else4177if (refdir[0] != '/') {4178fprintf(stderr,4179"ERROR: Cannot use relative path for refdir\n");4180exit(1);4181}4182#endif4183}4184#endif41854186#if !defined(_WIN32) && defined(SIGPIPE)4187{ /* Ignore SIGPIPE signals */4188struct sigaction sa;4189sa.sa_handler = SIG_IGN;4190sigemptyset(&sa.sa_mask);4191sa.sa_flags = 0;4192sigaction(SIGPIPE, &sa, NULL);4193}4194#endif41954196/*4197* Create a temp directory for the following tests.4198* Include the time the tests started as part of the name,4199* to make it easier to track the results of multiple tests.4200*/4201now = time(NULL);4202for (i = 0; ; i++) {4203#if defined(HAVE_LOCALTIME_S)4204tmptr = localtime_s(&tmbuf, &now) ? NULL : &tmbuf;4205#elif defined(HAVE_LOCALTIME_R)4206tmptr = localtime_r(&now, &tmbuf);4207#else4208tmptr = localtime(&now);4209#endif4210strftime(tmpdir_timestamp, sizeof(tmpdir_timestamp),4211"%Y-%m-%dT%H.%M.%S", tmptr);4212if (tmplen + 1 + strlen(progname) + 1 +4213strlen(tmpdir_timestamp) + 1 + 3 >=4214nitems(tmpdir)) {4215fprintf(stderr,4216"ERROR: Temp directory pathname too long\n");4217exit(1);4218}4219snprintf(tmpdir, sizeof(tmpdir), "%.*s/%s.%s-%03d",4220(int)tmplen, tmp, progname, tmpdir_timestamp, i);4221if (assertMakeDir(tmpdir, 0755))4222break;4223if (i >= 999) {4224fprintf(stderr,4225"ERROR: Unable to create temp directory %s\n",4226tmpdir);4227exit(1);4228}4229}42304231/*4232* If the user didn't specify a directory for locating4233* reference files, try to find the reference files in4234* the "usual places."4235*/4236refdir = refdir_alloc = get_refdir(refdir);42374238/*4239* Banner with basic information.4240*/4241printf("\n");4242printf("If tests fail or crash, details will be in:\n");4243printf(" %s\n", tmpdir);4244printf("\n");4245if (verbosity > VERBOSITY_SUMMARY_ONLY) {4246printf("Reference files will be read from: %s\n", refdir);4247#ifdef PROGRAM4248printf("Running tests on: %s\n", testprog);4249#endif4250printf("Exercising: ");4251fflush(stdout);4252printf("%s\n", EXTRA_VERSION);4253} else {4254printf("Running ");4255fflush(stdout);4256}42574258/*4259* Run some or all of the individual tests.4260*/4261saved_argv = argv;4262do {4263argv = saved_argv;4264do {4265int test_num;42664267test_num = get_test_set(test_set, limit, *argv);4268if (test_num < 0) {4269printf("*** INVALID Test %s\n", *argv);4270free(refdir_alloc);4271free(testprogdir);4272usage(progname);4273}4274for (i = 0; i < test_num; i++) {4275tests_run++;4276if (test_run(test_set[i], tmpdir)) {4277tests_failed++;4278if (until_failure)4279goto finish;4280}4281}4282if (*argv != NULL)4283argv++;4284} while (*argv != NULL);4285} while (until_failure);42864287finish:4288/* Must be freed after all tests run */4289free(tmp2);4290free(testprogdir);4291free(pwd);42924293/*4294* Report summary statistics.4295*/4296if (verbosity > VERBOSITY_SUMMARY_ONLY) {4297printf("\n");4298printf("Totals:\n");4299printf(" Tests run: %8d\n", tests_run);4300printf(" Tests failed: %8d\n", tests_failed);4301printf(" Assertions checked:%8d\n", assertions);4302printf(" Assertions failed: %8d\n", failures);4303printf(" Skips reported: %8d\n", skips);4304}4305if (failures) {4306printf("\n");4307printf("Failing tests:\n");4308for (i = 0; i < limit; ++i) {4309if (tests[i].failures)4310printf(" %d: %s (%d failures)\n", i,4311tests[i].name, tests[i].failures);4312}4313printf("\n");4314printf("Details for failing tests: %s\n", tmpdir);4315printf("\n");4316} else {4317if (verbosity == VERBOSITY_SUMMARY_ONLY)4318printf("\n");4319printf("%d tests passed, no failures\n", tests_run);4320}43214322free(refdir_alloc);43234324/* If the final tmpdir is empty, we can remove it. */4325/* This should be the usual case when all tests succeed. */4326assertChdir("..");4327rmdir(tmpdir);43284329if (tests_failed) return 1;43304331if (fail_if_tests_skipped == 1 && skips > 0) return 2;43324333return 0;4334}433543364337