1 /* vi: set sw=4 ts=4: */
3 * test implementation for busybox
5 * Copyright (c) by a whole pile of folks:
7 * test(1); version 7-like -- author Erik Baalbergen
8 * modified by Eric Gisin to be used as built-in.
9 * modified by Arnold Robbins to add SVR3 compatibility
10 * (-x -c -b -p -u -g -k) plus Korn's -L -nt -ot -ef and new -S (socket).
11 * modified by J.T. Conklin for NetBSD.
12 * modified by Herbert Xu to be used as built-in in ash.
13 * modified by Erik Andersen <andersen@codepoet.org> to be used
15 * modified by Bernhard Reutner-Fischer to be useable (i.e. a bit less bloaty).
17 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 * Original copyright notice states:
20 * "This program is in the Public Domain."
23 //config: bool "test (3.6 kb)"
26 //config: test is used to check file types and compare values,
27 //config: returning an appropriate exit code. The bash shell
28 //config: has test built in, ash can build it in optionally.
31 //config: bool "test as ["
34 //config: Provide test command in the "[ EXPR ]" form
37 //config: bool "test as [["
40 //config: Provide test command in the "[[ EXPR ]]" form
42 //config:config FEATURE_TEST_64
43 //config: bool "Extend test to 64 bit"
45 //config: depends on TEST || TEST1 || TEST2 || ASH_TEST || HUSH_TEST
47 //config: Enable 64-bit support in test.
49 //applet:IF_TEST(APPLET_NOFORK(test, test, BB_DIR_USR_BIN, BB_SUID_DROP, test))
50 //applet:IF_TEST1(APPLET_NOFORK([, test, BB_DIR_USR_BIN, BB_SUID_DROP, test))
51 //applet:IF_TEST2(APPLET_NOFORK([[, test, BB_DIR_USR_BIN, BB_SUID_DROP, test))
53 //kbuild:lib-$(CONFIG_TEST) += test.o test_ptr_hack.o
54 //kbuild:lib-$(CONFIG_TEST1) += test.o test_ptr_hack.o
55 //kbuild:lib-$(CONFIG_TEST2) += test.o test_ptr_hack.o
57 //kbuild:lib-$(CONFIG_ASH_TEST) += test.o test_ptr_hack.o
58 //kbuild:lib-$(CONFIG_HUSH_TEST) += test.o test_ptr_hack.o
60 /* "test --help" is special-cased to ignore --help */
61 //usage:#define test_trivial_usage NOUSAGE_STR
62 //usage:#define test_full_usage ""
64 //usage:#define test_example_usage
65 //usage: "$ test 1 -eq 2\n"
66 //usage: "$ echo $?\n"
68 //usage: "$ test 1 -eq 1\n"
69 //usage: "$ echo $?\n"
71 //usage: "$ [ -d /etc ]\n"
72 //usage: "$ echo $?\n"
74 //usage: "$ [ -d /junk ]\n"
75 //usage: "$ echo $?\n"
81 /* This is a NOFORK applet. Be very careful! */
83 /* test_main() is called from shells, and we need to be extra careful here.
84 * This is true regardless of PREFER_APPLETS and SH_STANDALONE
87 /* test(1) accepts the following grammar:
88 oexpr ::= aexpr | aexpr "-o" oexpr ;
89 aexpr ::= nexpr | nexpr "-a" aexpr ;
90 nexpr ::= primary | "!" primary
91 primary ::= unary-operator operand
92 | operand binary-operator operand
96 unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
97 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
99 binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
101 operand ::= <any legal UNIX file name>
104 /* TODO: handle [[ expr ]] bashism bash-compatibly.
105 * [[ ]] is meant to be a "better [ ]", with less weird syntax
106 * and without the risk of variables and quoted strings misinterpreted
108 * This will require support from shells - we need to know quote status
109 * of each parameter (see below).
111 * Word splitting and pathname expansion should NOT be performed:
112 * # a="a b"; [[ $a = "a b" ]] && echo YES
114 * # [[ /bin/m* ]] && echo YES
117 * =~ should do regexp match
118 * = and == should do pattern match against right side:
119 * # [[ *a* == bab ]] && echo YES
120 * # [[ bab == *a* ]] && echo YES
122 * != does the negated == (i.e., also with pattern matching).
123 * Pattern matching is quotation-sensitive:
124 * # [[ bab == "b"a* ]] && echo YES
126 * # [[ bab == b"a*" ]] && echo YES
128 * Conditional operators such as -f must be unquoted literals to be recognized:
129 * # [[ -e /bin ]] && echo YES
131 * # [[ '-e' /bin ]] && echo YES
132 * bash: conditional binary operator expected...
133 * # A='-e'; [[ $A /bin ]] && echo YES
134 * bash: conditional binary operator expected...
136 * || and && should work as -o and -a work in [ ]
137 * -a and -o aren't recognized (&& and || are to be used instead)
138 * ( and ) do not need to be quoted unlike in [ ]:
139 * # [[ ( abc ) && '' ]] && echo YES
140 * # [[ ( abc ) || '' ]] && echo YES
142 * # [[ ( abc ) -o '' ]] && echo YES
143 * bash: syntax error in conditional expression...
145 * Apart from the above, [[ expr ]] should work as [ expr ]
153 FILRD, /* file access */
159 FILREG, /* file type */
170 FILSUID, /* file bit */
174 FILNT, /* file ops */
202 #define is_int_op(a) (((unsigned char)((a) - INTEQ)) <= 5)
203 #define is_str_op(a) (((unsigned char)((a) - STREZ)) <= 5)
204 #define is_file_op(a) (((unsigned char)((a) - FILNT)) <= 2)
205 #define is_file_access(a) (((unsigned char)((a) - FILRD)) <= 2)
206 #define is_file_type(a) (((unsigned char)((a) - FILREG)) <= 5)
207 #define is_file_bit(a) (((unsigned char)((a) - FILSUID)) <= 2)
211 #define nest_msg(...) do { \
213 fprintf(stderr, "%*s", depth*2, ""); \
214 fprintf(stderr, __VA_ARGS__); \
216 #define unnest_msg(...) do { \
217 fprintf(stderr, "%*s", depth*2, ""); \
218 fprintf(stderr, __VA_ARGS__); \
221 #define dbg_msg(...) do { \
222 fprintf(stderr, "%*s", depth*2, ""); \
223 fprintf(stderr, __VA_ARGS__); \
225 #define unnest_msg_and_return(expr, ...) do { \
226 number_t __res = (expr); \
227 fprintf(stderr, "%*s", depth*2, ""); \
228 fprintf(stderr, __VA_ARGS__, res); \
232 static const char *const TOKSTR[] = {
275 #define nest_msg(...) ((void)0)
276 #define unnest_msg(...) ((void)0)
277 #define dbg_msg(...) ((void)0)
278 #define unnest_msg_and_return(expr, ...) return expr
290 unsigned char op_num, op_type;
293 static const struct operator_t ops_table[] = {
294 { /* "-r" */ FILRD , UNOP },
295 { /* "-w" */ FILWR , UNOP },
296 { /* "-x" */ FILEX , UNOP },
297 { /* "-e" */ FILEXIST, UNOP },
298 { /* "-f" */ FILREG , UNOP },
299 { /* "-d" */ FILDIR , UNOP },
300 { /* "-c" */ FILCDEV , UNOP },
301 { /* "-b" */ FILBDEV , UNOP },
302 { /* "-p" */ FILFIFO , UNOP },
303 { /* "-u" */ FILSUID , UNOP },
304 { /* "-g" */ FILSGID , UNOP },
305 { /* "-k" */ FILSTCK , UNOP },
306 { /* "-s" */ FILGZ , UNOP },
307 { /* "-t" */ FILTT , UNOP },
308 { /* "-z" */ STREZ , UNOP },
309 { /* "-n" */ STRNZ , UNOP },
310 { /* "-h" */ FILSYM , UNOP }, /* for backwards compat */
312 { /* "-O" */ FILUID , UNOP },
313 { /* "-G" */ FILGID , UNOP },
314 { /* "-L" */ FILSYM , UNOP },
315 { /* "-S" */ FILSOCK , UNOP },
316 { /* "=" */ STREQ , BINOP },
317 { /* "==" */ STREQ , BINOP },
318 { /* "!=" */ STRNE , BINOP },
319 { /* "<" */ STRLT , BINOP },
320 { /* ">" */ STRGT , BINOP },
321 { /* "-eq"*/ INTEQ , BINOP },
322 { /* "-ne"*/ INTNE , BINOP },
323 { /* "-ge"*/ INTGE , BINOP },
324 { /* "-gt"*/ INTGT , BINOP },
325 { /* "-le"*/ INTLE , BINOP },
326 { /* "-lt"*/ INTLT , BINOP },
327 { /* "-nt"*/ FILNT , BINOP },
328 { /* "-ot"*/ FILOT , BINOP },
329 { /* "-ef"*/ FILEQ , BINOP },
330 { /* "!" */ UNOT , BUNOP },
331 { /* "-a" */ BAND , BBINOP },
332 { /* "-o" */ BOR , BBINOP },
333 { /* "(" */ LPAREN , PAREN },
334 { /* ")" */ RPAREN , PAREN },
336 /* Please keep these two tables in sync */
337 static const char ops_texts[] ALIGN1 =
382 #if ENABLE_FEATURE_TEST_64
383 typedef int64_t number_t;
385 typedef int number_t;
389 /* We try to minimize both static and stack usage. */
390 struct test_statics {
392 /* set only by check_operator(), either to bogus struct
393 * or points to matching operator_t struct. Never NULL. */
394 const struct operator_t *last_operator;
400 /* See test_ptr_hack.c */
401 extern struct test_statics *const test_ptr_to_statics;
403 #define S (*test_ptr_to_statics)
404 #define args (S.args )
405 #define last_operator (S.last_operator)
406 #define group_array (S.group_array )
407 #define ngroups (S.ngroups )
408 #define leaving (S.leaving )
410 #define INIT_S() do { \
411 (*(struct test_statics**)&test_ptr_to_statics) = xzalloc(sizeof(S)); \
414 #define DEINIT_S() do { \
416 free(test_ptr_to_statics); \
419 static number_t primary(enum token n);
421 static void syntax(const char *op, const char *msg) NORETURN;
422 static void syntax(const char *op, const char *msg)
425 bb_error_msg("%s: %s", op, msg);
427 bb_error_msg("%s: %s"+4, msg);
432 /* atoi with error detection */
433 //XXX: FIXME: duplicate of existing libbb function?
434 static number_t getn(const char *s)
437 #if ENABLE_FEATURE_TEST_64
444 #if ENABLE_FEATURE_TEST_64
445 r = strtoll(s, &p, 10);
447 r = strtol(s, &p, 10);
451 syntax(s, "out of range");
453 if (p == s || *(skip_whitespace(p)) != '\0')
454 syntax(s, "bad number");
460 static int newerf(const char *f1, const char *f2)
464 return (stat(f1, &b1) == 0 &&
465 stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
468 static int olderf(const char *f1, const char *f2)
472 return (stat(f1, &b1) == 0 &&
473 stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
476 static int equalf(const char *f1, const char *f2)
480 return (stat(f1, &b1) == 0 &&
481 stat(f2, &b2) == 0 &&
482 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
487 static enum token check_operator(const char *s)
489 static const struct operator_t no_op = {
495 last_operator = &no_op;
498 n = index_in_strings(ops_texts, s);
501 last_operator = &ops_table[n];
502 return ops_table[n].op_num;
506 static int binop(void)
508 const char *opnd1, *opnd2;
509 const struct operator_t *op;
513 check_operator(*++args);
518 syntax(args[-1], "argument expected");
520 if (is_int_op(op->op_num)) {
523 if (op->op_num == INTEQ)
525 if (op->op_num == INTNE)
527 if (op->op_num == INTGE)
529 if (op->op_num == INTGT)
531 if (op->op_num == INTLE)
533 /*if (op->op_num == INTLT)*/
536 if (is_str_op(op->op_num)) {
537 val1 = strcmp(opnd1, opnd2);
538 if (op->op_num == STREQ)
540 if (op->op_num == STRNE)
542 if (op->op_num == STRLT)
544 /*if (op->op_num == STRGT)*/
547 /* We are sure that these three are by now the only binops we didn't check
548 * yet, so we do not check if the class is correct:
550 /* if (is_file_op(op->op_num)) */
554 if (stat(opnd1, &b1) || stat(opnd2, &b2))
555 return 0; /* false, since at least one stat failed */
556 if (op->op_num == FILNT)
557 return b1.st_mtime > b2.st_mtime;
558 if (op->op_num == FILOT)
559 return b1.st_mtime < b2.st_mtime;
560 /*if (op->op_num == FILEQ)*/
561 return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
563 /*return 1; - NOTREACHED */
566 static void initialize_group_array(void)
568 group_array = bb_getgroups(&ngroups, NULL);
571 /* Return non-zero if GID is one that we have in our groups list. */
572 //XXX: FIXME: duplicate of existing libbb function?
573 // see toplevel TODO file:
574 // possible code duplication ingroup() and is_a_group_member()
575 static int is_a_group_member(gid_t gid)
579 /* Short-circuit if possible, maybe saving a call to getgroups(). */
580 if (gid == getgid() || gid == getegid())
584 initialize_group_array();
586 /* Search through the list looking for GID. */
587 for (i = 0; i < ngroups; i++)
588 if (gid == group_array[i])
595 /* Do the same thing access(2) does, but use the effective uid and gid,
596 and don't make the mistake of telling root that any file is
598 static int test_eaccess(struct stat *st, int mode)
600 unsigned int euid = geteuid();
603 /* Root can read or write any file. */
607 /* Root can execute any file that has any one of the execute
609 if (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
613 if (st->st_uid == euid) /* owner */
615 else if (is_a_group_member(st->st_gid))
618 if (st->st_mode & mode)
625 static int filstat(char *nm, enum token mode)
628 unsigned i = i; /* gcc 3.x thinks it can be used uninitialized */
630 if (mode == FILSYM) {
632 if (lstat(nm, &s) == 0) {
640 if (stat(nm, &s) != 0)
642 if (mode == FILEXIST)
644 if (is_file_access(mode)) {
651 return test_eaccess(&s, i) == 0;
653 if (is_file_type(mode)) {
662 if (mode == FILFIFO) {
669 if (mode == FILSOCK) {
677 return ((s.st_mode & S_IFMT) == i);
679 if (is_file_bit(mode)) {
686 return ((s.st_mode & i) != 0);
689 return s.st_size > 0L;
691 return s.st_uid == geteuid();
693 return s.st_gid == getegid();
694 return 1; /* NOTREACHED */
698 static number_t nexpr(enum token n)
702 nest_msg(">nexpr(%s)\n", TOKSTR[n]);
704 n = check_operator(*++args);
706 /* special case: [ ! ], [ a -a ! ] are valid */
707 /* IOW, "! ARG" may miss ARG */
709 unnest_msg("<nexpr:1 (!EOI), args:%s(%p)\n", args[0], &args[0]);
713 unnest_msg("<nexpr:%lld\n", res);
717 unnest_msg("<nexpr:%lld\n", res);
722 static number_t aexpr(enum token n)
726 nest_msg(">aexpr(%s)\n", TOKSTR[n]);
728 dbg_msg("aexpr: nexpr:%lld, next args:%s(%p)\n", res, args[1], &args[1]);
729 if (check_operator(*++args) == BAND) {
730 dbg_msg("aexpr: arg is AND, next args:%s(%p)\n", args[1], &args[1]);
731 res = aexpr(check_operator(*++args)) && res;
732 unnest_msg("<aexpr:%lld\n", res);
736 unnest_msg("<aexpr:%lld, args:%s(%p)\n", res, args[0], &args[0]);
741 static number_t oexpr(enum token n)
745 nest_msg(">oexpr(%s)\n", TOKSTR[n]);
747 dbg_msg("oexpr: aexpr:%lld, next args:%s(%p)\n", res, args[1], &args[1]);
748 if (check_operator(*++args) == BOR) {
749 dbg_msg("oexpr: next arg is OR, next args:%s(%p)\n", args[1], &args[1]);
750 res = oexpr(check_operator(*++args)) || res;
751 unnest_msg("<oexpr:%lld\n", res);
755 unnest_msg("<oexpr:%lld, args:%s(%p)\n", res, args[0], &args[0]);
760 static number_t primary(enum token n)
763 number_t res = res; /* for compiler */
767 const struct operator_t *args0_op;
769 nest_msg(">primary(%s)\n", TOKSTR[n]);
771 syntax(NULL, "argument expected");
774 res = oexpr(check_operator(*++args));
775 if (check_operator(*++args) != RPAREN)
776 syntax(NULL, "closing paren expected");
777 unnest_msg("<primary:%lld\n", res);
781 /* coreutils 6.9 checks "is args[1] binop and args[2] exist?" first,
783 args0_op = last_operator;
784 /* last_operator = operator at args[1] */
785 if (check_operator(args[1]) != EOI) { /* if args[1] != NULL */
787 // coreutils also does this:
788 // if (args[3] && args[0]="-l" && args[2] is BINOP)
789 // return binop(1 /* prepended by -l */);
790 if (last_operator->op_type == BINOP)
791 unnest_msg_and_return(binop(), "<primary: binop:%lld\n");
794 /* check "is args[0] unop?" second */
795 if (args0_op->op_type == UNOP) {
796 /* unary expression */
798 // syntax(args0_op->op_text, "argument expected");
799 goto check_emptiness;
802 unnest_msg_and_return(args[0][0] == '\0', "<primary:%lld\n");
804 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
806 unnest_msg_and_return(isatty(getn(*args)), "<primary: isatty(%s)%lld\n", *args);
807 unnest_msg_and_return(filstat(*args, n), "<primary: filstat(%s):%lld\n", *args);
810 /*check_operator(args[1]); - already done */
811 if (last_operator->op_type == BINOP) {
812 /* args[2] is known to be NULL, isn't it bound to fail? */
813 unnest_msg_and_return(binop(), "<primary:%lld\n");
816 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
820 int test_main(int argc, char **argv)
825 arg0 = bb_basename(argv[0]);
826 if ((ENABLE_TEST1 || ENABLE_TEST2 || ENABLE_ASH_TEST || ENABLE_HUSH_TEST)
830 if (!arg0[1]) { /* "[" ? */
831 if (NOT_LONE_CHAR(argv[argc], ']')) {
832 bb_error_msg("missing ]");
835 } else { /* assuming "[[" */
836 if (strcmp(argv[argc], "]]") != 0) {
837 bb_error_msg("missing ]]");
843 /* argc is unused after this point */
845 /* We must do DEINIT_S() prior to returning */
848 res = setjmp(leaving);
852 /* resetting ngroups is probably unnecessary. it will
853 * force a new call to getgroups(), which prevents using
854 * group data fetched during a previous call. but the
855 * only way the group data could be stale is if there's
856 * been an intervening call to setgroups(), and this
857 * isn't likely in the case of a shell. paranoia
860 /*ngroups = 0; - done by INIT_S() */
865 /* Implement special cases from POSIX.2, section 4.62.4.
866 * Testcase: "test '(' = '('"
867 * The general parser would misinterpret '(' as group start.
879 res = (argv[0][0] == '\0');
885 * http://pubs.opengroup.org/onlinepubs/009695399/utilities/test.html
887 * If $2 is a binary primary, perform the binary test of $1 and $3.
890 check_operator(argv[1]);
891 if (last_operator->op_type == BINOP) {
892 /* "test [!] arg1 <binary_op> arg2" */
894 res = (binop() == 0);
896 /* If there was leading "!" op... */
900 /* """If $1 is '(' and $3 is ')', perform the unary test of $2."""
901 * Looks like this works without additional coding.
905 /* argv[3] exists (at least 4 args), is it exactly 4 args? */
909 * If $1 is '!', negate the three-argument test of $2, $3, and $4.
910 * If $1 is '(' and $4 is ')', perform the two-argument test of $2 and $3.
912 * Example why code below is necessary: test '(' ! -e ')'
914 if (LONE_CHAR(argv[0], '(')
915 && LONE_CHAR(argv[3], ')')
917 /* "test [!] ( x y )" */
924 if (LONE_CHAR(argv[0], '!')) {
931 res = !oexpr(check_operator(*args));
933 if (*args != NULL && *++args != NULL) {
938 bb_error_msg("%s: unknown operand", *args);