grep.c 23 KB

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