test.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * test implementation for busybox
  4. *
  5. * Copyright (c) by a whole pile of folks:
  6. *
  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
  14. * in busybox.
  15. * modified by Bernhard Reutner-Fischer to be useable (i.e. a bit less bloaty).
  16. *
  17. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  18. *
  19. * Original copyright notice states:
  20. * "This program is in the Public Domain."
  21. */
  22. //config:config TEST
  23. //config: bool "test (3.6 kb)"
  24. //config: default y
  25. //config: help
  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.
  29. //config:
  30. //config:config TEST1
  31. //config: bool "test as ["
  32. //config: default y
  33. //config: help
  34. //config: Provide test command in the "[ EXPR ]" form
  35. //config:
  36. //config:config TEST2
  37. //config: bool "test as [["
  38. //config: default y
  39. //config: help
  40. //config: Provide test command in the "[[ EXPR ]]" form
  41. //config:
  42. //config:config FEATURE_TEST_64
  43. //config: bool "Extend test to 64 bit"
  44. //config: default y
  45. //config: depends on TEST || TEST1 || TEST2 || ASH_TEST || HUSH_TEST
  46. //config: help
  47. //config: Enable 64-bit support in test.
  48. //applet:IF_TEST(APPLET_NOFORK(test, test, BB_DIR_USR_BIN, BB_SUID_DROP, test))
  49. //applet:IF_TEST1(APPLET_NOFORK([, test, BB_DIR_USR_BIN, BB_SUID_DROP, test))
  50. //applet:IF_TEST2(APPLET_NOFORK([[, test, BB_DIR_USR_BIN, BB_SUID_DROP, test))
  51. //kbuild:lib-$(CONFIG_TEST) += test.o test_ptr_hack.o
  52. //kbuild:lib-$(CONFIG_TEST1) += test.o test_ptr_hack.o
  53. //kbuild:lib-$(CONFIG_TEST2) += test.o test_ptr_hack.o
  54. //kbuild:lib-$(CONFIG_ASH_TEST) += test.o test_ptr_hack.o
  55. //kbuild:lib-$(CONFIG_HUSH_TEST) += test.o test_ptr_hack.o
  56. /* "test --help" is special-cased to ignore --help */
  57. //usage:#define test_trivial_usage NOUSAGE_STR
  58. //usage:#define test_full_usage ""
  59. //usage:
  60. //usage:#define test_example_usage
  61. //usage: "$ test 1 -eq 2\n"
  62. //usage: "$ echo $?\n"
  63. //usage: "1\n"
  64. //usage: "$ test 1 -eq 1\n"
  65. //usage: "$ echo $?\n"
  66. //usage: "0\n"
  67. //usage: "$ [ -d /etc ]\n"
  68. //usage: "$ echo $?\n"
  69. //usage: "0\n"
  70. //usage: "$ [ -d /junk ]\n"
  71. //usage: "$ echo $?\n"
  72. //usage: "1\n"
  73. #include "libbb.h"
  74. #include <setjmp.h>
  75. /* This is a NOFORK applet. Be very careful! */
  76. /* test_main() is called from shells, and we need to be extra careful here.
  77. * This is true regardless of PREFER_APPLETS and SH_STANDALONE
  78. * state. */
  79. /* test(1) accepts the following grammar:
  80. oexpr ::= aexpr | aexpr "-o" oexpr ;
  81. aexpr ::= nexpr | nexpr "-a" aexpr ;
  82. nexpr ::= primary | "!" primary
  83. primary ::= unary-operator operand
  84. | operand binary-operator operand
  85. | operand
  86. | "(" oexpr ")"
  87. ;
  88. unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
  89. "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
  90. binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
  91. "-nt"|"-ot"|"-ef";
  92. operand ::= <any legal UNIX file name>
  93. */
  94. /* TODO: handle [[ expr ]] bashism bash-compatibly.
  95. * [[ ]] is meant to be a "better [ ]", with less weird syntax
  96. * and without the risk of variables and quoted strings misinterpreted
  97. * as operators.
  98. * This will require support from shells - we need to know quote status
  99. * of each parameter (see below).
  100. *
  101. * Word splitting and pathname expansion should NOT be performed:
  102. * # a="a b"; [[ $a = "a b" ]] && echo YES
  103. * YES
  104. * # [[ /bin/m* ]] && echo YES
  105. * YES
  106. *
  107. * =~ should do regexp match
  108. * = and == should do pattern match against right side:
  109. * # [[ *a* == bab ]] && echo YES
  110. * # [[ bab == *a* ]] && echo YES
  111. * YES
  112. * != does the negated == (i.e., also with pattern matching).
  113. * Pattern matching is quotation-sensitive:
  114. * # [[ bab == "b"a* ]] && echo YES
  115. * YES
  116. * # [[ bab == b"a*" ]] && echo YES
  117. *
  118. * Conditional operators such as -f must be unquoted literals to be recognized:
  119. * # [[ -e /bin ]] && echo YES
  120. * YES
  121. * # [[ '-e' /bin ]] && echo YES
  122. * bash: conditional binary operator expected...
  123. * # A='-e'; [[ $A /bin ]] && echo YES
  124. * bash: conditional binary operator expected...
  125. *
  126. * || and && should work as -o and -a work in [ ]
  127. * -a and -o aren't recognized (&& and || are to be used instead)
  128. * ( and ) do not need to be quoted unlike in [ ]:
  129. * # [[ ( abc ) && '' ]] && echo YES
  130. * # [[ ( abc ) || '' ]] && echo YES
  131. * YES
  132. * # [[ ( abc ) -o '' ]] && echo YES
  133. * bash: syntax error in conditional expression...
  134. *
  135. * Apart from the above, [[ expr ]] should work as [ expr ]
  136. */
  137. #define TEST_DEBUG 0
  138. enum token {
  139. EOI,
  140. FILRD, /* file access */
  141. FILWR,
  142. FILEX,
  143. FILEXIST,
  144. FILREG, /* file type */
  145. FILDIR,
  146. FILCDEV,
  147. FILBDEV,
  148. FILFIFO,
  149. FILSOCK,
  150. FILSYM,
  151. FILGZ,
  152. FILTT,
  153. FILSUID, /* file bit */
  154. FILSGID,
  155. FILSTCK,
  156. FILNT, /* file ops */
  157. FILOT,
  158. FILEQ,
  159. FILUID,
  160. FILGID,
  161. STREZ, /* str ops */
  162. STRNZ,
  163. STREQ,
  164. STRNE,
  165. STRLT,
  166. STRGT,
  167. INTEQ, /* int ops */
  168. INTNE,
  169. INTGE,
  170. INTGT,
  171. INTLE,
  172. INTLT,
  173. UNOT,
  174. BAND,
  175. BOR,
  176. LPAREN,
  177. RPAREN,
  178. OPERAND
  179. };
  180. #define is_int_op(a) (((unsigned char)((a) - INTEQ)) <= 5)
  181. #define is_str_op(a) (((unsigned char)((a) - STREZ)) <= 5)
  182. #define is_file_op(a) (((unsigned char)((a) - FILNT)) <= 2)
  183. #define is_file_access(a) (((unsigned char)((a) - FILRD)) <= 2)
  184. #define is_file_type(a) (((unsigned char)((a) - FILREG)) <= 5)
  185. #define is_file_bit(a) (((unsigned char)((a) - FILSUID)) <= 2)
  186. #if TEST_DEBUG
  187. int depth;
  188. #define nest_msg(...) do { \
  189. depth++; \
  190. fprintf(stderr, "%*s", depth*2, ""); \
  191. fprintf(stderr, __VA_ARGS__); \
  192. } while (0)
  193. #define unnest_msg(...) do { \
  194. fprintf(stderr, "%*s", depth*2, ""); \
  195. fprintf(stderr, __VA_ARGS__); \
  196. depth--; \
  197. } while (0)
  198. #define dbg_msg(...) do { \
  199. fprintf(stderr, "%*s", depth*2, ""); \
  200. fprintf(stderr, __VA_ARGS__); \
  201. } while (0)
  202. #define unnest_msg_and_return(expr, ...) do { \
  203. number_t __res = (expr); \
  204. fprintf(stderr, "%*s", depth*2, ""); \
  205. fprintf(stderr, __VA_ARGS__, res); \
  206. depth--; \
  207. return __res; \
  208. } while (0)
  209. static const char *const TOKSTR[] = {
  210. "EOI",
  211. "FILRD",
  212. "FILWR",
  213. "FILEX",
  214. "FILEXIST",
  215. "FILREG",
  216. "FILDIR",
  217. "FILCDEV",
  218. "FILBDEV",
  219. "FILFIFO",
  220. "FILSOCK",
  221. "FILSYM",
  222. "FILGZ",
  223. "FILTT",
  224. "FILSUID",
  225. "FILSGID",
  226. "FILSTCK",
  227. "FILNT",
  228. "FILOT",
  229. "FILEQ",
  230. "FILUID",
  231. "FILGID",
  232. "STREZ",
  233. "STRNZ",
  234. "STREQ",
  235. "STRNE",
  236. "STRLT",
  237. "STRGT",
  238. "INTEQ",
  239. "INTNE",
  240. "INTGE",
  241. "INTGT",
  242. "INTLE",
  243. "INTLT",
  244. "UNOT",
  245. "BAND",
  246. "BOR",
  247. "LPAREN",
  248. "RPAREN",
  249. "OPERAND"
  250. };
  251. #else
  252. #define nest_msg(...) ((void)0)
  253. #define unnest_msg(...) ((void)0)
  254. #define dbg_msg(...) ((void)0)
  255. #define unnest_msg_and_return(expr, ...) return expr
  256. #endif
  257. enum {
  258. UNOP,
  259. BINOP,
  260. BUNOP,
  261. BBINOP,
  262. PAREN
  263. };
  264. struct operator_t {
  265. unsigned char op_num, op_type;
  266. };
  267. static const struct operator_t ops_table[] = {
  268. { /* "-r" */ FILRD , UNOP },
  269. { /* "-w" */ FILWR , UNOP },
  270. { /* "-x" */ FILEX , UNOP },
  271. { /* "-e" */ FILEXIST, UNOP },
  272. { /* "-f" */ FILREG , UNOP },
  273. { /* "-d" */ FILDIR , UNOP },
  274. { /* "-c" */ FILCDEV , UNOP },
  275. { /* "-b" */ FILBDEV , UNOP },
  276. { /* "-p" */ FILFIFO , UNOP },
  277. { /* "-u" */ FILSUID , UNOP },
  278. { /* "-g" */ FILSGID , UNOP },
  279. { /* "-k" */ FILSTCK , UNOP },
  280. { /* "-s" */ FILGZ , UNOP },
  281. { /* "-t" */ FILTT , UNOP },
  282. { /* "-z" */ STREZ , UNOP },
  283. { /* "-n" */ STRNZ , UNOP },
  284. { /* "-h" */ FILSYM , UNOP }, /* for backwards compat */
  285. { /* "-O" */ FILUID , UNOP },
  286. { /* "-G" */ FILGID , UNOP },
  287. { /* "-L" */ FILSYM , UNOP },
  288. { /* "-S" */ FILSOCK , UNOP },
  289. { /* "=" */ STREQ , BINOP },
  290. { /* "==" */ STREQ , BINOP },
  291. { /* "!=" */ STRNE , BINOP },
  292. { /* "<" */ STRLT , BINOP },
  293. { /* ">" */ STRGT , BINOP },
  294. { /* "-eq"*/ INTEQ , BINOP },
  295. { /* "-ne"*/ INTNE , BINOP },
  296. { /* "-ge"*/ INTGE , BINOP },
  297. { /* "-gt"*/ INTGT , BINOP },
  298. { /* "-le"*/ INTLE , BINOP },
  299. { /* "-lt"*/ INTLT , BINOP },
  300. { /* "-nt"*/ FILNT , BINOP },
  301. { /* "-ot"*/ FILOT , BINOP },
  302. { /* "-ef"*/ FILEQ , BINOP },
  303. { /* "!" */ UNOT , BUNOP },
  304. { /* "-a" */ BAND , BBINOP },
  305. { /* "-o" */ BOR , BBINOP },
  306. { /* "(" */ LPAREN , PAREN },
  307. { /* ")" */ RPAREN , PAREN },
  308. };
  309. /* Please keep these two tables in sync */
  310. static const char ops_texts[] ALIGN1 =
  311. "-r" "\0"
  312. "-w" "\0"
  313. "-x" "\0"
  314. "-e" "\0"
  315. "-f" "\0"
  316. "-d" "\0"
  317. "-c" "\0"
  318. "-b" "\0"
  319. "-p" "\0"
  320. "-u" "\0"
  321. "-g" "\0"
  322. "-k" "\0"
  323. "-s" "\0"
  324. "-t" "\0"
  325. "-z" "\0"
  326. "-n" "\0"
  327. "-h" "\0"
  328. "-O" "\0"
  329. "-G" "\0"
  330. "-L" "\0"
  331. "-S" "\0"
  332. "=" "\0"
  333. "==" "\0"
  334. "!=" "\0"
  335. "<" "\0"
  336. ">" "\0"
  337. "-eq" "\0"
  338. "-ne" "\0"
  339. "-ge" "\0"
  340. "-gt" "\0"
  341. "-le" "\0"
  342. "-lt" "\0"
  343. "-nt" "\0"
  344. "-ot" "\0"
  345. "-ef" "\0"
  346. "!" "\0"
  347. "-a" "\0"
  348. "-o" "\0"
  349. "(" "\0"
  350. ")" "\0"
  351. ;
  352. #if ENABLE_FEATURE_TEST_64
  353. typedef int64_t number_t;
  354. #else
  355. typedef int number_t;
  356. #endif
  357. /* We try to minimize both static and stack usage. */
  358. struct test_statics {
  359. char **args;
  360. /* set only by check_operator(), either to bogus struct
  361. * or points to matching operator_t struct. Never NULL. */
  362. const struct operator_t *last_operator;
  363. gid_t *group_array;
  364. int ngroups;
  365. jmp_buf leaving;
  366. };
  367. /* See test_ptr_hack.c */
  368. extern struct test_statics *const test_ptr_to_statics;
  369. #define S (*test_ptr_to_statics)
  370. #define args (S.args )
  371. #define last_operator (S.last_operator)
  372. #define group_array (S.group_array )
  373. #define ngroups (S.ngroups )
  374. #define leaving (S.leaving )
  375. #define INIT_S() do { \
  376. (*(struct test_statics**)&test_ptr_to_statics) = xzalloc(sizeof(S)); \
  377. barrier(); \
  378. } while (0)
  379. #define DEINIT_S() do { \
  380. free(group_array); \
  381. free(test_ptr_to_statics); \
  382. } while (0)
  383. 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)
  386. {
  387. if (op && *op) {
  388. bb_error_msg("%s: %s", op, msg);
  389. } else {
  390. bb_error_msg("%s: %s"+4, msg);
  391. }
  392. longjmp(leaving, 2);
  393. }
  394. /* atoi with error detection */
  395. //XXX: FIXME: duplicate of existing libbb function?
  396. static number_t getn(const char *s)
  397. {
  398. char *p;
  399. #if ENABLE_FEATURE_TEST_64
  400. long long r;
  401. #else
  402. long r;
  403. #endif
  404. errno = 0;
  405. #if ENABLE_FEATURE_TEST_64
  406. r = strtoll(s, &p, 10);
  407. #else
  408. r = strtol(s, &p, 10);
  409. #endif
  410. if (errno != 0)
  411. syntax(s, "out of range");
  412. if (p == s || *(skip_whitespace(p)) != '\0')
  413. syntax(s, "bad number");
  414. return r;
  415. }
  416. /* UNUSED
  417. static int newerf(const char *f1, const char *f2)
  418. {
  419. struct stat b1, b2;
  420. return (stat(f1, &b1) == 0 &&
  421. stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
  422. }
  423. static int olderf(const char *f1, const char *f2)
  424. {
  425. struct stat b1, b2;
  426. return (stat(f1, &b1) == 0 &&
  427. stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
  428. }
  429. static int equalf(const char *f1, const char *f2)
  430. {
  431. struct stat b1, b2;
  432. return (stat(f1, &b1) == 0 &&
  433. stat(f2, &b2) == 0 &&
  434. b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
  435. }
  436. */
  437. static enum token check_operator(const char *s)
  438. {
  439. static const struct operator_t no_op = {
  440. .op_num = -1,
  441. .op_type = -1
  442. };
  443. int n;
  444. last_operator = &no_op;
  445. if (s == NULL)
  446. return EOI;
  447. n = index_in_strings(ops_texts, s);
  448. if (n < 0)
  449. return OPERAND;
  450. last_operator = &ops_table[n];
  451. return ops_table[n].op_num;
  452. }
  453. static int binop(void)
  454. {
  455. const char *opnd1, *opnd2;
  456. const struct operator_t *op;
  457. number_t val1, val2;
  458. opnd1 = *args;
  459. check_operator(*++args);
  460. op = last_operator;
  461. opnd2 = *++args;
  462. if (opnd2 == NULL)
  463. syntax(args[-1], "argument expected");
  464. if (is_int_op(op->op_num)) {
  465. val1 = getn(opnd1);
  466. val2 = getn(opnd2);
  467. if (op->op_num == INTEQ)
  468. return val1 == val2;
  469. if (op->op_num == INTNE)
  470. return val1 != val2;
  471. if (op->op_num == INTGE)
  472. return val1 >= val2;
  473. if (op->op_num == INTGT)
  474. return val1 > val2;
  475. if (op->op_num == INTLE)
  476. return val1 <= val2;
  477. /*if (op->op_num == INTLT)*/
  478. return val1 < val2;
  479. }
  480. if (is_str_op(op->op_num)) {
  481. val1 = strcmp(opnd1, opnd2);
  482. if (op->op_num == STREQ)
  483. return val1 == 0;
  484. if (op->op_num == STRNE)
  485. return val1 != 0;
  486. if (op->op_num == STRLT)
  487. return val1 < 0;
  488. /*if (op->op_num == STRGT)*/
  489. return val1 > 0;
  490. }
  491. /* We are sure that these three are by now the only binops we didn't check
  492. * yet, so we do not check if the class is correct:
  493. */
  494. /* if (is_file_op(op->op_num)) */
  495. {
  496. struct stat b1, b2;
  497. if (stat(opnd1, &b1) || stat(opnd2, &b2))
  498. return 0; /* false, since at least one stat failed */
  499. if (op->op_num == FILNT)
  500. return b1.st_mtime > b2.st_mtime;
  501. if (op->op_num == FILOT)
  502. return b1.st_mtime < b2.st_mtime;
  503. /*if (op->op_num == FILEQ)*/
  504. return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
  505. }
  506. /*return 1; - NOTREACHED */
  507. }
  508. static void initialize_group_array(void)
  509. {
  510. group_array = bb_getgroups(&ngroups, NULL);
  511. }
  512. /* Return non-zero if GID is one that we have in our groups list. */
  513. //XXX: FIXME: duplicate of existing libbb function?
  514. // see toplevel TODO file:
  515. // possible code duplication ingroup() and is_a_group_member()
  516. static int is_a_group_member(gid_t gid)
  517. {
  518. int i;
  519. /* Short-circuit if possible, maybe saving a call to getgroups(). */
  520. if (gid == getgid() || gid == getegid())
  521. return 1;
  522. if (ngroups == 0)
  523. initialize_group_array();
  524. /* Search through the list looking for GID. */
  525. for (i = 0; i < ngroups; i++)
  526. if (gid == group_array[i])
  527. return 1;
  528. return 0;
  529. }
  530. /* Do the same thing access(2) does, but use the effective uid and gid,
  531. and don't make the mistake of telling root that any file is
  532. executable. */
  533. static int test_eaccess(struct stat *st, int mode)
  534. {
  535. unsigned int euid = geteuid();
  536. if (euid == 0) {
  537. /* Root can read or write any file. */
  538. if (mode != X_OK)
  539. return 0;
  540. /* Root can execute any file that has any one of the execute
  541. * bits set. */
  542. if (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
  543. return 0;
  544. }
  545. if (st->st_uid == euid) /* owner */
  546. mode <<= 6;
  547. else if (is_a_group_member(st->st_gid))
  548. mode <<= 3;
  549. if (st->st_mode & mode)
  550. return 0;
  551. return -1;
  552. }
  553. static int filstat(char *nm, enum token mode)
  554. {
  555. struct stat s;
  556. unsigned i = i; /* gcc 3.x thinks it can be used uninitialized */
  557. if (mode == FILSYM) {
  558. #ifdef S_IFLNK
  559. if (lstat(nm, &s) == 0) {
  560. i = S_IFLNK;
  561. goto filetype;
  562. }
  563. #endif
  564. return 0;
  565. }
  566. if (stat(nm, &s) != 0)
  567. return 0;
  568. if (mode == FILEXIST)
  569. return 1;
  570. if (is_file_access(mode)) {
  571. if (mode == FILRD)
  572. i = R_OK;
  573. if (mode == FILWR)
  574. i = W_OK;
  575. if (mode == FILEX)
  576. i = X_OK;
  577. return test_eaccess(&s, i) == 0;
  578. }
  579. if (is_file_type(mode)) {
  580. if (mode == FILREG)
  581. i = S_IFREG;
  582. if (mode == FILDIR)
  583. i = S_IFDIR;
  584. if (mode == FILCDEV)
  585. i = S_IFCHR;
  586. if (mode == FILBDEV)
  587. i = S_IFBLK;
  588. if (mode == FILFIFO) {
  589. #ifdef S_IFIFO
  590. i = S_IFIFO;
  591. #else
  592. return 0;
  593. #endif
  594. }
  595. if (mode == FILSOCK) {
  596. #ifdef S_IFSOCK
  597. i = S_IFSOCK;
  598. #else
  599. return 0;
  600. #endif
  601. }
  602. filetype:
  603. return ((s.st_mode & S_IFMT) == i);
  604. }
  605. if (is_file_bit(mode)) {
  606. if (mode == FILSUID)
  607. i = S_ISUID;
  608. if (mode == FILSGID)
  609. i = S_ISGID;
  610. if (mode == FILSTCK)
  611. i = S_ISVTX;
  612. return ((s.st_mode & i) != 0);
  613. }
  614. if (mode == FILGZ)
  615. return s.st_size > 0L;
  616. if (mode == FILUID)
  617. return s.st_uid == geteuid();
  618. if (mode == FILGID)
  619. return s.st_gid == getegid();
  620. return 1; /* NOTREACHED */
  621. }
  622. static number_t nexpr(enum token n)
  623. {
  624. number_t res;
  625. nest_msg(">nexpr(%s)\n", TOKSTR[n]);
  626. if (n == UNOT) {
  627. n = check_operator(*++args);
  628. if (n == EOI) {
  629. /* special case: [ ! ], [ a -a ! ] are valid */
  630. /* IOW, "! ARG" may miss ARG */
  631. args--;
  632. unnest_msg("<nexpr:1 (!EOI), args:%s(%p)\n", args[0], &args[0]);
  633. return 1;
  634. }
  635. res = !nexpr(n);
  636. unnest_msg("<nexpr:%lld\n", res);
  637. return res;
  638. }
  639. res = primary(n);
  640. unnest_msg("<nexpr:%lld\n", res);
  641. return res;
  642. }
  643. static number_t aexpr(enum token n)
  644. {
  645. number_t res;
  646. nest_msg(">aexpr(%s)\n", TOKSTR[n]);
  647. res = nexpr(n);
  648. dbg_msg("aexpr: nexpr:%lld, next args:%s(%p)\n", res, args[1], &args[1]);
  649. if (check_operator(*++args) == BAND) {
  650. dbg_msg("aexpr: arg is AND, next args:%s(%p)\n", args[1], &args[1]);
  651. res = aexpr(check_operator(*++args)) && res;
  652. unnest_msg("<aexpr:%lld\n", res);
  653. return res;
  654. }
  655. args--;
  656. unnest_msg("<aexpr:%lld, args:%s(%p)\n", res, args[0], &args[0]);
  657. return res;
  658. }
  659. static number_t oexpr(enum token n)
  660. {
  661. number_t res;
  662. nest_msg(">oexpr(%s)\n", TOKSTR[n]);
  663. res = aexpr(n);
  664. dbg_msg("oexpr: aexpr:%lld, next args:%s(%p)\n", res, args[1], &args[1]);
  665. if (check_operator(*++args) == BOR) {
  666. dbg_msg("oexpr: next arg is OR, next args:%s(%p)\n", args[1], &args[1]);
  667. res = oexpr(check_operator(*++args)) || res;
  668. unnest_msg("<oexpr:%lld\n", res);
  669. return res;
  670. }
  671. args--;
  672. unnest_msg("<oexpr:%lld, args:%s(%p)\n", res, args[0], &args[0]);
  673. return res;
  674. }
  675. static number_t primary(enum token n)
  676. {
  677. #if TEST_DEBUG
  678. number_t res = res; /* for compiler */
  679. #else
  680. number_t res;
  681. #endif
  682. const struct operator_t *args0_op;
  683. nest_msg(">primary(%s)\n", TOKSTR[n]);
  684. if (n == EOI) {
  685. syntax(NULL, "argument expected");
  686. }
  687. if (n == LPAREN) {
  688. res = oexpr(check_operator(*++args));
  689. if (check_operator(*++args) != RPAREN)
  690. syntax(NULL, "closing paren expected");
  691. unnest_msg("<primary:%lld\n", res);
  692. return res;
  693. }
  694. /* coreutils 6.9 checks "is args[1] binop and args[2] exist?" first,
  695. * do the same */
  696. args0_op = last_operator;
  697. /* last_operator = operator at args[1] */
  698. if (check_operator(args[1]) != EOI) { /* if args[1] != NULL */
  699. if (args[2]) {
  700. // coreutils also does this:
  701. // if (args[3] && args[0]="-l" && args[2] is BINOP)
  702. // return binop(1 /* prepended by -l */);
  703. if (last_operator->op_type == BINOP)
  704. unnest_msg_and_return(binop(), "<primary: binop:%lld\n");
  705. }
  706. }
  707. /* check "is args[0] unop?" second */
  708. if (args0_op->op_type == UNOP) {
  709. /* unary expression */
  710. if (args[1] == NULL)
  711. // syntax(args0_op->op_text, "argument expected");
  712. goto check_emptiness;
  713. args++;
  714. if (n == STREZ)
  715. unnest_msg_and_return(args[0][0] == '\0', "<primary:%lld\n");
  716. if (n == STRNZ)
  717. unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
  718. if (n == FILTT)
  719. unnest_msg_and_return(isatty(getn(*args)), "<primary: isatty(%s)%lld\n", *args);
  720. unnest_msg_and_return(filstat(*args, n), "<primary: filstat(%s):%lld\n", *args);
  721. }
  722. /*check_operator(args[1]); - already done */
  723. if (last_operator->op_type == BINOP) {
  724. /* args[2] is known to be NULL, isn't it bound to fail? */
  725. unnest_msg_and_return(binop(), "<primary:%lld\n");
  726. }
  727. check_emptiness:
  728. unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
  729. }
  730. int test_main(int argc, char **argv)
  731. {
  732. int res;
  733. const char *arg0;
  734. arg0 = bb_basename(argv[0]);
  735. if ((ENABLE_TEST1 || ENABLE_TEST2 || ENABLE_ASH_TEST || ENABLE_HUSH_TEST)
  736. && (arg0[0] == '[')
  737. ) {
  738. --argc;
  739. if (!arg0[1]) { /* "[" ? */
  740. if (NOT_LONE_CHAR(argv[argc], ']')) {
  741. bb_error_msg("missing ]");
  742. return 2;
  743. }
  744. } else { /* assuming "[[" */
  745. if (strcmp(argv[argc], "]]") != 0) {
  746. bb_error_msg("missing ]]");
  747. return 2;
  748. }
  749. }
  750. argv[argc] = NULL;
  751. }
  752. /* argc is unused after this point */
  753. /* We must do DEINIT_S() prior to returning */
  754. INIT_S();
  755. res = setjmp(leaving);
  756. if (res)
  757. goto ret;
  758. /* resetting ngroups is probably unnecessary. it will
  759. * force a new call to getgroups(), which prevents using
  760. * group data fetched during a previous call. but the
  761. * only way the group data could be stale is if there's
  762. * been an intervening call to setgroups(), and this
  763. * isn't likely in the case of a shell. paranoia
  764. * prevails...
  765. */
  766. /*ngroups = 0; - done by INIT_S() */
  767. argv++;
  768. args = argv;
  769. /* Implement special cases from POSIX.2, section 4.62.4.
  770. * Testcase: "test '(' = '('"
  771. * The general parser would misinterpret '(' as group start.
  772. */
  773. if (1) {
  774. int negate = 0;
  775. again:
  776. if (!argv[0]) {
  777. /* "test" */
  778. res = 1;
  779. goto ret_special;
  780. }
  781. if (!argv[1]) {
  782. /* "test [!] arg" */
  783. res = (argv[0][0] == '\0');
  784. goto ret_special;
  785. }
  786. if (argv[2]) {
  787. if (!argv[3]) {
  788. /*
  789. * http://pubs.opengroup.org/onlinepubs/009695399/utilities/test.html
  790. * """ 3 arguments:
  791. * If $2 is a binary primary, perform the binary test of $1 and $3.
  792. * """
  793. */
  794. check_operator(argv[1]);
  795. if (last_operator->op_type == BINOP) {
  796. /* "test [!] arg1 <binary_op> arg2" */
  797. args = argv;
  798. res = (binop() == 0);
  799. ret_special:
  800. /* If there was leading "!" op... */
  801. res ^= negate;
  802. goto ret;
  803. }
  804. /* """If $1 is '(' and $3 is ')', perform the unary test of $2."""
  805. * Looks like this works without additional coding.
  806. */
  807. goto check_negate;
  808. }
  809. /* argv[3] exists (at least 4 args), is it exactly 4 args? */
  810. if (!argv[4]) {
  811. /*
  812. * """ 4 arguments:
  813. * If $1 is '!', negate the three-argument test of $2, $3, and $4.
  814. * If $1 is '(' and $4 is ')', perform the two-argument test of $2 and $3.
  815. * """
  816. * Example why code below is necessary: test '(' ! -e ')'
  817. */
  818. if (LONE_CHAR(argv[0], '(')
  819. && LONE_CHAR(argv[3], ')')
  820. ) {
  821. /* "test [!] ( x y )" */
  822. argv[3] = NULL;
  823. argv++;
  824. }
  825. }
  826. }
  827. check_negate:
  828. if (LONE_CHAR(argv[0], '!')) {
  829. argv++;
  830. negate ^= 1;
  831. goto again;
  832. }
  833. }
  834. res = !oexpr(check_operator(*args));
  835. if (*args != NULL && *++args != NULL) {
  836. /* Examples:
  837. * test 3 -lt 5 6
  838. * test -t 1 2
  839. */
  840. bb_error_msg("%s: unknown operand", *args);
  841. res = 2;
  842. }
  843. ret:
  844. DEINIT_S();
  845. return res;
  846. }