grep.c 25 KB

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