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.
42 /* "test --help" is special-cased to ignore --help */
43 //usage:#define test_trivial_usage NOUSAGE_STR
44 //usage:#define test_full_usage ""
46 //usage:#define test_example_usage
47 //usage: "$ test 1 -eq 2\n"
48 //usage: "$ echo $?\n"
50 //usage: "$ test 1 -eq 1\n"
51 //usage: "$ echo $?\n"
53 //usage: "$ [ -d /etc ]\n"
54 //usage: "$ echo $?\n"
56 //usage: "$ [ -d /junk ]\n"
57 //usage: "$ echo $?\n"
63 /* This is a NOFORK applet. Be very careful! */
65 /* test_main() is called from shells, and we need to be extra careful here.
66 * This is true regardless of PREFER_APPLETS and SH_STANDALONE
69 /* test(1) accepts the following grammar:
70 oexpr ::= aexpr | aexpr "-o" oexpr ;
71 aexpr ::= nexpr | nexpr "-a" aexpr ;
72 nexpr ::= primary | "!" primary
73 primary ::= unary-operator operand
74 | operand binary-operator operand
78 unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
79 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
81 binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
83 operand ::= <any legal UNIX file name>
86 /* TODO: handle [[ expr ]] bashism bash-compatibly.
87 * [[ ]] is meant to be a "better [ ]", with less weird syntax
88 * and without the risk of variables and quoted strings misinterpreted
90 * This will require support from shells - we need to know quote status
91 * of each parameter (see below).
93 * Word splitting and pathname expansion should NOT be performed:
94 * # a="a b"; [[ $a = "a b" ]] && echo YES
96 * # [[ /bin/m* ]] && echo YES
99 * =~ should do regexp match
100 * = and == should do pattern match against right side:
101 * # [[ *a* == bab ]] && echo YES
102 * # [[ bab == *a* ]] && echo YES
104 * != does the negated == (i.e., also with pattern matching).
105 * Pattern matching is quotation-sensitive:
106 * # [[ bab == "b"a* ]] && echo YES
108 * # [[ bab == b"a*" ]] && echo YES
110 * Conditional operators such as -f must be unquoted literals to be recognized:
111 * # [[ -e /bin ]] && echo YES
113 * # [[ '-e' /bin ]] && echo YES
114 * bash: conditional binary operator expected...
115 * # A='-e'; [[ $A /bin ]] && echo YES
116 * bash: conditional binary operator expected...
118 * || and && should work as -o and -a work in [ ]
119 * -a and -o aren't recognized (&& and || are to be used instead)
120 * ( and ) do not need to be quoted unlike in [ ]:
121 * # [[ ( abc ) && '' ]] && echo YES
122 * # [[ ( abc ) || '' ]] && echo YES
124 * # [[ ( abc ) -o '' ]] && echo YES
125 * bash: syntax error in conditional expression...
127 * Apart from the above, [[ expr ]] should work as [ expr ]
135 FILRD, /* file access */
141 FILREG, /* file type */
152 FILSUID, /* file bit */
156 FILNT, /* file ops */
184 #define is_int_op(a) (((unsigned char)((a) - INTEQ)) <= 5)
185 #define is_str_op(a) (((unsigned char)((a) - STREZ)) <= 5)
186 #define is_file_op(a) (((unsigned char)((a) - FILNT)) <= 2)
187 #define is_file_access(a) (((unsigned char)((a) - FILRD)) <= 2)
188 #define is_file_type(a) (((unsigned char)((a) - FILREG)) <= 5)
189 #define is_file_bit(a) (((unsigned char)((a) - FILSUID)) <= 2)
193 #define nest_msg(...) do { \
195 fprintf(stderr, "%*s", depth*2, ""); \
196 fprintf(stderr, __VA_ARGS__); \
198 #define unnest_msg(...) do { \
199 fprintf(stderr, "%*s", depth*2, ""); \
200 fprintf(stderr, __VA_ARGS__); \
203 #define dbg_msg(...) do { \
204 fprintf(stderr, "%*s", depth*2, ""); \
205 fprintf(stderr, __VA_ARGS__); \
207 #define unnest_msg_and_return(expr, ...) do { \
208 number_t __res = (expr); \
209 fprintf(stderr, "%*s", depth*2, ""); \
210 fprintf(stderr, __VA_ARGS__, res); \
214 static const char *const TOKSTR[] = {
257 #define nest_msg(...) ((void)0)
258 #define unnest_msg(...) ((void)0)
259 #define dbg_msg(...) ((void)0)
260 #define unnest_msg_and_return(expr, ...) return expr
272 unsigned char op_num, op_type;
275 static const struct operator_t ops_table[] = {
276 { /* "-r" */ FILRD , UNOP },
277 { /* "-w" */ FILWR , UNOP },
278 { /* "-x" */ FILEX , UNOP },
279 { /* "-e" */ FILEXIST, UNOP },
280 { /* "-f" */ FILREG , UNOP },
281 { /* "-d" */ FILDIR , UNOP },
282 { /* "-c" */ FILCDEV , UNOP },
283 { /* "-b" */ FILBDEV , UNOP },
284 { /* "-p" */ FILFIFO , UNOP },
285 { /* "-u" */ FILSUID , UNOP },
286 { /* "-g" */ FILSGID , UNOP },
287 { /* "-k" */ FILSTCK , UNOP },
288 { /* "-s" */ FILGZ , UNOP },
289 { /* "-t" */ FILTT , UNOP },
290 { /* "-z" */ STREZ , UNOP },
291 { /* "-n" */ STRNZ , UNOP },
292 { /* "-h" */ FILSYM , UNOP }, /* for backwards compat */
294 { /* "-O" */ FILUID , UNOP },
295 { /* "-G" */ FILGID , UNOP },
296 { /* "-L" */ FILSYM , UNOP },
297 { /* "-S" */ FILSOCK , UNOP },
298 { /* "=" */ STREQ , BINOP },
299 { /* "==" */ STREQ , BINOP },
300 { /* "!=" */ STRNE , BINOP },
301 { /* "<" */ STRLT , BINOP },
302 { /* ">" */ STRGT , BINOP },
303 { /* "-eq"*/ INTEQ , BINOP },
304 { /* "-ne"*/ INTNE , BINOP },
305 { /* "-ge"*/ INTGE , BINOP },
306 { /* "-gt"*/ INTGT , BINOP },
307 { /* "-le"*/ INTLE , BINOP },
308 { /* "-lt"*/ INTLT , BINOP },
309 { /* "-nt"*/ FILNT , BINOP },
310 { /* "-ot"*/ FILOT , BINOP },
311 { /* "-ef"*/ FILEQ , BINOP },
312 { /* "!" */ UNOT , BUNOP },
313 { /* "-a" */ BAND , BBINOP },
314 { /* "-o" */ BOR , BBINOP },
315 { /* "(" */ LPAREN , PAREN },
316 { /* ")" */ RPAREN , PAREN },
318 /* Please keep these two tables in sync */
319 static const char ops_texts[] ALIGN1 =
364 #if ENABLE_FEATURE_TEST_64
365 typedef int64_t number_t;
367 typedef int number_t;
371 /* We try to minimize both static and stack usage. */
372 struct test_statics {
374 /* set only by check_operator(), either to bogus struct
375 * or points to matching operator_t struct. Never NULL. */
376 const struct operator_t *last_operator;
382 /* See test_ptr_hack.c */
383 extern struct test_statics *const test_ptr_to_statics;
385 #define S (*test_ptr_to_statics)
386 #define args (S.args )
387 #define last_operator (S.last_operator)
388 #define group_array (S.group_array )
389 #define ngroups (S.ngroups )
390 #define leaving (S.leaving )
392 #define INIT_S() do { \
393 (*(struct test_statics**)&test_ptr_to_statics) = xzalloc(sizeof(S)); \
396 #define DEINIT_S() do { \
397 free(test_ptr_to_statics); \
400 static number_t primary(enum token n);
402 static void syntax(const char *op, const char *msg) NORETURN;
403 static void syntax(const char *op, const char *msg)
406 bb_error_msg("%s: %s", op, msg);
408 bb_error_msg("%s: %s"+4, msg);
413 /* atoi with error detection */
414 //XXX: FIXME: duplicate of existing libbb function?
415 static number_t getn(const char *s)
418 #if ENABLE_FEATURE_TEST_64
425 #if ENABLE_FEATURE_TEST_64
426 r = strtoll(s, &p, 10);
428 r = strtol(s, &p, 10);
432 syntax(s, "out of range");
434 if (p == s || *(skip_whitespace(p)) != '\0')
435 syntax(s, "bad number");
441 static int newerf(const char *f1, const char *f2)
445 return (stat(f1, &b1) == 0 &&
446 stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
449 static int olderf(const char *f1, const char *f2)
453 return (stat(f1, &b1) == 0 &&
454 stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
457 static int equalf(const char *f1, const char *f2)
461 return (stat(f1, &b1) == 0 &&
462 stat(f2, &b2) == 0 &&
463 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
468 static enum token check_operator(const char *s)
470 static const struct operator_t no_op = {
476 last_operator = &no_op;
479 n = index_in_strings(ops_texts, s);
482 last_operator = &ops_table[n];
483 return ops_table[n].op_num;
487 static int binop(void)
489 const char *opnd1, *opnd2;
490 const struct operator_t *op;
494 check_operator(*++args);
499 syntax(args[-1], "argument expected");
501 if (is_int_op(op->op_num)) {
504 if (op->op_num == INTEQ)
506 if (op->op_num == INTNE)
508 if (op->op_num == INTGE)
510 if (op->op_num == INTGT)
512 if (op->op_num == INTLE)
514 /*if (op->op_num == INTLT)*/
517 if (is_str_op(op->op_num)) {
518 val1 = strcmp(opnd1, opnd2);
519 if (op->op_num == STREQ)
521 if (op->op_num == STRNE)
523 if (op->op_num == STRLT)
525 /*if (op->op_num == STRGT)*/
528 /* We are sure that these three are by now the only binops we didn't check
529 * yet, so we do not check if the class is correct:
531 /* if (is_file_op(op->op_num)) */
535 if (stat(opnd1, &b1) || stat(opnd2, &b2))
536 return 0; /* false, since at least one stat failed */
537 if (op->op_num == FILNT)
538 return b1.st_mtime > b2.st_mtime;
539 if (op->op_num == FILOT)
540 return b1.st_mtime < b2.st_mtime;
541 /*if (op->op_num == FILEQ)*/
542 return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
544 /*return 1; - NOTREACHED */
548 static void initialize_group_array(void)
552 /* getgroups may be expensive, try to use it only once */
555 /* FIXME: ash tries so hard to not die on OOM,
556 * and we spoil it with just one xrealloc here */
557 /* We realloc, because test_main can be entered repeatedly by shell.
558 * Testcase (ash): 'while true; do test -x some_file; done'
559 * and watch top. (some_file must have owner != you) */
561 group_array = xrealloc(group_array, n * sizeof(gid_t));
562 ngroups = getgroups(n, group_array);
563 } while (ngroups > n);
567 /* Return non-zero if GID is one that we have in our groups list. */
568 //XXX: FIXME: duplicate of existing libbb function?
569 // see toplevel TODO file:
570 // possible code duplication ingroup() and is_a_group_member()
571 static int is_a_group_member(gid_t gid)
575 /* Short-circuit if possible, maybe saving a call to getgroups(). */
576 if (gid == getgid() || gid == getegid())
580 initialize_group_array();
582 /* Search through the list looking for GID. */
583 for (i = 0; i < ngroups; i++)
584 if (gid == group_array[i])
591 /* Do the same thing access(2) does, but use the effective uid and gid,
592 and don't make the mistake of telling root that any file is
594 static int test_eaccess(char *path, int mode)
597 unsigned int euid = geteuid();
599 if (stat(path, &st) < 0)
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(nm, 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 (arg0[0] == '[') {
828 if (!arg0[1]) { /* "[" ? */
829 if (NOT_LONE_CHAR(argv[argc], ']')) {
830 bb_error_msg("missing ]");
833 } else { /* assuming "[[" */
834 if (strcmp(argv[argc], "]]") != 0) {
835 bb_error_msg("missing ]]");
841 /* argc is unused after this point */
843 /* We must do DEINIT_S() prior to returning */
846 res = setjmp(leaving);
850 /* resetting ngroups is probably unnecessary. it will
851 * force a new call to getgroups(), which prevents using
852 * group data fetched during a previous call. but the
853 * only way the group data could be stale is if there's
854 * been an intervening call to setgroups(), and this
855 * isn't likely in the case of a shell. paranoia
858 /*ngroups = 0; - done by INIT_S() */
863 /* Implement special cases from POSIX.2, section 4.62.4.
864 * Testcase: "test '(' = '('"
865 * The general parser would misinterpret '(' as group start.
877 res = (argv[0][0] == '\0');
880 if (argv[2] && !argv[3]) {
881 check_operator(argv[1]);
882 if (last_operator->op_type == BINOP) {
883 /* "test [!] arg1 <binary_op> arg2" */
885 res = (binop() == 0);
887 /* If there was leading "!" op... */
892 if (LONE_CHAR(argv[0], '!')) {
899 res = !oexpr(check_operator(*args));
901 if (*args != NULL && *++args != NULL) {
906 bb_error_msg("%s: unknown operand", *args);