grep.c 25 KB

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