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"
80 /* This is a NOFORK applet. Be very careful! */
82 /* test_main() is called from shells, and we need to be extra careful here.
83 * This is true regardless of PREFER_APPLETS and SH_STANDALONE
86 /* test(1) accepts the following grammar:
87 oexpr ::= aexpr | aexpr "-o" oexpr ;
88 aexpr ::= nexpr | nexpr "-a" aexpr ;
89 nexpr ::= primary | "!" primary
90 primary ::= unary-operator operand
91 | operand binary-operator operand
95 unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
96 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
98 binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
100 operand ::= <any legal UNIX file name>
103 /* TODO: handle [[ expr ]] bashism bash-compatibly.
104 * [[ ]] is meant to be a "better [ ]", with less weird syntax
105 * and without the risk of variables and quoted strings misinterpreted
107 * This will require support from shells - we need to know quote status
108 * of each parameter (see below).
110 * Word splitting and pathname expansion should NOT be performed:
111 * # a="a b"; [[ $a = "a b" ]] && echo YES
113 * # [[ /bin/m* ]] && echo YES
116 * =~ should do regexp match
117 * = and == should do pattern match against right side:
118 * # [[ *a* == bab ]] && echo YES
119 * # [[ bab == *a* ]] && echo YES
121 * != does the negated == (i.e., also with pattern matching).
122 * Pattern matching is quotation-sensitive:
123 * # [[ bab == "b"a* ]] && echo YES
125 * # [[ bab == b"a*" ]] && echo YES
127 * Conditional operators such as -f must be unquoted literals to be recognized:
128 * # [[ -e /bin ]] && echo YES
130 * # [[ '-e' /bin ]] && echo YES
131 * bash: conditional binary operator expected...
132 * # A='-e'; [[ $A /bin ]] && echo YES
133 * bash: conditional binary operator expected...
135 * || and && should work as -o and -a work in [ ]
136 * -a and -o aren't recognized (&& and || are to be used instead)
137 * ( and ) do not need to be quoted unlike in [ ]:
138 * # [[ ( abc ) && '' ]] && echo YES
139 * # [[ ( abc ) || '' ]] && echo YES
141 * # [[ ( abc ) -o '' ]] && echo YES
142 * bash: syntax error in conditional expression...
144 * Apart from the above, [[ expr ]] should work as [ expr ]
152 FILRD, /* file access */
158 FILREG, /* file type */
169 FILSUID, /* file bit */
173 FILNT, /* file ops */
201 #define is_int_op(a) (((unsigned char)((a) - INTEQ)) <= 5)
202 #define is_str_op(a) (((unsigned char)((a) - STREZ)) <= 5)
203 #define is_file_op(a) (((unsigned char)((a) - FILNT)) <= 2)
204 #define is_file_access(a) (((unsigned char)((a) - FILRD)) <= 2)
205 #define is_file_type(a) (((unsigned char)((a) - FILREG)) <= 5)
206 #define is_file_bit(a) (((unsigned char)((a) - FILSUID)) <= 2)
210 #define nest_msg(...) do { \
212 fprintf(stderr, "%*s", depth*2, ""); \
213 fprintf(stderr, __VA_ARGS__); \
215 #define unnest_msg(...) do { \
216 fprintf(stderr, "%*s", depth*2, ""); \
217 fprintf(stderr, __VA_ARGS__); \
220 #define dbg_msg(...) do { \
221 fprintf(stderr, "%*s", depth*2, ""); \
222 fprintf(stderr, __VA_ARGS__); \
224 #define unnest_msg_and_return(expr, ...) do { \
225 number_t __res = (expr); \
226 fprintf(stderr, "%*s", depth*2, ""); \
227 fprintf(stderr, __VA_ARGS__, res); \
231 static const char *const TOKSTR[] = {
274 #define nest_msg(...) ((void)0)
275 #define unnest_msg(...) ((void)0)
276 #define dbg_msg(...) ((void)0)
277 #define unnest_msg_and_return(expr, ...) return expr
289 unsigned char op_num, op_type;
292 static const struct operator_t ops_table[] = {
293 { /* "-r" */ FILRD , UNOP },
294 { /* "-w" */ FILWR , UNOP },
295 { /* "-x" */ FILEX , UNOP },
296 { /* "-e" */ FILEXIST, UNOP },
297 { /* "-f" */ FILREG , UNOP },
298 { /* "-d" */ FILDIR , UNOP },
299 { /* "-c" */ FILCDEV , UNOP },
300 { /* "-b" */ FILBDEV , UNOP },
301 { /* "-p" */ FILFIFO , UNOP },
302 { /* "-u" */ FILSUID , UNOP },
303 { /* "-g" */ FILSGID , UNOP },
304 { /* "-k" */ FILSTCK , UNOP },
305 { /* "-s" */ FILGZ , UNOP },
306 { /* "-t" */ FILTT , UNOP },
307 { /* "-z" */ STREZ , UNOP },
308 { /* "-n" */ STRNZ , UNOP },
309 { /* "-h" */ FILSYM , UNOP }, /* for backwards compat */
311 { /* "-O" */ FILUID , UNOP },
312 { /* "-G" */ FILGID , UNOP },
313 { /* "-L" */ FILSYM , UNOP },
314 { /* "-S" */ FILSOCK , UNOP },
315 { /* "=" */ STREQ , BINOP },
316 /* "==" is bashism, http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html
317 * lists only "=" as comparison operator.
319 { /* "==" */ STREQ , BINOP },
320 { /* "!=" */ STRNE , BINOP },
321 { /* "<" */ STRLT , BINOP },
322 { /* ">" */ STRGT , BINOP },
323 { /* "-eq"*/ INTEQ , BINOP },
324 { /* "-ne"*/ INTNE , BINOP },
325 { /* "-ge"*/ INTGE , BINOP },
326 { /* "-gt"*/ INTGT , BINOP },
327 { /* "-le"*/ INTLE , BINOP },
328 { /* "-lt"*/ INTLT , BINOP },
329 { /* "-nt"*/ FILNT , BINOP },
330 { /* "-ot"*/ FILOT , BINOP },
331 { /* "-ef"*/ FILEQ , BINOP },
332 { /* "!" */ UNOT , BUNOP },
333 { /* "-a" */ BAND , BBINOP },
334 { /* "-o" */ BOR , BBINOP },
335 { /* "(" */ LPAREN , PAREN },
336 { /* ")" */ RPAREN , PAREN },
338 /* Please keep these two tables in sync */
339 static const char ops_texts[] ALIGN1 =
363 /* "==" is bashism */
385 #if ENABLE_FEATURE_TEST_64
386 typedef int64_t number_t;
388 typedef int number_t;
392 /* We try to minimize both static and stack usage. */
393 struct test_statics {
395 /* set only by check_operator(), either to bogus struct
396 * or points to matching operator_t struct. Never NULL. */
397 const struct operator_t *last_operator;
403 /* See test_ptr_hack.c */
404 extern struct test_statics *const test_ptr_to_statics;
406 #define S (*test_ptr_to_statics)
407 #define args (S.args )
408 #define last_operator (S.last_operator)
409 #define group_array (S.group_array )
410 #define ngroups (S.ngroups )
411 #define leaving (S.leaving )
413 #define INIT_S() do { \
414 (*(struct test_statics**)&test_ptr_to_statics) = xzalloc(sizeof(S)); \
417 #define DEINIT_S() do { \
419 free(test_ptr_to_statics); \
422 static number_t primary(enum token n);
424 static void syntax(const char *op, const char *msg) NORETURN;
425 static void syntax(const char *op, const char *msg)
428 bb_error_msg("%s: %s", op, msg);
430 bb_error_msg("%s: %s"+4, msg);
435 /* atoi with error detection */
436 //XXX: FIXME: duplicate of existing libbb function?
437 static number_t getn(const char *s)
440 #if ENABLE_FEATURE_TEST_64
447 #if ENABLE_FEATURE_TEST_64
448 r = strtoll(s, &p, 10);
450 r = strtol(s, &p, 10);
454 syntax(s, "out of range");
456 if (p == s || *(skip_whitespace(p)) != '\0')
457 syntax(s, "bad number");
463 static int newerf(const char *f1, const char *f2)
467 return (stat(f1, &b1) == 0 &&
468 stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
471 static int olderf(const char *f1, const char *f2)
475 return (stat(f1, &b1) == 0 &&
476 stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
479 static int equalf(const char *f1, const char *f2)
483 return (stat(f1, &b1) == 0 &&
484 stat(f2, &b2) == 0 &&
485 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
490 static enum token check_operator(const char *s)
492 static const struct operator_t no_op = {
498 last_operator = &no_op;
501 n = index_in_strings(ops_texts, s);
504 last_operator = &ops_table[n];
505 return ops_table[n].op_num;
509 static int binop(void)
511 const char *opnd1, *opnd2;
512 const struct operator_t *op;
516 check_operator(*++args);
521 syntax(args[-1], "argument expected");
523 if (is_int_op(op->op_num)) {
526 if (op->op_num == INTEQ)
528 if (op->op_num == INTNE)
530 if (op->op_num == INTGE)
532 if (op->op_num == INTGT)
534 if (op->op_num == INTLE)
536 /*if (op->op_num == INTLT)*/
539 if (is_str_op(op->op_num)) {
540 val1 = strcmp(opnd1, opnd2);
541 if (op->op_num == STREQ)
543 if (op->op_num == STRNE)
545 if (op->op_num == STRLT)
547 /*if (op->op_num == STRGT)*/
550 /* We are sure that these three are by now the only binops we didn't check
551 * yet, so we do not check if the class is correct:
553 /* if (is_file_op(op->op_num)) */
557 if (stat(opnd1, &b1) || stat(opnd2, &b2))
558 return 0; /* false, since at least one stat failed */
559 if (op->op_num == FILNT)
560 return b1.st_mtime > b2.st_mtime;
561 if (op->op_num == FILOT)
562 return b1.st_mtime < b2.st_mtime;
563 /*if (op->op_num == FILEQ)*/
564 return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
566 /*return 1; - NOTREACHED */
569 static void initialize_group_array(void)
571 group_array = bb_getgroups(&ngroups, NULL);
574 /* Return non-zero if GID is one that we have in our groups list. */
575 //XXX: FIXME: duplicate of existing libbb function?
576 // see toplevel TODO file:
577 // possible code duplication ingroup() and is_a_group_member()
578 static int is_a_group_member(gid_t gid)
582 /* Short-circuit if possible, maybe saving a call to getgroups(). */
583 if (gid == getgid() || gid == getegid())
587 initialize_group_array();
589 /* Search through the list looking for GID. */
590 for (i = 0; i < ngroups; i++)
591 if (gid == group_array[i])
598 /* Do the same thing access(2) does, but use the effective uid and gid,
599 and don't make the mistake of telling root that any file is
601 static int test_eaccess(struct stat *st, int mode)
603 unsigned int euid = geteuid();
606 /* Root can read or write any file. */
610 /* Root can execute any file that has any one of the execute
612 if (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
616 if (st->st_uid == euid) /* owner */
618 else if (is_a_group_member(st->st_gid))
621 if (st->st_mode & mode)
628 static int filstat(char *nm, enum token mode)
631 unsigned i = i; /* gcc 3.x thinks it can be used uninitialized */
633 if (mode == FILSYM) {
635 if (lstat(nm, &s) == 0) {
643 if (stat(nm, &s) != 0)
645 if (mode == FILEXIST)
647 if (is_file_access(mode)) {
654 return test_eaccess(&s, i) == 0;
656 if (is_file_type(mode)) {
665 if (mode == FILFIFO) {
672 if (mode == FILSOCK) {
680 return ((s.st_mode & S_IFMT) == i);
682 if (is_file_bit(mode)) {
689 return ((s.st_mode & i) != 0);
692 return s.st_size > 0L;
694 return s.st_uid == geteuid();
696 return s.st_gid == getegid();
697 return 1; /* NOTREACHED */
701 static number_t nexpr(enum token n)
705 nest_msg(">nexpr(%s)\n", TOKSTR[n]);
707 n = check_operator(*++args);
709 /* special case: [ ! ], [ a -a ! ] are valid */
710 /* IOW, "! ARG" may miss ARG */
712 unnest_msg("<nexpr:1 (!EOI), args:%s(%p)\n", args[0], &args[0]);
716 unnest_msg("<nexpr:%lld\n", res);
720 unnest_msg("<nexpr:%lld\n", res);
725 static number_t aexpr(enum token n)
729 nest_msg(">aexpr(%s)\n", TOKSTR[n]);
731 dbg_msg("aexpr: nexpr:%lld, next args:%s(%p)\n", res, args[1], &args[1]);
732 if (check_operator(*++args) == BAND) {
733 dbg_msg("aexpr: arg is AND, next args:%s(%p)\n", args[1], &args[1]);
734 res = aexpr(check_operator(*++args)) && res;
735 unnest_msg("<aexpr:%lld\n", res);
739 unnest_msg("<aexpr:%lld, args:%s(%p)\n", res, args[0], &args[0]);
744 static number_t oexpr(enum token n)
748 nest_msg(">oexpr(%s)\n", TOKSTR[n]);
750 dbg_msg("oexpr: aexpr:%lld, next args:%s(%p)\n", res, args[1], &args[1]);
751 if (check_operator(*++args) == BOR) {
752 dbg_msg("oexpr: next arg is OR, next args:%s(%p)\n", args[1], &args[1]);
753 res = oexpr(check_operator(*++args)) || res;
754 unnest_msg("<oexpr:%lld\n", res);
758 unnest_msg("<oexpr:%lld, args:%s(%p)\n", res, args[0], &args[0]);
763 static number_t primary(enum token n)
766 number_t res = res; /* for compiler */
770 const struct operator_t *args0_op;
772 nest_msg(">primary(%s)\n", TOKSTR[n]);
774 syntax(NULL, "argument expected");
777 res = oexpr(check_operator(*++args));
778 if (check_operator(*++args) != RPAREN)
779 syntax(NULL, "closing paren expected");
780 unnest_msg("<primary:%lld\n", res);
784 /* coreutils 6.9 checks "is args[1] binop and args[2] exist?" first,
786 args0_op = last_operator;
787 /* last_operator = operator at args[1] */
788 if (check_operator(args[1]) != EOI) { /* if args[1] != NULL */
790 // coreutils also does this:
791 // if (args[3] && args[0]="-l" && args[2] is BINOP)
792 // return binop(1 /* prepended by -l */);
793 if (last_operator->op_type == BINOP)
794 unnest_msg_and_return(binop(), "<primary: binop:%lld\n");
797 /* check "is args[0] unop?" second */
798 if (args0_op->op_type == UNOP) {
799 /* unary expression */
801 // syntax(args0_op->op_text, "argument expected");
802 goto check_emptiness;
805 unnest_msg_and_return(args[0][0] == '\0', "<primary:%lld\n");
807 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
809 unnest_msg_and_return(isatty(getn(*args)), "<primary: isatty(%s)%lld\n", *args);
810 unnest_msg_and_return(filstat(*args, n), "<primary: filstat(%s):%lld\n", *args);
813 /*check_operator(args[1]); - already done */
814 if (last_operator->op_type == BINOP) {
815 /* args[2] is known to be NULL, isn't it bound to fail? */
816 unnest_msg_and_return(binop(), "<primary:%lld\n");
819 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
823 int test_main(int argc, char **argv)
828 arg0 = bb_basename(argv[0]);
829 if ((ENABLE_TEST1 || ENABLE_TEST2 || ENABLE_ASH_TEST || ENABLE_HUSH_TEST)
833 if (!arg0[1]) { /* "[" ? */
834 if (NOT_LONE_CHAR(argv[argc], ']')) {
835 bb_error_msg("missing ]");
838 } else { /* assuming "[[" */
839 if (strcmp(argv[argc], "]]") != 0) {
840 bb_error_msg("missing ]]");
846 /* argc is unused after this point */
848 /* We must do DEINIT_S() prior to returning */
851 res = setjmp(leaving);
855 /* resetting ngroups is probably unnecessary. it will
856 * force a new call to getgroups(), which prevents using
857 * group data fetched during a previous call. but the
858 * only way the group data could be stale is if there's
859 * been an intervening call to setgroups(), and this
860 * isn't likely in the case of a shell. paranoia
863 /*ngroups = 0; - done by INIT_S() */
868 /* Implement special cases from POSIX.2, section 4.62.4.
869 * Testcase: "test '(' = '('"
870 * The general parser would misinterpret '(' as group start.
882 res = (argv[0][0] == '\0');
888 * http://pubs.opengroup.org/onlinepubs/009695399/utilities/test.html
890 * If $2 is a binary primary, perform the binary test of $1 and $3.
893 check_operator(argv[1]);
894 if (last_operator->op_type == BINOP) {
895 /* "test [!] arg1 <binary_op> arg2" */
897 res = (binop() == 0);
899 /* If there was leading "!" op... */
903 /* """If $1 is '(' and $3 is ')', perform the unary test of $2."""
904 * Looks like this works without additional coding.
908 /* argv[3] exists (at least 4 args), is it exactly 4 args? */
912 * If $1 is '!', negate the three-argument test of $2, $3, and $4.
913 * If $1 is '(' and $4 is ')', perform the two-argument test of $2 and $3.
915 * Example why code below is necessary: test '(' ! -e ')'
917 if (LONE_CHAR(argv[0], '(')
918 && LONE_CHAR(argv[3], ')')
920 /* "test [!] ( x y )" */
927 if (LONE_CHAR(argv[0], '!')) {
934 res = !oexpr(check_operator(*args));
936 if (*args != NULL && *++args != NULL) {
941 bb_error_msg("%s: unknown operand", *args);