⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test.c

📁 《linux应用开发技术详解》的配套代码
💻 C
📖 第 1 页 / 共 2 页
字号:
/* GNU test program (ksb and mjb) */

/* Modified to run with the GNU shell by bfox. */

/* Copyright (C) 1987-2002 Free Software Foundation, Inc.

   This file is part of GNU Bash, the Bourne Again SHell.

   Bash is free software; you can redistribute it and/or modify it under
   the terms of the GNU General Public License as published by the Free
   Software Foundation; either version 2, or (at your option) any later
   version.

   Bash is distributed in the hope that it will be useful, but WITHOUT ANY
   WARRANTY; without even the implied warranty of MERCHANTABILITY or
   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

/* Define TEST_STANDALONE to get the /bin/test version.  Otherwise, you get
   the shell builtin version. */
/* #define TEST_STANDALONE */

#include <config.h>
#include <stdio.h>
#include <sys/types.h>

/* The official name of this program (e.g., no `g' prefix).  */
#define PROGRAM_NAME "test"

#define TEST_STANDALONE 1

#if !defined (TEST_STANDALONE)
# include "shell.h"
# include "posixstat.h"
# include "filecntl.h"
#else /* TEST_STANDALONE */
# include "system.h"
# include "group-member.h"
# include "error.h"
# if !defined (S_IXUGO)
#  define S_IXUGO 0111
# endif /* S_IXUGO */
# if defined (_POSIX_VERSION)
#  include <limits.h>
# else /* !_POSIX_VERSION */
#  include <sys/param.h>
# endif /* _POSIX_VERSION */
# define whitespace(c) (((c) == ' ') || ((c) == '\t'))
# define digit(c)  ((c) >= '0' && (c) <= '9')
# define digit_value(c) ((c) - '0')
char *program_name;
#endif /* TEST_STANDALONE */

#if !defined (_POSIX_VERSION)
# include <sys/file.h>
#endif /* !_POSIX_VERSION */

#include <errno.h>
#ifndef errno
extern int errno;
#endif

#undef STREQ
#define STREQ(a, b) ((a)[0] == (b)[0] && strcmp (a, b) == 0)

#if !defined (member)
# define member(c, s) ((c) ? (strchr ((s), (c)) ? 1 : 0) : 0)
#endif /* !member */

extern gid_t getegid ();
extern uid_t geteuid ();

#if !defined (R_OK)
# define R_OK 4
# define W_OK 2
# define X_OK 1
# define F_OK 0
#endif /* R_OK */

/* This name is used solely when printing --version information.  */
#define PROGRAM_NAME "test"

/* The following few defines control the truth and false output of each stage.
   TRUE and FALSE are what we use to compute the final output value.
   SHELL_BOOLEAN is the form which returns truth or falseness in shell terms.
   TRUTH_OR is how to do logical or with TRUE and FALSE.
   TRUTH_AND is how to do logical and with TRUE and FALSE..
   Default is TRUE = 1, FALSE = 0, TRUTH_OR = a | b, TRUTH_AND = a & b,
    SHELL_BOOLEAN = (!value). */
#define TRUE 1
#define FALSE 0
#define SHELL_BOOLEAN(value) (!(value))
#define TRUTH_OR(a, b) ((a) | (b))
#define TRUTH_AND(a, b) ((a) & (b))

#if defined (TEST_STANDALONE)
# define test_exit(val) exit (val)
#else
   static jmp_buf test_exit_buf;
   static int test_error_return = 0;
# define test_exit(val) test_error_return = val, longjmp (test_exit_buf, 1)
#endif /* !TEST_STANDALONE */

static int pos;		/* The offset of the current argument in ARGV. */
static int argc;	/* The number of arguments present in ARGV. */
static char **argv;	/* The argument list. */

static int unop PARAMS ((int op));
static int binop PARAMS ((char *s));
static int unary_operator PARAMS ((void));
static int binary_operator PARAMS ((void));
static int two_arguments PARAMS ((void));
static int three_arguments PARAMS ((void));
static int posixtest PARAMS ((void));

static int expr PARAMS ((void));
static int term PARAMS ((void));
static int and PARAMS ((void));
static int or PARAMS ((void));

static void test_syntax_error PARAMS ((char const *format, char const *arg))
     ATTRIBUTE_NORETURN;
static void beyond PARAMS ((void)) ATTRIBUTE_NORETURN;

static void
test_syntax_error (char const *format, char const *arg)
{
  fprintf (stderr, "%s: ", argv[0]);
  fprintf (stderr, format, arg);
  fflush (stderr);
  test_exit (SHELL_BOOLEAN (FALSE));
}

/* A wrapper for stat () which disallows pathnames that are empty strings. */
static int
test_stat (char *path, struct stat *finfo)
{
  if (*path == '\0')
    {
      errno = ENOENT;
      return (-1);
    }
  return (stat (path, finfo));
}

/* Do the same thing access(2) does, but use the effective uid and gid,
   and don't make the mistake of telling root that any file is executable.
   But this loses when the containing filesystem is mounted e.g. read-only.  */
static int
eaccess (char *path, int mode)
{
  struct stat st;
  static uid_t euid = -1;

  if (test_stat (path, &st) < 0)
    return (-1);

  if (euid == (uid_t) -1)
    euid = geteuid ();

  if (euid == 0)
    {
      /* Root can read or write any file. */
      if (mode != X_OK)
	return (0);

      /* Root can execute any file that has any one of the execute
	 bits set. */
      if (st.st_mode & S_IXUGO)
	return (0);
    }

  if (st.st_uid == euid)        /* owner */
    mode <<= 6;
  else if (group_member (st.st_gid))
    mode <<= 3;

  if (st.st_mode & mode)
    return (0);

  return (-1);
}

/* Increment our position in the argument list.  Check that we're not
   past the end of the argument list.  This check is supressed if the
   argument is FALSE.  Made a macro for efficiency. */
#define advance(f)							\
  do									\
    {									\
      ++pos;								\
      if ((f) && pos >= argc)						\
	beyond ();							\
    }									\
  while (0)

#if !defined (advance)
static int
advance (int f)
{
  ++pos;

  if (f && pos >= argc)
    beyond ();
}
#endif /* advance */

#define unary_advance() 						\
  do									\
    {									\
      advance (1);							\
      ++pos;								\
    }									\
  while (0)

/*
 * beyond - call when we're beyond the end of the argument list (an
 *	error condition)
 */
static void
beyond (void)
{
  test_syntax_error (_("argument expected\n"), NULL);
}

/* Syntax error for when an integer argument was expected, but
   something else was found. */
static void
integer_expected_error (char const *pch)
{
  test_syntax_error (_("integer expression expected %s\n"), pch);
}

/* Return nonzero if the characters pointed to by STRING constitute a
   valid number.  Stuff the converted number into RESULT if RESULT is
   not null.  */
static int
isint (register char *string, intmax_t *result)
{
  int sign;
  intmax_t value;

  sign = 1;
  value = 0;

  if (result)
    *result = 0;

  /* Skip leading whitespace characters. */
  while (whitespace (*string))
    string++;

  if (!*string)
    return (0);

  /* We allow leading `-' or `+'. */
  if (*string == '-' || *string == '+')
    {
      if (!digit (string[1]))
	return (0);

      if (*string == '-')
	sign = -1;

      string++;
    }

  while (digit (*string))
    {
      if (result)
	value = (value * 10) + digit_value (*string);
      string++;
    }

  /* Skip trailing whitespace, if any. */
  while (whitespace (*string))
    string++;

  /* Error if not at end of string. */
  if (*string)
    return (0);

  if (result)
    {
      value *= sign;
      *result = value;
    }

  return (1);
}

/* Find the modification time of FILE, and stuff it into *AGE.
   Return 0 if successful, -1 if not.  */
static int
age_of (char *filename, time_t *age)
{
  struct stat finfo;
  int r = test_stat (filename, &finfo);
  if (r == 0)
    *age = finfo.st_mtime;
  return r;
}

/*
 * term - parse a term and return 1 or 0 depending on whether the term
 *	evaluates to true or false, respectively.
 *
 * term ::=
 *	'-'('h'|'d'|'f'|'r'|'s'|'w'|'c'|'b'|'p'|'u'|'g'|'k') filename
 *	'-'('L'|'x') filename
 * 	'-t' [ int ]
 *	'-'('z'|'n') string
 *	string
 *	string ('!='|'=') string
 *	<int> '-'(eq|ne|le|lt|ge|gt) <int>
 *	file '-'(nt|ot|ef) file
 *	'(' <expr> ')'
 * int ::=
 *	'-l' string
 *	positive and negative integers
 */
static int
term (void)
{
  int value;

  if (pos >= argc)
    beyond ();

  /* Deal with leading "not"'s. */
  if ('!' == argv[pos][0] && '\000' == argv[pos][1])
    {
      value = FALSE;
      while (pos < argc && '!' == argv[pos][0] && '\000' == argv[pos][1])
	{
	  advance (1);
	  value ^= (TRUE);
	}

      return (value ^ (term ()));
    }

  /* A paren-bracketed argument. */
  if (argv[pos][0] == '(' && !argv[pos][1])
    {
      advance (1);
      value = expr ();
      if (!argv[pos])
	test_syntax_error (_("')' expected\n"), NULL);
      else
        if (argv[pos][0] != ')' || argv[pos][1])
	  test_syntax_error (_("')' expected, found %s\n"), argv[pos]);
      advance (0);
      return (TRUE == (value));
    }

  /* are there enough arguments left that this could be dyadic? */
  if (((pos + 3 <= argc) && binop (argv[pos + 1])) ||
      ((pos + 4 <= argc && STREQ (argv[pos], "-l") && binop (argv[pos + 2]))))
    value = binary_operator ();

  /* Might be a switch type argument */
  else if ('-' == argv[pos][0] && argv[pos][1] && 0 == argv[pos][2])
    {
      if (unop (argv[pos][1]))
	value = unary_operator ();
      else
	test_syntax_error (_("%s: unary operator expected\n"), argv[pos]);
    }
  else
    {
      value = (argv[pos][0] != '\0');
      advance (0);
    }

  return (value);
}

static int
binary_operator (void)
{
  register int op;
  struct stat stat_buf, stat_spare;
  intmax_t l, r;
  int value;
  /* Are the left and right integer expressions of the form '-l string'? */
  int l_is_l, r_is_l;

  if (strcmp (argv[pos], "-l") == 0)
    {
      l_is_l = 1;
      op = pos + 2;

      /* Make sure that OP is still a valid binary operator. */
      if ((op >= argc - 1) || (binop (argv[op]) == 0))
	test_syntax_error (_("%s: binary operator expected\n"), argv[op]);

      advance (0);
    }
  else
    {
      l_is_l = 0;
      op = pos + 1;
    }

  if ((op < argc - 2) && (strcmp (argv[op + 1], "-l") == 0))
    {
      r_is_l = 1;
      advance (0);
    }
  else
    r_is_l = 0;

  if (argv[op][0] == '-')
    {
      /* check for eq, nt, and stuff */
      switch (argv[op][1])
	{
	default:
	  break;

	case 'l':
	  if (argv[op][2] == 't' && !argv[op][3])
	    {
	      /* lt */
	      if (l_is_l)
		l = strlen (argv[op - 1]);
	      else
		{
		  if (!isint (argv[op - 1], &l))
		    integer_expected_error (_("before -lt"));
		}

	      if (r_is_l)
		r = strlen (argv[op + 2]);
	      else
		{
		  if (!isint (argv[op + 1], &r))
		    integer_expected_error (_("after -lt"));
		}
	      pos += 3;
	      return (TRUE == (l < r));
	    }

	  if (argv[op][2] == 'e' && !argv[op][3])
	    {
	      /* le */
	      if (l_is_l)
		l = strlen (argv[op - 1]);
	      else
		{
		  if (!isint (argv[op - 1], &l))
		    integer_expected_error (_("before -le"));
		}
	      if (r_is_l)
		r = strlen (argv[op + 2]);
	      else
		{
		  if (!isint (argv[op + 1], &r))
		    integer_expected_error (_("after -le"));
		}
	      pos += 3;
	      return (TRUE == (l <= r));
	    }
	  break;

	case 'g':
	  if (argv[op][2] == 't' && !argv[op][3])
	    {
	      /* gt integer greater than */
	      if (l_is_l)
		l = strlen (argv[op - 1]);
	      else
		{
		  if (!isint (argv[op - 1], &l))
		    integer_expected_error (_("before -gt"));
		}
	      if (r_is_l)
		r = strlen (argv[op + 2]);
	      else
		{
		  if (!isint (argv[op + 1], &r))
		    integer_expected_error (_("after -gt"));
		}
	      pos += 3;
	      return (TRUE == (l > r));
	    }

	  if (argv[op][2] == 'e' && !argv[op][3])
	    {
	      /* ge - integer greater than or equal to */
	      if (l_is_l)
		l = strlen (argv[op - 1]);
	      else
		{
		  if (!isint (argv[op - 1], &l))
		    integer_expected_error (_("before -ge"));
		}
	      if (r_is_l)
		r = strlen (argv[op + 2]);
	      else
		{
		  if (!isint (argv[op + 1], &r))
		    integer_expected_error (_("after -ge"));
		}
	      pos += 3;
	      return (TRUE == (l >= r));
	    }
	  break;

	case 'n':
	  if (argv[op][2] == 't' && !argv[op][3])
	    {
	      /* nt - newer than */
	      time_t lt, rt;
	      int le, re;
	      pos += 3;
	      if (l_is_l || r_is_l)
		test_syntax_error (_("-nt does not accept -l\n"), NULL);
	      le = age_of (argv[op - 1], &lt);
	      re = age_of (argv[op + 1], &rt);
	      return le > re || (le == 0 && lt > rt);
	    }

	  if (argv[op][2] == 'e' && !argv[op][3])
	    {
	      /* ne - integer not equal */
	      if (l_is_l)
		l = strlen (argv[op - 1]);
	      else
		{
		  if (!isint (argv[op - 1], &l))
		    integer_expected_error (_("before -ne"));
		}
	      if (r_is_l)
		r = strlen (argv[op + 2]);
	      else
		{
		  if (!isint (argv[op + 1], &r))
		    integer_expected_error (_("after -ne"));
		}
	      pos += 3;
	      return (TRUE == (l != r));
	    }
	  break;

	case 'e':
	  if (argv[op][2] == 'q' && !argv[op][3])
	    {
	      /* eq - integer equal */
	      if (l_is_l)
		l = strlen (argv[op - 1]);
	      else
		{
		  if (!isint (argv[op - 1], &l))
		    integer_expected_error (_("before -eq"));
		}
	      if (r_is_l)
		r = strlen (argv[op + 2]);
	      else
		{
		  if (!isint (argv[op + 1], &r))
		    integer_expected_error (_("after -eq"));
		}
	      pos += 3;
	      return (TRUE == (l == r));
	    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -