grep.c 16 KB

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