grep.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 "libbb.h"
  22. #include "xregex.h"
  23. /* options */
  24. #define OPTSTR_GREP \
  25. "lnqvscFiHhe:f:Lorm:" \
  26. USE_FEATURE_GREP_CONTEXT("A:B:C:") \
  27. USE_FEATURE_GREP_EGREP_ALIAS("E") \
  28. USE_DESKTOP("w") \
  29. "aI"
  30. /* ignored: -a "assume all files to be text" */
  31. /* ignored: -I "assume binary files have no matches" */
  32. enum {
  33. OPTBIT_l, /* list matched file names only */
  34. OPTBIT_n, /* print line# */
  35. OPTBIT_q, /* quiet - exit(0) of first match */
  36. OPTBIT_v, /* invert the match, to select non-matching lines */
  37. OPTBIT_s, /* suppress errors about file open errors */
  38. OPTBIT_c, /* count matches per file (suppresses normal output) */
  39. OPTBIT_F, /* literal match */
  40. OPTBIT_i, /* case-insensitive */
  41. OPTBIT_H, /* force filename display */
  42. OPTBIT_h, /* inhibit filename display */
  43. OPTBIT_e, /* -e PATTERN */
  44. OPTBIT_f, /* -f FILE_WITH_PATTERNS */
  45. OPTBIT_L, /* list unmatched file names only */
  46. OPTBIT_o, /* show only matching parts of lines */
  47. OPTBIT_r, /* recurse dirs */
  48. OPTBIT_m, /* -m MAX_MATCHES */
  49. USE_FEATURE_GREP_CONTEXT( OPTBIT_A ,) /* -A NUM: after-match context */
  50. USE_FEATURE_GREP_CONTEXT( OPTBIT_B ,) /* -B NUM: before-match context */
  51. USE_FEATURE_GREP_CONTEXT( OPTBIT_C ,) /* -C NUM: -A and -B combined */
  52. USE_FEATURE_GREP_EGREP_ALIAS(OPTBIT_E ,) /* extended regexp */
  53. USE_DESKTOP( OPTBIT_w ,) /* whole word match */
  54. OPT_l = 1 << OPTBIT_l,
  55. OPT_n = 1 << OPTBIT_n,
  56. OPT_q = 1 << OPTBIT_q,
  57. OPT_v = 1 << OPTBIT_v,
  58. OPT_s = 1 << OPTBIT_s,
  59. OPT_c = 1 << OPTBIT_c,
  60. OPT_F = 1 << OPTBIT_F,
  61. OPT_i = 1 << OPTBIT_i,
  62. OPT_H = 1 << OPTBIT_H,
  63. OPT_h = 1 << OPTBIT_h,
  64. OPT_e = 1 << OPTBIT_e,
  65. OPT_f = 1 << OPTBIT_f,
  66. OPT_L = 1 << OPTBIT_L,
  67. OPT_o = 1 << OPTBIT_o,
  68. OPT_r = 1 << OPTBIT_r,
  69. OPT_m = 1 << OPTBIT_m,
  70. OPT_A = USE_FEATURE_GREP_CONTEXT( (1 << OPTBIT_A)) + 0,
  71. OPT_B = USE_FEATURE_GREP_CONTEXT( (1 << OPTBIT_B)) + 0,
  72. OPT_C = USE_FEATURE_GREP_CONTEXT( (1 << OPTBIT_C)) + 0,
  73. OPT_E = USE_FEATURE_GREP_EGREP_ALIAS((1 << OPTBIT_E)) + 0,
  74. OPT_w = USE_DESKTOP( (1 << OPTBIT_w)) + 0,
  75. };
  76. #define PRINT_FILES_WITH_MATCHES (option_mask32 & OPT_l)
  77. #define PRINT_LINE_NUM (option_mask32 & OPT_n)
  78. #define BE_QUIET (option_mask32 & OPT_q)
  79. #define SUPPRESS_ERR_MSGS (option_mask32 & OPT_s)
  80. #define PRINT_MATCH_COUNTS (option_mask32 & OPT_c)
  81. #define FGREP_FLAG (option_mask32 & OPT_F)
  82. #define PRINT_FILES_WITHOUT_MATCHES (option_mask32 & OPT_L)
  83. typedef unsigned char byte_t;
  84. static int max_matches;
  85. static int reflags;
  86. static byte_t invert_search;
  87. static byte_t print_filename;
  88. static byte_t open_errors;
  89. #if ENABLE_FEATURE_GREP_CONTEXT
  90. static byte_t did_print_line;
  91. static int lines_before;
  92. static int lines_after;
  93. static char **before_buf;
  94. static int last_line_printed;
  95. #endif /* ENABLE_FEATURE_GREP_CONTEXT */
  96. /* globals used internally */
  97. static llist_t *pattern_head; /* growable list of patterns to match */
  98. static const char *cur_file; /* the current file we are reading */
  99. typedef struct grep_list_data_t {
  100. char *pattern;
  101. regex_t preg;
  102. #define PATTERN_MEM_A 1
  103. #define COMPILED 2
  104. int flg_mem_alocated_compiled;
  105. } grep_list_data_t;
  106. static void print_line(const char *line, int linenum, char decoration)
  107. {
  108. #if ENABLE_FEATURE_GREP_CONTEXT
  109. /* Happens when we go to next file, immediately hit match
  110. * and try to print prev context... from prev file! Don't do it */
  111. if (linenum < 1)
  112. return;
  113. /* possibly print the little '--' separator */
  114. if ((lines_before || lines_after) && did_print_line &&
  115. last_line_printed != linenum - 1) {
  116. puts("--");
  117. }
  118. /* guard against printing "--" before first line of first file */
  119. did_print_line = 1;
  120. last_line_printed = linenum;
  121. #endif
  122. if (print_filename)
  123. printf("%s%c", cur_file, decoration);
  124. if (PRINT_LINE_NUM)
  125. printf("%i%c", linenum, decoration);
  126. /* Emulate weird GNU grep behavior with -ov */
  127. if ((option_mask32 & (OPT_v|OPT_o)) != (OPT_v|OPT_o))
  128. puts(line);
  129. }
  130. static int grep_file(FILE *file)
  131. {
  132. char *line;
  133. byte_t ret;
  134. int linenum = 0;
  135. int nmatches = 0;
  136. regmatch_t regmatch;
  137. #if ENABLE_FEATURE_GREP_CONTEXT
  138. int print_n_lines_after = 0;
  139. int curpos = 0; /* track where we are in the circular 'before' buffer */
  140. int idx = 0; /* used for iteration through the circular buffer */
  141. #else
  142. enum { print_n_lines_after = 0 };
  143. #endif /* ENABLE_FEATURE_GREP_CONTEXT */
  144. while ((line = xmalloc_getline(file)) != NULL) {
  145. llist_t *pattern_ptr = pattern_head;
  146. grep_list_data_t *gl = gl; /* for gcc */
  147. linenum++;
  148. ret = 0;
  149. while (pattern_ptr) {
  150. gl = (grep_list_data_t *)pattern_ptr->data;
  151. if (FGREP_FLAG) {
  152. ret |= (strstr(line, gl->pattern) != NULL);
  153. } else {
  154. /*
  155. * test for a postitive-assertion match (regexec returns success (0)
  156. * and the user did not specify invert search), or a negative-assertion
  157. * match (regexec returns failure (REG_NOMATCH) and the user specified
  158. * invert search)
  159. */
  160. if (!(gl->flg_mem_alocated_compiled & COMPILED)) {
  161. gl->flg_mem_alocated_compiled |= COMPILED;
  162. xregcomp(&(gl->preg), gl->pattern, reflags);
  163. }
  164. regmatch.rm_so = 0;
  165. regmatch.rm_eo = 0;
  166. if (regexec(&(gl->preg), line, 1, &regmatch, 0) == 0) {
  167. if (!(option_mask32 & OPT_w))
  168. ret = 1;
  169. else {
  170. char c = ' ';
  171. if (regmatch.rm_so)
  172. c = line[regmatch.rm_so - 1];
  173. if (!isalnum(c) && c != '_') {
  174. c = line[regmatch.rm_eo];
  175. if (!c || (!isalnum(c) && c != '_'))
  176. ret = 1;
  177. }
  178. }
  179. }
  180. }
  181. pattern_ptr = pattern_ptr->link;
  182. } /* while (pattern_ptr) */
  183. if (ret ^ invert_search) {
  184. /* keep track of matches */
  185. nmatches++;
  186. /* quiet/print (non)matching file names only? */
  187. if (option_mask32 & (OPT_q|OPT_l|OPT_L)) {
  188. free(line); /* we don't need line anymore */
  189. if (BE_QUIET) {
  190. /* manpage says about -q:
  191. * "exit immediately with zero status
  192. * if any match is found,
  193. * even if errors were detected" */
  194. exit(0);
  195. }
  196. /* if we're just printing filenames, we stop after the first match */
  197. if (PRINT_FILES_WITH_MATCHES) {
  198. puts(cur_file);
  199. /* fall thru to "return 1" */
  200. }
  201. /* OPT_L aka PRINT_FILES_WITHOUT_MATCHES: return early */
  202. return 1; /* one match */
  203. }
  204. #if ENABLE_FEATURE_GREP_CONTEXT
  205. /* Were we printing context and saw next (unwanted) match? */
  206. if ((option_mask32 & OPT_m) && nmatches > max_matches)
  207. break;
  208. #endif
  209. /* print the matched line */
  210. if (PRINT_MATCH_COUNTS == 0) {
  211. #if ENABLE_FEATURE_GREP_CONTEXT
  212. int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
  213. /* if we were told to print 'before' lines and there is at least
  214. * one line in the circular buffer, print them */
  215. if (lines_before && before_buf[prevpos] != NULL) {
  216. int first_buf_entry_line_num = linenum - lines_before;
  217. /* advance to the first entry in the circular buffer, and
  218. * figure out the line number is of the first line in the
  219. * buffer */
  220. idx = curpos;
  221. while (before_buf[idx] == NULL) {
  222. idx = (idx + 1) % lines_before;
  223. first_buf_entry_line_num++;
  224. }
  225. /* now print each line in the buffer, clearing them as we go */
  226. while (before_buf[idx] != NULL) {
  227. print_line(before_buf[idx], first_buf_entry_line_num, '-');
  228. free(before_buf[idx]);
  229. before_buf[idx] = NULL;
  230. idx = (idx + 1) % lines_before;
  231. first_buf_entry_line_num++;
  232. }
  233. }
  234. /* make a note that we need to print 'after' lines */
  235. print_n_lines_after = lines_after;
  236. #endif
  237. if (option_mask32 & OPT_o) {
  238. if (FGREP_FLAG) {
  239. /* -Fo just prints the pattern
  240. * (unless -v: -Fov doesnt print anything at all) */
  241. if (ret)
  242. print_line(gl->pattern, linenum, ':');
  243. } else {
  244. line[regmatch.rm_eo] = '\0';
  245. print_line(line + regmatch.rm_so, linenum, ':');
  246. }
  247. } else {
  248. print_line(line, linenum, ':');
  249. }
  250. }
  251. }
  252. #if ENABLE_FEATURE_GREP_CONTEXT
  253. else { /* no match */
  254. /* if we need to print some context lines after the last match, do so */
  255. if (print_n_lines_after) {
  256. print_line(line, linenum, '-');
  257. print_n_lines_after--;
  258. } else if (lines_before) {
  259. /* Add the line to the circular 'before' buffer */
  260. free(before_buf[curpos]);
  261. before_buf[curpos] = line;
  262. curpos = (curpos + 1) % lines_before;
  263. /* avoid free(line) - we took line */
  264. line = NULL;
  265. }
  266. }
  267. #endif /* ENABLE_FEATURE_GREP_CONTEXT */
  268. free(line);
  269. /* Did we print all context after last requested match? */
  270. if ((option_mask32 & OPT_m)
  271. && !print_n_lines_after && nmatches == max_matches)
  272. break;
  273. }
  274. /* special-case file post-processing for options where we don't print line
  275. * matches, just filenames and possibly match counts */
  276. /* grep -c: print [filename:]count, even if count is zero */
  277. if (PRINT_MATCH_COUNTS) {
  278. if (print_filename)
  279. printf("%s:", cur_file);
  280. printf("%d\n", nmatches);
  281. }
  282. /* grep -L: print just the filename */
  283. if (PRINT_FILES_WITHOUT_MATCHES) {
  284. /* nmatches is zero, no need to check it:
  285. * we return 1 early if we detected a match
  286. * and PRINT_FILES_WITHOUT_MATCHES is set */
  287. puts(cur_file);
  288. }
  289. return nmatches;
  290. }
  291. #if ENABLE_FEATURE_CLEAN_UP
  292. #define new_grep_list_data(p, m) add_grep_list_data(p, m)
  293. static char * add_grep_list_data(char *pattern, int flg_used_mem)
  294. #else
  295. #define new_grep_list_data(p, m) add_grep_list_data(p)
  296. static char * add_grep_list_data(char *pattern)
  297. #endif
  298. {
  299. grep_list_data_t *gl = xmalloc(sizeof(grep_list_data_t));
  300. gl->pattern = pattern;
  301. #if ENABLE_FEATURE_CLEAN_UP
  302. gl->flg_mem_alocated_compiled = flg_used_mem;
  303. #else
  304. gl->flg_mem_alocated_compiled = 0;
  305. #endif
  306. return (char *)gl;
  307. }
  308. static void load_regexes_from_file(llist_t *fopt)
  309. {
  310. char *line;
  311. FILE *f;
  312. while (fopt) {
  313. llist_t *cur = fopt;
  314. char *ffile = cur->data;
  315. fopt = cur->link;
  316. free(cur);
  317. f = xfopen(ffile, "r");
  318. while ((line = xmalloc_getline(f)) != NULL) {
  319. llist_add_to(&pattern_head,
  320. new_grep_list_data(line, PATTERN_MEM_A));
  321. }
  322. }
  323. }
  324. static int file_action_grep(const char *filename, struct stat *statbuf, void* matched, int depth)
  325. {
  326. FILE *file = fopen(filename, "r");
  327. if (file == NULL) {
  328. if (!SUPPRESS_ERR_MSGS)
  329. bb_perror_msg("%s", cur_file);
  330. open_errors = 1;
  331. return 0;
  332. }
  333. cur_file = filename;
  334. *(int*)matched += grep_file(file);
  335. fclose(file);
  336. return 1;
  337. }
  338. static int grep_dir(const char *dir)
  339. {
  340. int matched = 0;
  341. recursive_action(dir,
  342. /* recurse=yes */ ACTION_RECURSE |
  343. /* followLinks=no */
  344. /* depthFirst=yes */ ACTION_DEPTHFIRST,
  345. /* fileAction= */ file_action_grep,
  346. /* dirAction= */ NULL,
  347. /* userData= */ &matched,
  348. /* depth= */ 0);
  349. return matched;
  350. }
  351. int grep_main(int argc, char **argv);
  352. int grep_main(int argc, char **argv)
  353. {
  354. FILE *file;
  355. int matched;
  356. char *mopt;
  357. llist_t *fopt = NULL;
  358. /* do normal option parsing */
  359. #if ENABLE_FEATURE_GREP_CONTEXT
  360. char *slines_after;
  361. char *slines_before;
  362. char *Copt;
  363. opt_complementary = "H-h:e::f::C-AB";
  364. getopt32(argv,
  365. OPTSTR_GREP,
  366. &pattern_head, &fopt, &mopt,
  367. &slines_after, &slines_before, &Copt);
  368. if (option_mask32 & OPT_C) {
  369. /* -C unsets prev -A and -B, but following -A or -B
  370. may override it */
  371. if (!(option_mask32 & OPT_A)) /* not overridden */
  372. slines_after = Copt;
  373. if (!(option_mask32 & OPT_B)) /* not overridden */
  374. slines_before = Copt;
  375. option_mask32 |= OPT_A|OPT_B; /* for parser */
  376. }
  377. if (option_mask32 & OPT_A) {
  378. lines_after = xatoi_u(slines_after);
  379. }
  380. if (option_mask32 & OPT_B) {
  381. lines_before = xatoi_u(slines_before);
  382. }
  383. /* sanity checks */
  384. if (option_mask32 & (OPT_c|OPT_q|OPT_l|OPT_L)) {
  385. option_mask32 &= ~OPT_n;
  386. lines_before = 0;
  387. lines_after = 0;
  388. } else if (lines_before > 0)
  389. before_buf = xzalloc(lines_before * sizeof(char *));
  390. #else
  391. /* with auto sanity checks */
  392. opt_complementary = "H-h:e::f::c-n:q-n:l-n";
  393. getopt32(argv, OPTSTR_GREP,
  394. &pattern_head, &fopt, &mopt);
  395. #endif
  396. if (option_mask32 & OPT_m) {
  397. max_matches = xatoi_u(mopt);
  398. }
  399. invert_search = ((option_mask32 & OPT_v) != 0); /* 0 | 1 */
  400. if (pattern_head != NULL) {
  401. /* convert char **argv to grep_list_data_t */
  402. llist_t *cur;
  403. for (cur = pattern_head; cur; cur = cur->link)
  404. cur->data = new_grep_list_data(cur->data, 0);
  405. }
  406. if (option_mask32 & OPT_f)
  407. load_regexes_from_file(fopt);
  408. if (ENABLE_FEATURE_GREP_FGREP_ALIAS && applet_name[0] == 'f')
  409. option_mask32 |= OPT_F;
  410. if (!(option_mask32 & (OPT_o | OPT_w)))
  411. reflags = REG_NOSUB;
  412. if (ENABLE_FEATURE_GREP_EGREP_ALIAS &&
  413. (applet_name[0] == 'e' || (option_mask32 & OPT_E)))
  414. reflags |= REG_EXTENDED;
  415. if (option_mask32 & OPT_i)
  416. reflags |= REG_ICASE;
  417. argv += optind;
  418. argc -= optind;
  419. /* if we didn't get a pattern from a -e and no command file was specified,
  420. * argv[optind] should be the pattern. no pattern, no worky */
  421. if (pattern_head == NULL) {
  422. char *pattern;
  423. if (*argv == NULL)
  424. bb_show_usage();
  425. pattern = new_grep_list_data(*argv++, 0);
  426. llist_add_to(&pattern_head, pattern);
  427. argc--;
  428. }
  429. /* argv[(optind)..(argc-1)] should be names of file to grep through. If
  430. * there is more than one file to grep, we will print the filenames. */
  431. if (argc > 1)
  432. print_filename = 1;
  433. /* -H / -h of course override */
  434. if (option_mask32 & OPT_H)
  435. print_filename = 1;
  436. if (option_mask32 & OPT_h)
  437. print_filename = 0;
  438. /* If no files were specified, or '-' was specified, take input from
  439. * stdin. Otherwise, we grep through all the files specified. */
  440. if (argc == 0)
  441. argc++;
  442. matched = 0;
  443. while (argc--) {
  444. cur_file = *argv++;
  445. file = stdin;
  446. if (!cur_file || (*cur_file == '-' && !cur_file[1])) {
  447. cur_file = "(standard input)";
  448. } else {
  449. if (option_mask32 & OPT_r) {
  450. struct stat st;
  451. if (stat(cur_file, &st) == 0 && S_ISDIR(st.st_mode)) {
  452. if (!(option_mask32 & OPT_h))
  453. print_filename = 1;
  454. matched += grep_dir(cur_file);
  455. goto grep_done;
  456. }
  457. }
  458. /* else: fopen(dir) will succeed, but reading won't */
  459. file = fopen(cur_file, "r");
  460. if (file == NULL) {
  461. if (!SUPPRESS_ERR_MSGS)
  462. bb_perror_msg("%s", cur_file);
  463. open_errors = 1;
  464. continue;
  465. }
  466. }
  467. matched += grep_file(file);
  468. fclose_if_not_stdin(file);
  469. grep_done: ;
  470. }
  471. /* destroy all the elments in the pattern list */
  472. if (ENABLE_FEATURE_CLEAN_UP) {
  473. while (pattern_head) {
  474. llist_t *pattern_head_ptr = pattern_head;
  475. grep_list_data_t *gl =
  476. (grep_list_data_t *)pattern_head_ptr->data;
  477. pattern_head = pattern_head->link;
  478. if ((gl->flg_mem_alocated_compiled & PATTERN_MEM_A))
  479. free(gl->pattern);
  480. if ((gl->flg_mem_alocated_compiled & COMPILED))
  481. regfree(&(gl->preg));
  482. free(gl);
  483. free(pattern_head_ptr);
  484. }
  485. }
  486. /* 0 = success, 1 = failed, 2 = error */
  487. if (open_errors)
  488. return 2;
  489. return !matched; /* invert return value 0 = success, 1 = failed */
  490. }