grep.c 16 KB

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