grep.c 19 KB

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