• 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 [-bcdefghkLprSsuwx 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
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   }
113   return *count = 0;
114 }
115 
116 #define NOT 1  // Most recent test had an odd number of preceding !
117 #define AND 2  // test before -a failed since -o or ( so force false
118 #define OR  4  // test before -o succeeded since ( so force true
test_main(void)119 void test_main(void)
120 {
121   char *s = (void *)1;
122   int pos, paren, pstack, result = 0;
123 
124   toys.exitval = 2;
125   if (CFG_TOYBOX && *toys.which->name=='[') {
126     if (toys.optc) for (s = toys.optargs[--toys.optc]; *s==']'; s++);
127     if (*s) error_exit("Missing ']'");
128   }
129 
130   // loop through command line arguments
131   if (toys.optc) for (pos = paren = pstack = 0; ; pos++) {
132     int len = toys.optc-pos;
133 
134     if (!len) perror_exit("need arg @%d", pos);
135 
136     // Evaluate next test
137     result = do_test(toys.optargs+pos, &len);
138     pos += len;
139     // Single argument could be ! ( or nonempty
140     if (!len) {
141       if (toys.optargs[pos+1]) {
142         if (!strcmp("!", toys.optargs[pos])) {
143           pstack ^= NOT;
144           continue;
145         }
146         if (!strcmp("(", toys.optargs[pos])) {
147           if (++paren>9) perror_exit("bad (");
148           pstack <<= 3;
149           continue;
150         }
151       }
152       result = *toys.optargs[pos++];
153     }
154     s = toys.optargs[pos];
155     for (;;) {
156 
157       // Handle pending ! -a -o (the else means -o beats -a)
158       if (pstack&NOT) result = !result;
159       pstack &= ~NOT;
160       if (pstack&OR) result = 1;
161       else if (pstack&AND) result = 0;
162 
163       // Do it again for every )
164       if (!paren || pos==toys.optc || strcmp(")", s)) break;
165       paren--;
166       pstack >>= 3;
167       s = toys.optargs[++pos];
168     }
169 
170     // Out of arguments?
171     if (pos==toys.optc) {
172       if (paren) perror_exit("need )");
173       break;
174     }
175 
176     // are we followed by -a or -o?
177 
178     if (!strcmp("-a", s)) {
179       if (!result) pstack |= AND;
180     } else if (!strcmp("-o", s)) {
181       // -o flushes -a even if previous test was false
182       pstack &=~AND;
183       if (result) pstack |= OR;
184     } else error_exit("too many arguments");
185   }
186 
187   // Invert C logic to get shell logic
188   toys.exitval = !result;
189 }
190