• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* test.c - evaluate expression
2  *
3  * Copyright 2018 Rob Landley <rob@landley.net>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html
6  *
7  * Deviations from posix: -k, [[ < > =~ ]]
8 
9 USE_TEST(NEWTOY(test, 0, TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_NOHELP|TOYFLAG_MAYFORK))
10 USE_TEST_GLUE(OLDTOY([, test, TOYFLAG_BIN|TOYFLAG_MAYFORK|TOYFLAG_NOHELP))
11 USE_SH(OLDTOY([[, test, TOYFLAG_NOFORK|TOYFLAG_NOHELP))
12 
13 config TEST
14   bool "test"
15   default y
16   help
17     usage: test [-bcdefghLPrSsuwx PATH] [-nz STRING] [-t FD] [X ?? Y]
18 
19     Return true or false by performing tests. No arguments is false, one argument
20     is true if not empty string.
21 
22     --- Tests with a single argument (after the option):
23     PATH is/has:
24       -b  block device   -f  regular file   -p  fifo           -u  setuid bit
25       -c  char device    -g  setgid         -r  readable       -w  writable
26       -d  directory      -h  symlink        -S  socket         -x  executable
27       -e  exists         -L  symlink        -s  nonzero size   -k  sticky bit
28     STRING is:
29       -n  nonzero size   -z  zero size
30     FD (integer file descriptor) is:
31       -t  a TTY          -T  open
32 
33     --- Tests with one argument on each side of an operator:
34     Two strings:
35       =  are identical   !=  differ         =~  string matches regex
36     Alphabetical sort:
37       <  first is lower  >   first higher
38     Two integers:
39       -eq  equal         -gt  first > second    -lt  first < second
40       -ne  not equal     -ge  first >= second   -le  first <= second
41 
42     --- Modify or combine tests:
43       ! EXPR     not (swap true/false)   EXPR -a EXPR    and (are both true)
44       ( EXPR )   evaluate this first     EXPR -o EXPR    or (is either true)
45 
46 config TEST_GLUE
47   bool
48   default y
49   depends on TEST || SH
50 */
51 
52 #include "toys.h"
53 
54 // Consume 3, 2, or 1 argument test, returning result and *count used.
do_test(char ** args,int * count)55 static int do_test(char **args, int *count)
56 {
57   char c, *s;
58   int i;
59 
60   if (*count>=3) {
61     *count = 3;
62     char *s = args[1], *ss = "eqnegtgeltle";
63     // TODO shell integration case insensitivity
64     if (!strcmp(s, "=") || !strcmp(s, "==")) return !strcmp(args[0], args[2]);
65     if (!strcmp(s, "!=")) return strcmp(args[0], args[2]);
66     if (!strcmp(s, "=~")) {
67       regex_t reg;
68 
69       // TODO: regex needs integrated quoting support with the shell.
70       // Ala [[ abc =~ "1"* ]] matches but [[ abc =~ 1"*" ]] does not
71       xregcomp(&reg, args[2], REG_NOSUB); // REG_EXTENDED? REG_ICASE?
72       i = regexec(&reg, args[0], 0, 0, 0);
73       regfree(&reg);
74 
75       return !i;
76     }
77     if ((*s=='<' || *s=='>') && !s[1]) {
78       i = strcmp(args[0], args[2]);
79       return (*s=='<') ? i<0 : i>0;
80     }
81     if (*s=='-' && strlen(s)==3 && (s = strstr(ss, s+1)) && !((i = s-ss)&1)) {
82       long long a = atolx(args[0]), b = atolx(args[2]);
83 
84       if (!i) return a == b;
85       if (i==2) return a != b;
86       if (i==4) return a > b;
87       if (i==6) return a >= b;
88       if (i==8) return a < b;
89       if (i==10) return a<= b;
90     }
91   }
92   s = *args;
93   if (*count>=2 && *s == '-' && s[1] && !s[2]) {
94     *count = 2;
95     c = s[1];
96     if (c=='a') c = 'e';
97     if (-1 != (i = stridx("hLbcdefgkpSusxwr", c))) {
98       struct stat st;
99 
100       if (i>=13) return !access(args[1], 1<<(i-13));
101       // stat or lstat, check s
102       if (-1 == ((i<2) ? lstat : stat)(args[1], &st)) return 0;
103       if (c == 's') return !!st.st_size; // otherwise 1<<32 == 0
104 
105       // handle file type checking and SUID/SGID
106       if ((i = ((char []){80,80,48,16,32,0,64,2,1,8,96,4}[i])<<9)>=4096)
107         return (st.st_mode&S_IFMT) == i;
108       else return (st.st_mode & i) == i;
109     } else if (c == 'z') return !*args[1];
110     else if (c == 'n') return *args[1];
111     else if (c == 't') return isatty(atolx(args[1]));
112     else if (c == 'T') return -1 != fcntl(atolx(args[1]), F_GETFL);
113   }
114   return *count = 0;
115 }
116 
117 #define NOT 1  // Most recent test had an odd number of preceding !
118 #define AND 2  // test before -a failed since -o or ( so force false
119 #define OR  4  // test before -o succeeded since ( so force true
test_main(void)120 void test_main(void)
121 {
122   char *s = (void *)1;
123   int pos, paren, pstack, result = 0;
124 
125   toys.exitval = 2;
126   if (CFG_TOYBOX && *toys.which->name=='[') {
127     if (toys.optc) for (s = toys.optargs[--toys.optc]; *s==']'; s++);
128     if (*s) error_exit("Missing ']'");
129   }
130 
131   // loop through command line arguments
132   if (toys.optc) for (pos = paren = pstack = 0; ; pos++) {
133     int len = toys.optc-pos;
134 
135     if (!len) perror_exit("need arg @%d", pos);
136 
137     // Evaluate next test
138     result = do_test(toys.optargs+pos, &len);
139     pos += len;
140     // Single argument could be ! ( or nonempty
141     if (!len) {
142       if (toys.optargs[pos+1]) {
143         if (!strcmp("!", toys.optargs[pos])) {
144           pstack ^= NOT;
145           continue;
146         }
147         if (!strcmp("(", toys.optargs[pos])) {
148           if (++paren>9) perror_exit("bad (");
149           pstack <<= 3;
150           continue;
151         }
152       }
153       result = *toys.optargs[pos++];
154     }
155     s = toys.optargs[pos];
156     for (;;) {
157 
158       // Handle pending ! -a -o (the else means -o beats -a)
159       if (pstack&NOT) result = !result;
160       pstack &= ~NOT;
161       if (pstack&OR) result = 1;
162       else if (pstack&AND) result = 0;
163 
164       // Do it again for every )
165       if (!paren || pos==toys.optc || strcmp(")", s)) break;
166       paren--;
167       pstack >>= 3;
168       s = toys.optargs[++pos];
169     }
170 
171     // Out of arguments?
172     if (pos==toys.optc) {
173       if (paren) perror_exit("need )");
174       break;
175     }
176 
177     // are we followed by -a or -o?
178 
179     if (!strcmp("-a", s)) {
180       if (!result) pstack |= AND;
181     } else if (!strcmp("-o", s)) {
182       // -o flushes -a even if previous test was false
183       pstack &=~AND;
184       if (result) pstack |= OR;
185     } else error_exit("too many arguments");
186   }
187 
188   // Invert C logic to get shell logic
189   toys.exitval = !result;
190 }
191