grep.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini grep implementation for busybox using libc regex.
  4. *
  5. * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
  6. * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
  7. *
  8. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  9. */
  10. /* BB_AUDIT SUSv3 defects - unsupported option -x. */
  11. /* BB_AUDIT GNU defects - always acts as -a. */
  12. /* http://www.opengroup.org/onlinepubs/007904975/utilities/grep.html */
  13. /*
  14. * 2004,2006 (C) Vladimir Oleynik <dzo@simtreas.ru> -
  15. * correction "-e pattern1 -e pattern2" logic and more optimizations.
  16. * precompiled regex
  17. */
  18. /*
  19. * (C) 2006 Jac Goudsmit added -o option
  20. */
  21. #include "busybox.h"
  22. #include "xregex.h"
  23. /* options */
  24. #define GREP_OPTS "lnqvscFiHhe:f:Lor"
  25. #define GREP_OPT_l (1<<0)
  26. #define PRINT_FILES_WITH_MATCHES (option_mask32 & GREP_OPT_l)
  27. #define GREP_OPT_n (1<<1)
  28. #define PRINT_LINE_NUM (option_mask32 & GREP_OPT_n)
  29. #define GREP_OPT_q (1<<2)
  30. #define BE_QUIET (option_mask32 & GREP_OPT_q)
  31. #define GREP_OPT_v (1<<3)
  32. #define GREP_OPT_s (1<<4)
  33. #define SUPPRESS_ERR_MSGS (option_mask32 & GREP_OPT_s)
  34. #define GREP_OPT_c (1<<5)
  35. #define PRINT_MATCH_COUNTS (option_mask32 & GREP_OPT_c)
  36. #define GREP_OPT_F (1<<6)
  37. #define FGREP_FLAG (option_mask32 & GREP_OPT_F)
  38. #define GREP_OPT_i (1<<7)
  39. #define GREP_OPT_H (1<<8)
  40. #define GREP_OPT_h (1<<9)
  41. #define GREP_OPT_e (1<<10)
  42. #define GREP_OPT_f (1<<11)
  43. #define GREP_OPT_L (1<<12)
  44. #define PRINT_FILES_WITHOUT_MATCHES (option_mask32 & GREP_OPT_L)
  45. #define GREP_OPT_o (1<<13)
  46. #define GREP_OPT_r (1<<14)
  47. #if ENABLE_FEATURE_GREP_CONTEXT
  48. # define GREP_OPT_CONTEXT "A:B:C:"
  49. # define GREP_OPT_A (1<<15)
  50. # define GREP_OPT_B (1<<16)
  51. # define GREP_OPT_C (1<<17)
  52. # define GREP_OPT_E (1<<18)
  53. #else
  54. # define GREP_OPT_CONTEXT ""
  55. # define GREP_OPT_A 0
  56. # define GREP_OPT_B 0
  57. # define GREP_OPT_C 0
  58. # define GREP_OPT_E (1<<15)
  59. #endif
  60. #if ENABLE_FEATURE_GREP_EGREP_ALIAS
  61. # define OPT_EGREP "E"
  62. #else
  63. # define OPT_EGREP ""
  64. #endif
  65. typedef unsigned char byte_t;
  66. static int reflags;
  67. static byte_t invert_search;
  68. static byte_t print_filename;
  69. static byte_t open_errors;
  70. #if ENABLE_FEATURE_GREP_CONTEXT
  71. static int lines_before;
  72. static int lines_after;
  73. static char **before_buf;
  74. static int last_line_printed;
  75. #endif /* ENABLE_FEATURE_GREP_CONTEXT */
  76. /* globals used internally */
  77. static llist_t *pattern_head; /* growable list of patterns to match */
  78. static const char *cur_file; /* the current file we are reading */
  79. typedef struct GREP_LIST_DATA {
  80. char *pattern;
  81. regex_t preg;
  82. #define PATTERN_MEM_A 1
  83. #define COMPILED 2
  84. int flg_mem_alocated_compiled;
  85. } grep_list_data_t;
  86. static void print_line(const char *line, int linenum, char decoration)
  87. {
  88. #if ENABLE_FEATURE_GREP_CONTEXT
  89. /* possibly print the little '--' separator */
  90. if ((lines_before || lines_after) && last_line_printed &&
  91. last_line_printed < linenum - 1) {
  92. puts("--");
  93. }
  94. last_line_printed = linenum;
  95. #endif
  96. if (print_filename)
  97. printf("%s%c", cur_file, decoration);
  98. if (PRINT_LINE_NUM)
  99. printf("%i%c", linenum, decoration);
  100. /* Emulate weird GNU grep behavior with -ov */
  101. if ((option_mask32 & (GREP_OPT_v+GREP_OPT_o)) != (GREP_OPT_v+GREP_OPT_o))
  102. puts(line);
  103. }
  104. static int grep_file(FILE *file)
  105. {
  106. char *line;
  107. byte_t ret;
  108. int linenum = 0;
  109. int nmatches = 0;
  110. regmatch_t regmatch;
  111. #if ENABLE_FEATURE_GREP_CONTEXT
  112. int print_n_lines_after = 0;
  113. int curpos = 0; /* track where we are in the circular 'before' buffer */
  114. int idx = 0; /* used for iteration through the circular buffer */
  115. #endif /* ENABLE_FEATURE_GREP_CONTEXT */
  116. while ((line = xmalloc_getline(file)) != NULL) {
  117. llist_t *pattern_ptr = pattern_head;
  118. grep_list_data_t * gl;
  119. linenum++;
  120. ret = 0;
  121. while (pattern_ptr) {
  122. gl = (grep_list_data_t *)pattern_ptr->data;
  123. if (FGREP_FLAG) {
  124. ret = strstr(line, gl->pattern) != NULL;
  125. } else {
  126. /*
  127. * test for a postitive-assertion match (regexec returns success (0)
  128. * and the user did not specify invert search), or a negative-assertion
  129. * match (regexec returns failure (REG_NOMATCH) and the user specified
  130. * invert search)
  131. */
  132. if (!(gl->flg_mem_alocated_compiled & COMPILED)) {
  133. gl->flg_mem_alocated_compiled |= COMPILED;
  134. xregcomp(&(gl->preg), gl->pattern, reflags);
  135. }
  136. regmatch.rm_so = 0;
  137. regmatch.rm_eo = 0;
  138. ret |= regexec(&(gl->preg), line, 1, &regmatch, 0) == 0;
  139. }
  140. pattern_ptr = pattern_ptr->link;
  141. } /* while (pattern_ptr) */
  142. if (ret ^ invert_search) {
  143. if (PRINT_FILES_WITH_MATCHES || BE_QUIET)
  144. free(line);
  145. /* if we found a match but were told to be quiet, stop here */
  146. if (BE_QUIET || PRINT_FILES_WITHOUT_MATCHES)
  147. return -1;
  148. /* keep track of matches */
  149. nmatches++;
  150. /* if we're just printing filenames, we stop after the first match */
  151. if (PRINT_FILES_WITH_MATCHES)
  152. break;
  153. /* print the matched line */
  154. if (PRINT_MATCH_COUNTS == 0) {
  155. #if ENABLE_FEATURE_GREP_CONTEXT
  156. int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
  157. /* if we were told to print 'before' lines and there is at least
  158. * one line in the circular buffer, print them */
  159. if (lines_before && before_buf[prevpos] != NULL) {
  160. int first_buf_entry_line_num = linenum - lines_before;
  161. /* advance to the first entry in the circular buffer, and
  162. * figure out the line number is of the first line in the
  163. * buffer */
  164. idx = curpos;
  165. while (before_buf[idx] == NULL) {
  166. idx = (idx + 1) % lines_before;
  167. first_buf_entry_line_num++;
  168. }
  169. /* now print each line in the buffer, clearing them as we go */
  170. while (before_buf[idx] != NULL) {
  171. print_line(before_buf[idx], first_buf_entry_line_num, '-');
  172. free(before_buf[idx]);
  173. before_buf[idx] = NULL;
  174. idx = (idx + 1) % lines_before;
  175. first_buf_entry_line_num++;
  176. }
  177. }
  178. /* make a note that we need to print 'after' lines */
  179. print_n_lines_after = lines_after;
  180. #endif
  181. if (option_mask32 & GREP_OPT_o) {
  182. line[regmatch.rm_eo] = '\0';
  183. print_line(line + regmatch.rm_so, linenum, ':');
  184. } else {
  185. print_line(line, linenum, ':');
  186. }
  187. }
  188. }
  189. #if ENABLE_FEATURE_GREP_CONTEXT
  190. else { /* no match */
  191. /* Add the line to the circular 'before' buffer */
  192. if (lines_before) {
  193. free(before_buf[curpos]);
  194. before_buf[curpos] = xstrdup(line);
  195. curpos = (curpos + 1) % lines_before;
  196. }
  197. }
  198. /* if we need to print some context lines after the last match, do so */
  199. if (print_n_lines_after && (last_line_printed != linenum)) {
  200. print_line(line, linenum, '-');
  201. print_n_lines_after--;
  202. }
  203. #endif /* ENABLE_FEATURE_GREP_CONTEXT */
  204. free(line);
  205. }
  206. /* special-case file post-processing for options where we don't print line
  207. * matches, just filenames and possibly match counts */
  208. /* grep -c: print [filename:]count, even if count is zero */
  209. if (PRINT_MATCH_COUNTS) {
  210. if (print_filename)
  211. printf("%s:", cur_file);
  212. printf("%d\n", nmatches);
  213. }
  214. /* grep -l: print just the filename, but only if we grepped the line in the file */
  215. if (PRINT_FILES_WITH_MATCHES && nmatches > 0) {
  216. puts(cur_file);
  217. }
  218. /* grep -L: print just the filename, but only if we didn't grep the line in the file */
  219. if (PRINT_FILES_WITHOUT_MATCHES && nmatches == 0) {
  220. puts(cur_file);
  221. }
  222. return nmatches;
  223. }
  224. #if ENABLE_FEATURE_CLEAN_UP
  225. #define new_grep_list_data(p, m) add_grep_list_data(p, m)
  226. static char * add_grep_list_data(char *pattern, int flg_used_mem)
  227. #else
  228. #define new_grep_list_data(p, m) add_grep_list_data(p)
  229. static char * add_grep_list_data(char *pattern)
  230. #endif
  231. {
  232. grep_list_data_t *gl = xmalloc(sizeof(grep_list_data_t));
  233. gl->pattern = pattern;
  234. #if ENABLE_FEATURE_CLEAN_UP
  235. gl->flg_mem_alocated_compiled = flg_used_mem;
  236. #else
  237. gl->flg_mem_alocated_compiled = 0;
  238. #endif
  239. return (char *)gl;
  240. }
  241. static void load_regexes_from_file(llist_t *fopt)
  242. {
  243. char *line;
  244. FILE *f;
  245. while (fopt) {
  246. llist_t *cur = fopt;
  247. char *ffile = cur->data;
  248. fopt = cur->link;
  249. free(cur);
  250. f = xfopen(ffile, "r");
  251. while ((line = xmalloc_getline(f)) != NULL) {
  252. llist_add_to(&pattern_head,
  253. new_grep_list_data(line, PATTERN_MEM_A));
  254. }
  255. }
  256. }
  257. static int file_action_grep(const char *filename, struct stat *statbuf, void* matched, int depth)
  258. {
  259. FILE *file = fopen(filename, "r");
  260. if (file == NULL) {
  261. if (!SUPPRESS_ERR_MSGS)
  262. bb_perror_msg("%s", cur_file);
  263. open_errors = 1;
  264. return 0;
  265. }
  266. cur_file = filename;
  267. *(int*)matched += grep_file(file);
  268. fclose(file);
  269. return 1;
  270. }
  271. static int grep_dir(const char *dir)
  272. {
  273. int matched = 0;
  274. recursive_action(dir,
  275. /* recurse= */ 1,
  276. /* followLinks= */ 0,
  277. /* depthFirst= */ 1,
  278. /* fileAction= */ file_action_grep,
  279. /* dirAction= */ NULL,
  280. /* userData= */ &matched,
  281. /* depth= */ 0);
  282. return matched;
  283. }
  284. int grep_main(int argc, char **argv)
  285. {
  286. FILE *file;
  287. int matched;
  288. llist_t *fopt = NULL;
  289. /* do normal option parsing */
  290. #if ENABLE_FEATURE_GREP_CONTEXT
  291. char *slines_after;
  292. char *slines_before;
  293. char *Copt;
  294. opt_complementary = "H-h:e::f::C-AB";
  295. getopt32(argc, argv,
  296. GREP_OPTS GREP_OPT_CONTEXT OPT_EGREP,
  297. &pattern_head, &fopt,
  298. &slines_after, &slines_before, &Copt);
  299. if (option_mask32 & GREP_OPT_C) {
  300. /* -C unsets prev -A and -B, but following -A or -B
  301. may override it */
  302. if (!(option_mask32 & GREP_OPT_A)) /* not overridden */
  303. slines_after = Copt;
  304. if (!(option_mask32 & GREP_OPT_B)) /* not overridden */
  305. slines_before = Copt;
  306. option_mask32 |= GREP_OPT_A|GREP_OPT_B; /* for parser */
  307. }
  308. if (option_mask32 & GREP_OPT_A) {
  309. lines_after = xatoi_u(slines_after);
  310. }
  311. if (option_mask32 & GREP_OPT_B) {
  312. lines_before = xatoi_u(slines_before);
  313. }
  314. /* sanity checks */
  315. if (option_mask32 & (GREP_OPT_c|GREP_OPT_q|GREP_OPT_l|GREP_OPT_L)) {
  316. option_mask32 &= ~GREP_OPT_n;
  317. lines_before = 0;
  318. lines_after = 0;
  319. } else if (lines_before > 0)
  320. before_buf = xzalloc(lines_before * sizeof(char *));
  321. #else
  322. /* with auto sanity checks */
  323. opt_complementary = "H-h:e::f::c-n:q-n:l-n";
  324. getopt32(argc, argv, GREP_OPTS OPT_EGREP,
  325. &pattern_head, &fopt);
  326. #endif
  327. invert_search = ((option_mask32 & GREP_OPT_v) != 0); /* 0 | 1 */
  328. if (pattern_head != NULL) {
  329. /* convert char *argv[] to grep_list_data_t */
  330. llist_t *cur;
  331. for (cur = pattern_head; cur; cur = cur->link)
  332. cur->data = new_grep_list_data(cur->data, 0);
  333. }
  334. if (option_mask32 & GREP_OPT_f)
  335. load_regexes_from_file(fopt);
  336. if (ENABLE_FEATURE_GREP_FGREP_ALIAS && applet_name[0] == 'f')
  337. option_mask32 |= GREP_OPT_F;
  338. if (!(option_mask32 & GREP_OPT_o))
  339. reflags = REG_NOSUB;
  340. if (ENABLE_FEATURE_GREP_EGREP_ALIAS &&
  341. (applet_name[0] == 'e' || (option_mask32 & GREP_OPT_E)))
  342. reflags |= REG_EXTENDED;
  343. if (option_mask32 & GREP_OPT_i)
  344. reflags |= REG_ICASE;
  345. argv += optind;
  346. argc -= optind;
  347. /* if we didn't get a pattern from a -e and no command file was specified,
  348. * argv[optind] should be the pattern. no pattern, no worky */
  349. if (pattern_head == NULL) {
  350. if (*argv == NULL)
  351. bb_show_usage();
  352. else {
  353. char *pattern = new_grep_list_data(*argv++, 0);
  354. llist_add_to(&pattern_head, pattern);
  355. argc--;
  356. }
  357. }
  358. /* argv[(optind)..(argc-1)] should be names of file to grep through. If
  359. * there is more than one file to grep, we will print the filenames. */
  360. if (argc > 1)
  361. print_filename = 1;
  362. /* -H / -h of course override */
  363. if (option_mask32 & GREP_OPT_H)
  364. print_filename = 1;
  365. if (option_mask32 & GREP_OPT_h)
  366. print_filename = 0;
  367. /* If no files were specified, or '-' was specified, take input from
  368. * stdin. Otherwise, we grep through all the files specified. */
  369. if (argc == 0)
  370. argc++;
  371. matched = 0;
  372. while (argc--) {
  373. cur_file = *argv++;
  374. file = stdin;
  375. if (!cur_file || (*cur_file == '-' && !cur_file[1])) {
  376. cur_file = "(standard input)";
  377. } else {
  378. if (option_mask32 & GREP_OPT_r) {
  379. struct stat st;
  380. if (stat(cur_file, &st) == 0 && S_ISDIR(st.st_mode)) {
  381. if (!(option_mask32 & GREP_OPT_h))
  382. print_filename = 1;
  383. matched += grep_dir(cur_file);
  384. goto grep_done;
  385. }
  386. }
  387. /* else: fopen(dir) will succeed, but reading won't */
  388. file = fopen(cur_file, "r");
  389. if (file == NULL) {
  390. if (!SUPPRESS_ERR_MSGS)
  391. bb_perror_msg("%s", cur_file);
  392. open_errors = 1;
  393. continue;
  394. }
  395. }
  396. matched += grep_file(file);
  397. fclose_if_not_stdin(file);
  398. grep_done:
  399. if (matched < 0) {
  400. /* we found a match but were told to be quiet, stop here and
  401. * return success */
  402. break;
  403. }
  404. }
  405. /* destroy all the elments in the pattern list */
  406. if (ENABLE_FEATURE_CLEAN_UP) {
  407. while (pattern_head) {
  408. llist_t *pattern_head_ptr = pattern_head;
  409. grep_list_data_t *gl =
  410. (grep_list_data_t *)pattern_head_ptr->data;
  411. pattern_head = pattern_head->link;
  412. if ((gl->flg_mem_alocated_compiled & PATTERN_MEM_A))
  413. free(gl->pattern);
  414. if ((gl->flg_mem_alocated_compiled & COMPILED))
  415. regfree(&(gl->preg));
  416. free(pattern_head_ptr);
  417. }
  418. }
  419. /* 0 = success, 1 = failed, 2 = error */
  420. /* If the -q option is specified, the exit status shall be zero
  421. * if an input line is selected, even if an error was detected. */
  422. if (BE_QUIET && matched)
  423. return 0;
  424. if (open_errors)
  425. return 2;
  426. return !matched; /* invert return value 0 = success, 1 = failed */
  427. }