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 //kbuild:lib-$(CONFIG_TEST) += test.o test_ptr_hack.o
24 //kbuild:lib-$(CONFIG_ASH) += test.o test_ptr_hack.o
25 //kbuild:lib-$(CONFIG_HUSH) += test.o test_ptr_hack.o
31 //config: test is used to check file types and compare values,
32 //config: returning an appropriate exit code. The bash shell
33 //config: has test built in, ash can build it in optionally.
35 //config:config FEATURE_TEST_64
36 //config: bool "Extend test to 64 bit"
38 //config: depends on TEST || ASH_BUILTIN_TEST || HUSH
40 //config: Enable 64-bit support in test.
45 /* This is a NOFORK applet. Be very careful! */
47 /* test_main() is called from shells, and we need to be extra careful here.
48 * This is true regardless of PREFER_APPLETS and STANDALONE_SHELL
51 /* test(1) accepts the following grammar:
52 oexpr ::= aexpr | aexpr "-o" oexpr ;
53 aexpr ::= nexpr | nexpr "-a" aexpr ;
54 nexpr ::= primary | "!" primary
55 primary ::= unary-operator operand
56 | operand binary-operator operand
60 unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
61 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
63 binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
65 operand ::= <any legal UNIX file name>
68 /* TODO: handle [[ expr ]] bashism bash-compatibly.
69 * [[ ]] is meant to be a "better [ ]", with less weird syntax
70 * and without the risk of variables and quoted strings misinterpreted
72 * This will require support from shells - we need to know quote status
73 * of each parameter (see below).
75 * Word splitting and pathname expansion should NOT be performed:
76 * # a="a b"; [[ $a = "a b" ]] && echo YES
78 * # [[ /bin/m* ]] && echo YES
81 * =~ should do regexp match
82 * = and == should do pattern match against right side:
83 * # [[ *a* == bab ]] && echo YES
84 * # [[ bab == *a* ]] && echo YES
86 * != does the negated == (i.e., also with pattern matching).
87 * Pattern matching is quotation-sensitive:
88 * # [[ bab == "b"a* ]] && echo YES
90 * # [[ bab == b"a*" ]] && echo YES
92 * Conditional operators such as -f must be unquoted literals to be recognized:
93 * # [[ -e /bin ]] && echo YES
95 * # [[ '-e' /bin ]] && echo YES
96 * bash: conditional binary operator expected...
97 * # A='-e'; [[ $A /bin ]] && echo YES
98 * bash: conditional binary operator expected...
100 * || and && should work as -o and -a work in [ ]
101 * -a and -o aren't recognized (&& and || are to be used instead)
102 * ( and ) do not need to be quoted unlike in [ ]:
103 * # [[ ( abc ) && '' ]] && echo YES
104 * # [[ ( abc ) || '' ]] && echo YES
106 * # [[ ( abc ) -o '' ]] && echo YES
107 * bash: syntax error in conditional expression...
109 * Apart from the above, [[ expr ]] should work as [ expr ]
117 FILRD, /* file access */
123 FILREG, /* file type */
134 FILSUID, /* file bit */
138 FILNT, /* file ops */
166 #define is_int_op(a) (((unsigned char)((a) - INTEQ)) <= 5)
167 #define is_str_op(a) (((unsigned char)((a) - STREZ)) <= 5)
168 #define is_file_op(a) (((unsigned char)((a) - FILNT)) <= 2)
169 #define is_file_access(a) (((unsigned char)((a) - FILRD)) <= 2)
170 #define is_file_type(a) (((unsigned char)((a) - FILREG)) <= 5)
171 #define is_file_bit(a) (((unsigned char)((a) - FILSUID)) <= 2)
175 #define nest_msg(...) do { \
177 fprintf(stderr, "%*s", depth*2, ""); \
178 fprintf(stderr, __VA_ARGS__); \
180 #define unnest_msg(...) do { \
181 fprintf(stderr, "%*s", depth*2, ""); \
182 fprintf(stderr, __VA_ARGS__); \
185 #define dbg_msg(...) do { \
186 fprintf(stderr, "%*s", depth*2, ""); \
187 fprintf(stderr, __VA_ARGS__); \
189 #define unnest_msg_and_return(expr, ...) do { \
190 number_t __res = (expr); \
191 fprintf(stderr, "%*s", depth*2, ""); \
192 fprintf(stderr, __VA_ARGS__, res); \
196 static const char *const TOKSTR[] = {
239 #define nest_msg(...) ((void)0)
240 #define unnest_msg(...) ((void)0)
241 #define dbg_msg(...) ((void)0)
242 #define unnest_msg_and_return(expr, ...) return expr
254 unsigned char op_num, op_type;
257 static const struct operator_t ops_table[] = {
258 { /* "-r" */ FILRD , UNOP },
259 { /* "-w" */ FILWR , UNOP },
260 { /* "-x" */ FILEX , UNOP },
261 { /* "-e" */ FILEXIST, UNOP },
262 { /* "-f" */ FILREG , UNOP },
263 { /* "-d" */ FILDIR , UNOP },
264 { /* "-c" */ FILCDEV , UNOP },
265 { /* "-b" */ FILBDEV , UNOP },
266 { /* "-p" */ FILFIFO , UNOP },
267 { /* "-u" */ FILSUID , UNOP },
268 { /* "-g" */ FILSGID , UNOP },
269 { /* "-k" */ FILSTCK , UNOP },
270 { /* "-s" */ FILGZ , UNOP },
271 { /* "-t" */ FILTT , UNOP },
272 { /* "-z" */ STREZ , UNOP },
273 { /* "-n" */ STRNZ , UNOP },
274 { /* "-h" */ FILSYM , UNOP }, /* for backwards compat */
276 { /* "-O" */ FILUID , UNOP },
277 { /* "-G" */ FILGID , UNOP },
278 { /* "-L" */ FILSYM , UNOP },
279 { /* "-S" */ FILSOCK , UNOP },
280 { /* "=" */ STREQ , BINOP },
281 { /* "==" */ STREQ , BINOP },
282 { /* "!=" */ STRNE , BINOP },
283 { /* "<" */ STRLT , BINOP },
284 { /* ">" */ STRGT , BINOP },
285 { /* "-eq"*/ INTEQ , BINOP },
286 { /* "-ne"*/ INTNE , BINOP },
287 { /* "-ge"*/ INTGE , BINOP },
288 { /* "-gt"*/ INTGT , BINOP },
289 { /* "-le"*/ INTLE , BINOP },
290 { /* "-lt"*/ INTLT , BINOP },
291 { /* "-nt"*/ FILNT , BINOP },
292 { /* "-ot"*/ FILOT , BINOP },
293 { /* "-ef"*/ FILEQ , BINOP },
294 { /* "!" */ UNOT , BUNOP },
295 { /* "-a" */ BAND , BBINOP },
296 { /* "-o" */ BOR , BBINOP },
297 { /* "(" */ LPAREN , PAREN },
298 { /* ")" */ RPAREN , PAREN },
300 /* Please keep these two tables in sync */
301 static const char ops_texts[] ALIGN1 =
346 #if ENABLE_FEATURE_TEST_64
347 typedef int64_t number_t;
349 typedef int number_t;
353 /* We try to minimize both static and stack usage. */
354 struct test_statics {
356 /* set only by check_operator(), either to bogus struct
357 * or points to matching operator_t struct. Never NULL. */
358 const struct operator_t *last_operator;
364 /* See test_ptr_hack.c */
365 extern struct test_statics *const test_ptr_to_statics;
367 #define S (*test_ptr_to_statics)
368 #define args (S.args )
369 #define last_operator (S.last_operator)
370 #define group_array (S.group_array )
371 #define ngroups (S.ngroups )
372 #define leaving (S.leaving )
374 #define INIT_S() do { \
375 (*(struct test_statics**)&test_ptr_to_statics) = xzalloc(sizeof(S)); \
378 #define DEINIT_S() do { \
379 free(test_ptr_to_statics); \
382 static number_t primary(enum token n);
384 static void syntax(const char *op, const char *msg) NORETURN;
385 static void syntax(const char *op, const char *msg)
388 bb_error_msg("%s: %s", op, msg);
390 bb_error_msg("%s: %s"+4, msg);
395 /* atoi with error detection */
396 //XXX: FIXME: duplicate of existing libbb function?
397 static number_t getn(const char *s)
400 #if ENABLE_FEATURE_TEST_64
407 #if ENABLE_FEATURE_TEST_64
408 r = strtoll(s, &p, 10);
410 r = strtol(s, &p, 10);
414 syntax(s, "out of range");
416 if (p == s || *(skip_whitespace(p)) != '\0')
417 syntax(s, "bad number");
423 static int newerf(const char *f1, const char *f2)
427 return (stat(f1, &b1) == 0 &&
428 stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
431 static int olderf(const char *f1, const char *f2)
435 return (stat(f1, &b1) == 0 &&
436 stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
439 static int equalf(const char *f1, const char *f2)
443 return (stat(f1, &b1) == 0 &&
444 stat(f2, &b2) == 0 &&
445 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
450 static enum token check_operator(const char *s)
452 static const struct operator_t no_op = {
458 last_operator = &no_op;
461 n = index_in_strings(ops_texts, s);
464 last_operator = &ops_table[n];
465 return ops_table[n].op_num;
469 static int binop(void)
471 const char *opnd1, *opnd2;
472 const struct operator_t *op;
476 check_operator(*++args);
481 syntax(args[-1], "argument expected");
483 if (is_int_op(op->op_num)) {
486 if (op->op_num == INTEQ)
488 if (op->op_num == INTNE)
490 if (op->op_num == INTGE)
492 if (op->op_num == INTGT)
494 if (op->op_num == INTLE)
496 /*if (op->op_num == INTLT)*/
499 if (is_str_op(op->op_num)) {
500 val1 = strcmp(opnd1, opnd2);
501 if (op->op_num == STREQ)
503 if (op->op_num == STRNE)
505 if (op->op_num == STRLT)
507 /*if (op->op_num == STRGT)*/
510 /* We are sure that these three are by now the only binops we didn't check
511 * yet, so we do not check if the class is correct:
513 /* if (is_file_op(op->op_num)) */
517 if (stat(opnd1, &b1) || stat(opnd2, &b2))
518 return 0; /* false, since at least one stat failed */
519 if (op->op_num == FILNT)
520 return b1.st_mtime > b2.st_mtime;
521 if (op->op_num == FILOT)
522 return b1.st_mtime < b2.st_mtime;
523 /*if (op->op_num == FILEQ)*/
524 return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
526 /*return 1; - NOTREACHED */
530 static void initialize_group_array(void)
534 /* getgroups may be expensive, try to use it only once */
537 /* FIXME: ash tries so hard to not die on OOM,
538 * and we spoil it with just one xrealloc here */
539 /* We realloc, because test_main can be entered repeatedly by shell.
540 * Testcase (ash): 'while true; do test -x some_file; done'
541 * and watch top. (some_file must have owner != you) */
543 group_array = xrealloc(group_array, n * sizeof(gid_t));
544 ngroups = getgroups(n, group_array);
545 } while (ngroups > n);
549 /* Return non-zero if GID is one that we have in our groups list. */
550 //XXX: FIXME: duplicate of existing libbb function?
551 // see toplevel TODO file:
552 // possible code duplication ingroup() and is_a_group_member()
553 static int is_a_group_member(gid_t gid)
557 /* Short-circuit if possible, maybe saving a call to getgroups(). */
558 if (gid == getgid() || gid == getegid())
562 initialize_group_array();
564 /* Search through the list looking for GID. */
565 for (i = 0; i < ngroups; i++)
566 if (gid == group_array[i])
573 /* Do the same thing access(2) does, but use the effective uid and gid,
574 and don't make the mistake of telling root that any file is
576 static int test_eaccess(char *path, int mode)
579 unsigned int euid = geteuid();
581 if (stat(path, &st) < 0)
585 /* Root can read or write any file. */
589 /* Root can execute any file that has any one of the execute
591 if (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
595 if (st.st_uid == euid) /* owner */
597 else if (is_a_group_member(st.st_gid))
600 if (st.st_mode & mode)
607 static int filstat(char *nm, enum token mode)
610 unsigned i = i; /* gcc 3.x thinks it can be used uninitialized */
612 if (mode == FILSYM) {
614 if (lstat(nm, &s) == 0) {
622 if (stat(nm, &s) != 0)
624 if (mode == FILEXIST)
626 if (is_file_access(mode)) {
633 return test_eaccess(nm, i) == 0;
635 if (is_file_type(mode)) {
644 if (mode == FILFIFO) {
651 if (mode == FILSOCK) {
659 return ((s.st_mode & S_IFMT) == i);
661 if (is_file_bit(mode)) {
668 return ((s.st_mode & i) != 0);
671 return s.st_size > 0L;
673 return s.st_uid == geteuid();
675 return s.st_gid == getegid();
676 return 1; /* NOTREACHED */
680 static number_t nexpr(enum token n)
684 nest_msg(">nexpr(%s)\n", TOKSTR[n]);
686 n = check_operator(*++args);
688 /* special case: [ ! ], [ a -a ! ] are valid */
689 /* IOW, "! ARG" may miss ARG */
690 unnest_msg("<nexpr:1 (!EOI)\n");
694 unnest_msg("<nexpr:%lld\n", res);
698 unnest_msg("<nexpr:%lld\n", res);
703 static number_t aexpr(enum token n)
707 nest_msg(">aexpr(%s)\n", TOKSTR[n]);
709 dbg_msg("aexpr: nexpr:%lld, next args:%s\n", res, args[1]);
710 if (check_operator(*++args) == BAND) {
711 dbg_msg("aexpr: arg is AND, next args:%s\n", args[1]);
712 res = aexpr(check_operator(*++args)) && res;
713 unnest_msg("<aexpr:%lld\n", res);
717 unnest_msg("<aexpr:%lld, args:%s\n", res, args[0]);
722 static number_t oexpr(enum token n)
726 nest_msg(">oexpr(%s)\n", TOKSTR[n]);
728 dbg_msg("oexpr: aexpr:%lld, next args:%s\n", res, args[1]);
729 if (check_operator(*++args) == BOR) {
730 dbg_msg("oexpr: next arg is OR, next args:%s\n", args[1]);
731 res = oexpr(check_operator(*++args)) || res;
732 unnest_msg("<oexpr:%lld\n", res);
736 unnest_msg("<oexpr:%lld, args:%s\n", res, args[0]);
741 static number_t primary(enum token n)
744 number_t res = res; /* for compiler */
748 const struct operator_t *args0_op;
750 nest_msg(">primary(%s)\n", TOKSTR[n]);
752 syntax(NULL, "argument expected");
755 res = oexpr(check_operator(*++args));
756 if (check_operator(*++args) != RPAREN)
757 syntax(NULL, "closing paren expected");
758 unnest_msg("<primary:%lld\n", res);
762 /* coreutils 6.9 checks "is args[1] binop and args[2] exist?" first,
764 args0_op = last_operator;
765 /* last_operator = operator at args[1] */
766 if (check_operator(args[1]) != EOI) { /* if args[1] != NULL */
768 // coreutils also does this:
769 // if (args[3] && args[0]="-l" && args[2] is BINOP)
770 // return binop(1 /* prepended by -l */);
771 if (last_operator->op_type == BINOP)
772 unnest_msg_and_return(binop(), "<primary: binop:%lld\n");
775 /* check "is args[0] unop?" second */
776 if (args0_op->op_type == UNOP) {
777 /* unary expression */
779 // syntax(args0_op->op_text, "argument expected");
780 goto check_emptiness;
783 unnest_msg_and_return(args[0][0] == '\0', "<primary:%lld\n");
785 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
787 unnest_msg_and_return(isatty(getn(*args)), "<primary: isatty(%s)%lld\n", *args);
788 unnest_msg_and_return(filstat(*args, n), "<primary: filstat(%s):%lld\n", *args);
791 /*check_operator(args[1]); - already done */
792 if (last_operator->op_type == BINOP) {
793 /* args[2] is known to be NULL, isn't it bound to fail? */
794 unnest_msg_and_return(binop(), "<primary:%lld\n");
797 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
801 int test_main(int argc, char **argv)
807 arg0 = bb_basename(argv[0]);
808 if (arg0[0] == '[') {
810 if (!arg0[1]) { /* "[" ? */
811 if (NOT_LONE_CHAR(argv[argc], ']')) {
812 bb_error_msg("missing ]");
815 } else { /* assuming "[[" */
816 if (strcmp(argv[argc], "]]") != 0) {
817 bb_error_msg("missing ]]");
824 /* We must do DEINIT_S() prior to returning */
827 res = setjmp(leaving);
831 /* resetting ngroups is probably unnecessary. it will
832 * force a new call to getgroups(), which prevents using
833 * group data fetched during a previous call. but the
834 * only way the group data could be stale is if there's
835 * been an intervening call to setgroups(), and this
836 * isn't likely in the case of a shell. paranoia
839 /*ngroups = 0; - done by INIT_S() */
844 /* Implement special cases from POSIX.2, section 4.62.4 */
845 if (!argv[0]) { /* "test" */
850 // Now it's fixed in the parser and should not be needed
851 if (LONE_CHAR(argv[0], '!') && argv[1]) {
856 if (!argv[1]) { /* "test [!] arg" */
857 res = (*argv[0] == '\0');
860 if (argv[2] && !argv[3]) {
861 check_operator(argv[1]);
862 if (last_operator->op_type == BINOP) {
863 /* "test [!] arg1 <binary_op> arg2" */
865 res = (binop() == 0);
870 /* Some complex expression. Undo '!' removal */
878 res = !oexpr(check_operator(*args));
880 if (*args != NULL && *++args != NULL) {
881 /* TODO: example when this happens? */
882 bb_error_msg("%s: unknown operand", *args);
887 // return negate ? !res : res;