grep.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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. //kbuild:lib-$(CONFIG_GREP) += grep.o
  22. //config:
  23. //config:config GREP
  24. //config: bool "grep"
  25. //config: default n
  26. //config: help
  27. //config: grep is used to search files for a specified pattern.
  28. //config:
  29. //config:config FEATURE_GREP_EGREP_ALIAS
  30. //config: bool "Enable extended regular expressions (egrep & grep -E)"
  31. //config: default y
  32. //config: depends on GREP
  33. //config: help
  34. //config: Enabled support for extended regular expressions. Extended
  35. //config: regular expressions allow for alternation (foo|bar), grouping,
  36. //config: and various repetition operators.
  37. //config:
  38. //config:config FEATURE_GREP_FGREP_ALIAS
  39. //config: bool "Alias fgrep to grep -F"
  40. //config: default y
  41. //config: depends on GREP
  42. //config: help
  43. //config: fgrep sees the search pattern as a normal string rather than
  44. //config: regular expressions.
  45. //config: grep -F always works, this just creates the fgrep alias.
  46. //config:
  47. //config:config FEATURE_GREP_CONTEXT
  48. //config: bool "Enable before and after context flags (-A, -B and -C)"
  49. //config: default y
  50. //config: depends on GREP
  51. //config: help
  52. //config: Print the specified number of leading (-B) and/or trailing (-A)
  53. //config: context surrounding our matching lines.
  54. //config: Print the specified number of context lines (-C).
  55. #include "libbb.h"
  56. #include "xregex.h"
  57. /* options */
  58. #define OPTSTR_GREP \
  59. "lnqvscFiHhe:f:Lorm:w" \
  60. IF_FEATURE_GREP_CONTEXT("A:B:C:") \
  61. IF_FEATURE_GREP_EGREP_ALIAS("E") \
  62. IF_EXTRA_COMPAT("z") \
  63. "aI"
  64. /* ignored: -a "assume all files to be text" */
  65. /* ignored: -I "assume binary files have no matches" */
  66. enum {
  67. OPTBIT_l, /* list matched file names only */
  68. OPTBIT_n, /* print line# */
  69. OPTBIT_q, /* quiet - exit(EXIT_SUCCESS) of first match */
  70. OPTBIT_v, /* invert the match, to select non-matching lines */
  71. OPTBIT_s, /* suppress errors about file open errors */
  72. OPTBIT_c, /* count matches per file (suppresses normal output) */
  73. OPTBIT_F, /* literal match */
  74. OPTBIT_i, /* case-insensitive */
  75. OPTBIT_H, /* force filename display */
  76. OPTBIT_h, /* inhibit filename display */
  77. OPTBIT_e, /* -e PATTERN */
  78. OPTBIT_f, /* -f FILE_WITH_PATTERNS */
  79. OPTBIT_L, /* list unmatched file names only */
  80. OPTBIT_o, /* show only matching parts of lines */
  81. OPTBIT_r, /* recurse dirs */
  82. OPTBIT_m, /* -m MAX_MATCHES */
  83. OPTBIT_w, /* -w whole word match */
  84. IF_FEATURE_GREP_CONTEXT( OPTBIT_A ,) /* -A NUM: after-match context */
  85. IF_FEATURE_GREP_CONTEXT( OPTBIT_B ,) /* -B NUM: before-match context */
  86. IF_FEATURE_GREP_CONTEXT( OPTBIT_C ,) /* -C NUM: -A and -B combined */
  87. IF_FEATURE_GREP_EGREP_ALIAS(OPTBIT_E ,) /* extended regexp */
  88. IF_EXTRA_COMPAT( OPTBIT_z ,) /* input is NUL terminated */
  89. OPT_l = 1 << OPTBIT_l,
  90. OPT_n = 1 << OPTBIT_n,
  91. OPT_q = 1 << OPTBIT_q,
  92. OPT_v = 1 << OPTBIT_v,
  93. OPT_s = 1 << OPTBIT_s,
  94. OPT_c = 1 << OPTBIT_c,
  95. OPT_F = 1 << OPTBIT_F,
  96. OPT_i = 1 << OPTBIT_i,
  97. OPT_H = 1 << OPTBIT_H,
  98. OPT_h = 1 << OPTBIT_h,
  99. OPT_e = 1 << OPTBIT_e,
  100. OPT_f = 1 << OPTBIT_f,
  101. OPT_L = 1 << OPTBIT_L,
  102. OPT_o = 1 << OPTBIT_o,
  103. OPT_r = 1 << OPTBIT_r,
  104. OPT_m = 1 << OPTBIT_m,
  105. OPT_w = 1 << OPTBIT_w,
  106. OPT_A = IF_FEATURE_GREP_CONTEXT( (1 << OPTBIT_A)) + 0,
  107. OPT_B = IF_FEATURE_GREP_CONTEXT( (1 << OPTBIT_B)) + 0,
  108. OPT_C = IF_FEATURE_GREP_CONTEXT( (1 << OPTBIT_C)) + 0,
  109. OPT_E = IF_FEATURE_GREP_EGREP_ALIAS((1 << OPTBIT_E)) + 0,
  110. OPT_z = IF_EXTRA_COMPAT( (1 << OPTBIT_z)) + 0,
  111. };
  112. #define PRINT_FILES_WITH_MATCHES (option_mask32 & OPT_l)
  113. #define PRINT_LINE_NUM (option_mask32 & OPT_n)
  114. #define BE_QUIET (option_mask32 & OPT_q)
  115. #define SUPPRESS_ERR_MSGS (option_mask32 & OPT_s)
  116. #define PRINT_MATCH_COUNTS (option_mask32 & OPT_c)
  117. #define FGREP_FLAG (option_mask32 & OPT_F)
  118. #define PRINT_FILES_WITHOUT_MATCHES (option_mask32 & OPT_L)
  119. #define NUL_DELIMITED (option_mask32 & OPT_z)
  120. struct globals {
  121. int max_matches;
  122. #if !ENABLE_EXTRA_COMPAT
  123. int reflags;
  124. #else
  125. RE_TRANSLATE_TYPE case_fold; /* RE_TRANSLATE_TYPE is [[un]signed] char* */
  126. #endif
  127. smalluint invert_search;
  128. smalluint print_filename;
  129. smalluint open_errors;
  130. #if ENABLE_FEATURE_GREP_CONTEXT
  131. smalluint did_print_line;
  132. int lines_before;
  133. int lines_after;
  134. char **before_buf;
  135. IF_EXTRA_COMPAT(size_t *before_buf_size;)
  136. int last_line_printed;
  137. #endif
  138. /* globals used internally */
  139. llist_t *pattern_head; /* growable list of patterns to match */
  140. const char *cur_file; /* the current file we are reading */
  141. } FIX_ALIASING;
  142. #define G (*(struct globals*)&bb_common_bufsiz1)
  143. #define INIT_G() do { \
  144. struct G_sizecheck { \
  145. char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
  146. }; \
  147. } while (0)
  148. #define max_matches (G.max_matches )
  149. #if !ENABLE_EXTRA_COMPAT
  150. # define reflags (G.reflags )
  151. #else
  152. # define case_fold (G.case_fold )
  153. /* http://www.delorie.com/gnu/docs/regex/regex_46.html */
  154. # define reflags re_syntax_options
  155. # undef REG_NOSUB
  156. # undef REG_EXTENDED
  157. # undef REG_ICASE
  158. # define REG_NOSUB bug:is:here /* should not be used */
  159. /* Just RE_SYNTAX_EGREP is not enough, need to enable {n[,[m]]} too */
  160. # define REG_EXTENDED (RE_SYNTAX_EGREP | RE_INTERVALS | RE_NO_BK_BRACES)
  161. # define REG_ICASE bug:is:here /* should not be used */
  162. #endif
  163. #define invert_search (G.invert_search )
  164. #define print_filename (G.print_filename )
  165. #define open_errors (G.open_errors )
  166. #define did_print_line (G.did_print_line )
  167. #define lines_before (G.lines_before )
  168. #define lines_after (G.lines_after )
  169. #define before_buf (G.before_buf )
  170. #define before_buf_size (G.before_buf_size )
  171. #define last_line_printed (G.last_line_printed )
  172. #define pattern_head (G.pattern_head )
  173. #define cur_file (G.cur_file )
  174. typedef struct grep_list_data_t {
  175. char *pattern;
  176. /* for GNU regex, matched_range must be persistent across grep_file() calls */
  177. #if !ENABLE_EXTRA_COMPAT
  178. regex_t compiled_regex;
  179. regmatch_t matched_range;
  180. #else
  181. struct re_pattern_buffer compiled_regex;
  182. struct re_registers matched_range;
  183. #endif
  184. #define ALLOCATED 1
  185. #define COMPILED 2
  186. int flg_mem_alocated_compiled;
  187. } grep_list_data_t;
  188. #if !ENABLE_EXTRA_COMPAT
  189. #define print_line(line, line_len, linenum, decoration) \
  190. print_line(line, linenum, decoration)
  191. #endif
  192. static void print_line(const char *line, size_t line_len, int linenum, char decoration)
  193. {
  194. #if ENABLE_FEATURE_GREP_CONTEXT
  195. /* Happens when we go to next file, immediately hit match
  196. * and try to print prev context... from prev file! Don't do it */
  197. if (linenum < 1)
  198. return;
  199. /* possibly print the little '--' separator */
  200. if ((lines_before || lines_after) && did_print_line
  201. && last_line_printed != linenum - 1
  202. ) {
  203. puts("--");
  204. }
  205. /* guard against printing "--" before first line of first file */
  206. did_print_line = 1;
  207. last_line_printed = linenum;
  208. #endif
  209. if (print_filename)
  210. printf("%s%c", cur_file, decoration);
  211. if (PRINT_LINE_NUM)
  212. printf("%i%c", linenum, decoration);
  213. /* Emulate weird GNU grep behavior with -ov */
  214. if ((option_mask32 & (OPT_v|OPT_o)) != (OPT_v|OPT_o)) {
  215. #if !ENABLE_EXTRA_COMPAT
  216. puts(line);
  217. #else
  218. fwrite(line, 1, line_len, stdout);
  219. putchar(NUL_DELIMITED ? '\0' : '\n');
  220. #endif
  221. }
  222. }
  223. #if ENABLE_EXTRA_COMPAT
  224. /* Unlike getline, this one removes trailing '\n' */
  225. static ssize_t FAST_FUNC bb_getline(char **line_ptr, size_t *line_alloc_len, FILE *file)
  226. {
  227. ssize_t res_sz;
  228. char *line;
  229. int delim = (NUL_DELIMITED ? '\0' : '\n');
  230. res_sz = getdelim(line_ptr, line_alloc_len, delim, file);
  231. line = *line_ptr;
  232. if (res_sz > 0) {
  233. if (line[res_sz - 1] == delim)
  234. line[--res_sz] = '\0';
  235. } else {
  236. free(line); /* uclibc allocates a buffer even on EOF. WTF? */
  237. }
  238. return res_sz;
  239. }
  240. #endif
  241. static int grep_file(FILE *file)
  242. {
  243. smalluint found;
  244. int linenum = 0;
  245. int nmatches = 0;
  246. #if !ENABLE_EXTRA_COMPAT
  247. char *line;
  248. #else
  249. char *line = NULL;
  250. ssize_t line_len;
  251. size_t line_alloc_len;
  252. # define rm_so start[0]
  253. # define rm_eo end[0]
  254. #endif
  255. #if ENABLE_FEATURE_GREP_CONTEXT
  256. int print_n_lines_after = 0;
  257. int curpos = 0; /* track where we are in the circular 'before' buffer */
  258. int idx = 0; /* used for iteration through the circular buffer */
  259. #else
  260. enum { print_n_lines_after = 0 };
  261. #endif
  262. while (
  263. #if !ENABLE_EXTRA_COMPAT
  264. (line = xmalloc_fgetline(file)) != NULL
  265. #else
  266. (line_len = bb_getline(&line, &line_alloc_len, file)) >= 0
  267. #endif
  268. ) {
  269. llist_t *pattern_ptr = pattern_head;
  270. grep_list_data_t *gl = gl; /* for gcc */
  271. linenum++;
  272. found = 0;
  273. while (pattern_ptr) {
  274. gl = (grep_list_data_t *)pattern_ptr->data;
  275. if (FGREP_FLAG) {
  276. found |= (((option_mask32 & OPT_i)
  277. ? strcasestr(line, gl->pattern)
  278. : strstr(line, gl->pattern)
  279. ) != NULL);
  280. } else {
  281. if (!(gl->flg_mem_alocated_compiled & COMPILED)) {
  282. gl->flg_mem_alocated_compiled |= COMPILED;
  283. #if !ENABLE_EXTRA_COMPAT
  284. xregcomp(&gl->compiled_regex, gl->pattern, reflags);
  285. #else
  286. memset(&gl->compiled_regex, 0, sizeof(gl->compiled_regex));
  287. gl->compiled_regex.translate = case_fold; /* for -i */
  288. if (re_compile_pattern(gl->pattern, strlen(gl->pattern), &gl->compiled_regex))
  289. bb_error_msg_and_die("bad regex '%s'", gl->pattern);
  290. #endif
  291. }
  292. #if !ENABLE_EXTRA_COMPAT
  293. gl->matched_range.rm_so = 0;
  294. gl->matched_range.rm_eo = 0;
  295. #endif
  296. if (
  297. #if !ENABLE_EXTRA_COMPAT
  298. regexec(&gl->compiled_regex, line, 1, &gl->matched_range, 0) == 0
  299. #else
  300. re_search(&gl->compiled_regex, line, line_len,
  301. /*start:*/ 0, /*range:*/ line_len,
  302. &gl->matched_range) >= 0
  303. #endif
  304. ) {
  305. if (!(option_mask32 & OPT_w))
  306. found = 1;
  307. else {
  308. char c = ' ';
  309. if (gl->matched_range.rm_so)
  310. c = line[gl->matched_range.rm_so - 1];
  311. if (!isalnum(c) && c != '_') {
  312. c = line[gl->matched_range.rm_eo];
  313. if (!c || (!isalnum(c) && c != '_'))
  314. found = 1;
  315. }
  316. }
  317. }
  318. }
  319. /* If it's non-inverted search, we can stop
  320. * at first match */
  321. if (found && !invert_search)
  322. goto do_found;
  323. pattern_ptr = pattern_ptr->link;
  324. } /* while (pattern_ptr) */
  325. if (found ^ invert_search) {
  326. do_found:
  327. /* keep track of matches */
  328. nmatches++;
  329. /* quiet/print (non)matching file names only? */
  330. if (option_mask32 & (OPT_q|OPT_l|OPT_L)) {
  331. free(line); /* we don't need line anymore */
  332. if (BE_QUIET) {
  333. /* manpage says about -q:
  334. * "exit immediately with zero status
  335. * if any match is found,
  336. * even if errors were detected" */
  337. exit(EXIT_SUCCESS);
  338. }
  339. /* if we're just printing filenames, we stop after the first match */
  340. if (PRINT_FILES_WITH_MATCHES) {
  341. puts(cur_file);
  342. /* fall through to "return 1" */
  343. }
  344. /* OPT_L aka PRINT_FILES_WITHOUT_MATCHES: return early */
  345. return 1; /* one match */
  346. }
  347. #if ENABLE_FEATURE_GREP_CONTEXT
  348. /* Were we printing context and saw next (unwanted) match? */
  349. if ((option_mask32 & OPT_m) && nmatches > max_matches)
  350. break;
  351. #endif
  352. /* print the matched line */
  353. if (PRINT_MATCH_COUNTS == 0) {
  354. #if ENABLE_FEATURE_GREP_CONTEXT
  355. int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
  356. /* if we were told to print 'before' lines and there is at least
  357. * one line in the circular buffer, print them */
  358. if (lines_before && before_buf[prevpos] != NULL) {
  359. int first_buf_entry_line_num = linenum - lines_before;
  360. /* advance to the first entry in the circular buffer, and
  361. * figure out the line number is of the first line in the
  362. * buffer */
  363. idx = curpos;
  364. while (before_buf[idx] == NULL) {
  365. idx = (idx + 1) % lines_before;
  366. first_buf_entry_line_num++;
  367. }
  368. /* now print each line in the buffer, clearing them as we go */
  369. while (before_buf[idx] != NULL) {
  370. print_line(before_buf[idx], before_buf_size[idx], first_buf_entry_line_num, '-');
  371. free(before_buf[idx]);
  372. before_buf[idx] = NULL;
  373. idx = (idx + 1) % lines_before;
  374. first_buf_entry_line_num++;
  375. }
  376. }
  377. /* make a note that we need to print 'after' lines */
  378. print_n_lines_after = lines_after;
  379. #endif
  380. if (option_mask32 & OPT_o) {
  381. if (FGREP_FLAG) {
  382. /* -Fo just prints the pattern
  383. * (unless -v: -Fov doesnt print anything at all) */
  384. if (found)
  385. print_line(gl->pattern, strlen(gl->pattern), linenum, ':');
  386. } else while (1) {
  387. unsigned end = gl->matched_range.rm_eo;
  388. char old = line[end];
  389. line[end] = '\0';
  390. print_line(line + gl->matched_range.rm_so,
  391. end - gl->matched_range.rm_so,
  392. linenum, ':');
  393. if (old == '\0')
  394. break;
  395. line[end] = old;
  396. #if !ENABLE_EXTRA_COMPAT
  397. if (regexec(&gl->compiled_regex, line + end,
  398. 1, &gl->matched_range, REG_NOTBOL) != 0)
  399. break;
  400. gl->matched_range.rm_so += end;
  401. gl->matched_range.rm_eo += end;
  402. #else
  403. if (re_search(&gl->compiled_regex, line, line_len,
  404. end, line_len - end,
  405. &gl->matched_range) < 0)
  406. break;
  407. #endif
  408. }
  409. } else {
  410. print_line(line, line_len, linenum, ':');
  411. }
  412. }
  413. }
  414. #if ENABLE_FEATURE_GREP_CONTEXT
  415. else { /* no match */
  416. /* if we need to print some context lines after the last match, do so */
  417. if (print_n_lines_after) {
  418. print_line(line, strlen(line), linenum, '-');
  419. print_n_lines_after--;
  420. } else if (lines_before) {
  421. /* Add the line to the circular 'before' buffer */
  422. free(before_buf[curpos]);
  423. before_buf[curpos] = line;
  424. IF_EXTRA_COMPAT(before_buf_size[curpos] = line_len;)
  425. curpos = (curpos + 1) % lines_before;
  426. /* avoid free(line) - we took the line */
  427. line = NULL;
  428. }
  429. }
  430. #endif /* ENABLE_FEATURE_GREP_CONTEXT */
  431. #if !ENABLE_EXTRA_COMPAT
  432. free(line);
  433. #endif
  434. /* Did we print all context after last requested match? */
  435. if ((option_mask32 & OPT_m)
  436. && !print_n_lines_after
  437. && nmatches == max_matches
  438. ) {
  439. break;
  440. }
  441. } /* while (read line) */
  442. /* special-case file post-processing for options where we don't print line
  443. * matches, just filenames and possibly match counts */
  444. /* grep -c: print [filename:]count, even if count is zero */
  445. if (PRINT_MATCH_COUNTS) {
  446. if (print_filename)
  447. printf("%s:", cur_file);
  448. printf("%d\n", nmatches);
  449. }
  450. /* grep -L: print just the filename */
  451. if (PRINT_FILES_WITHOUT_MATCHES) {
  452. /* nmatches is zero, no need to check it:
  453. * we return 1 early if we detected a match
  454. * and PRINT_FILES_WITHOUT_MATCHES is set */
  455. puts(cur_file);
  456. }
  457. return nmatches;
  458. }
  459. #if ENABLE_FEATURE_CLEAN_UP
  460. #define new_grep_list_data(p, m) add_grep_list_data(p, m)
  461. static char *add_grep_list_data(char *pattern, int flg_used_mem)
  462. #else
  463. #define new_grep_list_data(p, m) add_grep_list_data(p)
  464. static char *add_grep_list_data(char *pattern)
  465. #endif
  466. {
  467. grep_list_data_t *gl = xzalloc(sizeof(*gl));
  468. gl->pattern = pattern;
  469. #if ENABLE_FEATURE_CLEAN_UP
  470. gl->flg_mem_alocated_compiled = flg_used_mem;
  471. #else
  472. /*gl->flg_mem_alocated_compiled = 0;*/
  473. #endif
  474. return (char *)gl;
  475. }
  476. static void load_regexes_from_file(llist_t *fopt)
  477. {
  478. char *line;
  479. FILE *f;
  480. while (fopt) {
  481. llist_t *cur = fopt;
  482. char *ffile = cur->data;
  483. fopt = cur->link;
  484. free(cur);
  485. f = xfopen_stdin(ffile);
  486. while ((line = xmalloc_fgetline(f)) != NULL) {
  487. llist_add_to(&pattern_head,
  488. new_grep_list_data(line, ALLOCATED));
  489. }
  490. }
  491. }
  492. static int FAST_FUNC file_action_grep(const char *filename,
  493. struct stat *statbuf UNUSED_PARAM,
  494. void* matched,
  495. int depth UNUSED_PARAM)
  496. {
  497. FILE *file = fopen_for_read(filename);
  498. if (file == NULL) {
  499. if (!SUPPRESS_ERR_MSGS)
  500. bb_simple_perror_msg(filename);
  501. open_errors = 1;
  502. return 0;
  503. }
  504. cur_file = filename;
  505. *(int*)matched += grep_file(file);
  506. fclose(file);
  507. return 1;
  508. }
  509. static int grep_dir(const char *dir)
  510. {
  511. int matched = 0;
  512. recursive_action(dir,
  513. /* recurse=yes */ ACTION_RECURSE |
  514. /* followLinks=no */
  515. /* depthFirst=yes */ ACTION_DEPTHFIRST,
  516. /* fileAction= */ file_action_grep,
  517. /* dirAction= */ NULL,
  518. /* userData= */ &matched,
  519. /* depth= */ 0);
  520. return matched;
  521. }
  522. int grep_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  523. int grep_main(int argc UNUSED_PARAM, char **argv)
  524. {
  525. FILE *file;
  526. int matched;
  527. llist_t *fopt = NULL;
  528. /* do normal option parsing */
  529. #if ENABLE_FEATURE_GREP_CONTEXT
  530. int Copt;
  531. /* -H unsets -h; -C unsets -A,-B; -e,-f are lists;
  532. * -m,-A,-B,-C have numeric param */
  533. opt_complementary = "H-h:C-AB:e::f::m+:A+:B+:C+";
  534. getopt32(argv,
  535. OPTSTR_GREP,
  536. &pattern_head, &fopt, &max_matches,
  537. &lines_after, &lines_before, &Copt);
  538. if (option_mask32 & OPT_C) {
  539. /* -C unsets prev -A and -B, but following -A or -B
  540. may override it */
  541. if (!(option_mask32 & OPT_A)) /* not overridden */
  542. lines_after = Copt;
  543. if (!(option_mask32 & OPT_B)) /* not overridden */
  544. lines_before = Copt;
  545. }
  546. /* sanity checks */
  547. if (option_mask32 & (OPT_c|OPT_q|OPT_l|OPT_L)) {
  548. option_mask32 &= ~OPT_n;
  549. lines_before = 0;
  550. lines_after = 0;
  551. } else if (lines_before > 0) {
  552. before_buf = xzalloc(lines_before * sizeof(before_buf[0]));
  553. IF_EXTRA_COMPAT(before_buf_size = xzalloc(lines_before * sizeof(before_buf_size[0]));)
  554. }
  555. #else
  556. /* with auto sanity checks */
  557. /* -H unsets -h; -c,-q or -l unset -n; -e,-f are lists; -m N */
  558. opt_complementary = "H-h:c-n:q-n:l-n:e::f::m+";
  559. getopt32(argv, OPTSTR_GREP,
  560. &pattern_head, &fopt, &max_matches);
  561. #endif
  562. invert_search = ((option_mask32 & OPT_v) != 0); /* 0 | 1 */
  563. if (pattern_head != NULL) {
  564. /* convert char **argv to grep_list_data_t */
  565. llist_t *cur;
  566. for (cur = pattern_head; cur; cur = cur->link)
  567. cur->data = new_grep_list_data(cur->data, 0);
  568. }
  569. if (option_mask32 & OPT_f)
  570. load_regexes_from_file(fopt);
  571. if (ENABLE_FEATURE_GREP_FGREP_ALIAS && applet_name[0] == 'f')
  572. option_mask32 |= OPT_F;
  573. #if !ENABLE_EXTRA_COMPAT
  574. if (!(option_mask32 & (OPT_o | OPT_w)))
  575. reflags = REG_NOSUB;
  576. #endif
  577. if (ENABLE_FEATURE_GREP_EGREP_ALIAS
  578. && (applet_name[0] == 'e' || (option_mask32 & OPT_E))
  579. ) {
  580. reflags |= REG_EXTENDED;
  581. }
  582. #if ENABLE_EXTRA_COMPAT
  583. else {
  584. reflags = RE_SYNTAX_GREP;
  585. }
  586. #endif
  587. if (option_mask32 & OPT_i) {
  588. #if !ENABLE_EXTRA_COMPAT
  589. reflags |= REG_ICASE;
  590. #else
  591. int i;
  592. case_fold = xmalloc(256);
  593. for (i = 0; i < 256; i++)
  594. case_fold[i] = (unsigned char)i;
  595. for (i = 'a'; i <= 'z'; i++)
  596. case_fold[i] = (unsigned char)(i - ('a' - 'A'));
  597. #endif
  598. }
  599. argv += optind;
  600. /* if we didn't get a pattern from -e and no command file was specified,
  601. * first parameter should be the pattern. no pattern, no worky */
  602. if (pattern_head == NULL) {
  603. char *pattern;
  604. if (*argv == NULL)
  605. bb_show_usage();
  606. pattern = new_grep_list_data(*argv++, 0);
  607. llist_add_to(&pattern_head, pattern);
  608. }
  609. /* argv[0..(argc-1)] should be names of file to grep through. If
  610. * there is more than one file to grep, we will print the filenames. */
  611. if (argv[0] && argv[1])
  612. print_filename = 1;
  613. /* -H / -h of course override */
  614. if (option_mask32 & OPT_H)
  615. print_filename = 1;
  616. if (option_mask32 & OPT_h)
  617. print_filename = 0;
  618. /* If no files were specified, or '-' was specified, take input from
  619. * stdin. Otherwise, we grep through all the files specified. */
  620. matched = 0;
  621. do {
  622. cur_file = *argv;
  623. file = stdin;
  624. if (!cur_file || LONE_DASH(cur_file)) {
  625. cur_file = "(standard input)";
  626. } else {
  627. if (option_mask32 & OPT_r) {
  628. struct stat st;
  629. if (stat(cur_file, &st) == 0 && S_ISDIR(st.st_mode)) {
  630. if (!(option_mask32 & OPT_h))
  631. print_filename = 1;
  632. matched += grep_dir(cur_file);
  633. goto grep_done;
  634. }
  635. }
  636. /* else: fopen(dir) will succeed, but reading won't */
  637. file = fopen_for_read(cur_file);
  638. if (file == NULL) {
  639. if (!SUPPRESS_ERR_MSGS)
  640. bb_simple_perror_msg(cur_file);
  641. open_errors = 1;
  642. continue;
  643. }
  644. }
  645. matched += grep_file(file);
  646. fclose_if_not_stdin(file);
  647. grep_done: ;
  648. } while (*argv && *++argv);
  649. /* destroy all the elments in the pattern list */
  650. if (ENABLE_FEATURE_CLEAN_UP) {
  651. while (pattern_head) {
  652. llist_t *pattern_head_ptr = pattern_head;
  653. grep_list_data_t *gl = (grep_list_data_t *)pattern_head_ptr->data;
  654. pattern_head = pattern_head->link;
  655. if (gl->flg_mem_alocated_compiled & ALLOCATED)
  656. free(gl->pattern);
  657. if (gl->flg_mem_alocated_compiled & COMPILED)
  658. regfree(&gl->compiled_regex);
  659. free(gl);
  660. free(pattern_head_ptr);
  661. }
  662. }
  663. /* 0 = success, 1 = failed, 2 = error */
  664. if (open_errors)
  665. return 2;
  666. return !matched; /* invert return value: 0 = success, 1 = failed */
  667. }