grep.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. */
  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:Lor" \
  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,
  34. OPTBIT_n,
  35. OPTBIT_q,
  36. OPTBIT_v,
  37. OPTBIT_s,
  38. OPTBIT_c,
  39. OPTBIT_F,
  40. OPTBIT_i,
  41. OPTBIT_H,
  42. OPTBIT_h,
  43. OPTBIT_e,
  44. OPTBIT_f,
  45. OPTBIT_L,
  46. OPTBIT_o,
  47. OPTBIT_r,
  48. USE_FEATURE_GREP_CONTEXT( OPTBIT_A ,)
  49. USE_FEATURE_GREP_CONTEXT( OPTBIT_B ,)
  50. USE_FEATURE_GREP_CONTEXT( OPTBIT_C ,)
  51. USE_FEATURE_GREP_EGREP_ALIAS(OPTBIT_E ,)
  52. USE_DESKTOP( OPTBIT_w ,)
  53. OPT_l = 1 << OPTBIT_l,
  54. OPT_n = 1 << OPTBIT_n,
  55. OPT_q = 1 << OPTBIT_q,
  56. OPT_v = 1 << OPTBIT_v,
  57. OPT_s = 1 << OPTBIT_s,
  58. OPT_c = 1 << OPTBIT_c,
  59. OPT_F = 1 << OPTBIT_F,
  60. OPT_i = 1 << OPTBIT_i,
  61. OPT_H = 1 << OPTBIT_H,
  62. OPT_h = 1 << OPTBIT_h,
  63. OPT_e = 1 << OPTBIT_e,
  64. OPT_f = 1 << OPTBIT_f,
  65. OPT_L = 1 << OPTBIT_L,
  66. OPT_o = 1 << OPTBIT_o,
  67. OPT_r = 1 << OPTBIT_r,
  68. OPT_A = USE_FEATURE_GREP_CONTEXT( (1 << OPTBIT_A)) + 0,
  69. OPT_B = USE_FEATURE_GREP_CONTEXT( (1 << OPTBIT_B)) + 0,
  70. OPT_C = USE_FEATURE_GREP_CONTEXT( (1 << OPTBIT_C)) + 0,
  71. OPT_E = USE_FEATURE_GREP_EGREP_ALIAS((1 << OPTBIT_E)) + 0,
  72. OPT_w = USE_DESKTOP( (1 << OPTBIT_w)) + 0,
  73. };
  74. #define PRINT_FILES_WITH_MATCHES (option_mask32 & OPT_l)
  75. #define PRINT_LINE_NUM (option_mask32 & OPT_n)
  76. #define BE_QUIET (option_mask32 & OPT_q)
  77. #define SUPPRESS_ERR_MSGS (option_mask32 & OPT_s)
  78. #define PRINT_MATCH_COUNTS (option_mask32 & OPT_c)
  79. #define FGREP_FLAG (option_mask32 & OPT_F)
  80. #define PRINT_FILES_WITHOUT_MATCHES (option_mask32 & OPT_L)
  81. typedef unsigned char byte_t;
  82. static int reflags;
  83. static byte_t invert_search;
  84. static byte_t print_filename;
  85. static byte_t open_errors;
  86. #if ENABLE_FEATURE_GREP_CONTEXT
  87. static int lines_before;
  88. static int lines_after;
  89. static char **before_buf;
  90. static int last_line_printed;
  91. #endif /* ENABLE_FEATURE_GREP_CONTEXT */
  92. /* globals used internally */
  93. static llist_t *pattern_head; /* growable list of patterns to match */
  94. static const char *cur_file; /* the current file we are reading */
  95. typedef struct grep_list_data_t {
  96. char *pattern;
  97. regex_t preg;
  98. #define PATTERN_MEM_A 1
  99. #define COMPILED 2
  100. int flg_mem_alocated_compiled;
  101. } grep_list_data_t;
  102. static void print_line(const char *line, int linenum, char decoration)
  103. {
  104. #if ENABLE_FEATURE_GREP_CONTEXT
  105. /* possibly print the little '--' separator */
  106. if ((lines_before || lines_after) && last_line_printed &&
  107. last_line_printed < linenum - 1) {
  108. puts("--");
  109. }
  110. last_line_printed = linenum;
  111. #endif
  112. if (print_filename)
  113. printf("%s%c", cur_file, decoration);
  114. if (PRINT_LINE_NUM)
  115. printf("%i%c", linenum, decoration);
  116. /* Emulate weird GNU grep behavior with -ov */
  117. if ((option_mask32 & (OPT_v+OPT_o)) != (OPT_v+OPT_o))
  118. puts(line);
  119. }
  120. static int grep_file(FILE *file)
  121. {
  122. char *line;
  123. byte_t ret;
  124. int linenum = 0;
  125. int nmatches = 0;
  126. regmatch_t regmatch;
  127. #if ENABLE_FEATURE_GREP_CONTEXT
  128. int print_n_lines_after = 0;
  129. int curpos = 0; /* track where we are in the circular 'before' buffer */
  130. int idx = 0; /* used for iteration through the circular buffer */
  131. #endif /* ENABLE_FEATURE_GREP_CONTEXT */
  132. while ((line = xmalloc_getline(file)) != NULL) {
  133. llist_t *pattern_ptr = pattern_head;
  134. grep_list_data_t * gl;
  135. linenum++;
  136. ret = 0;
  137. while (pattern_ptr) {
  138. gl = (grep_list_data_t *)pattern_ptr->data;
  139. if (FGREP_FLAG) {
  140. ret = strstr(line, gl->pattern) != NULL;
  141. } else {
  142. /*
  143. * test for a postitive-assertion match (regexec returns success (0)
  144. * and the user did not specify invert search), or a negative-assertion
  145. * match (regexec returns failure (REG_NOMATCH) and the user specified
  146. * invert search)
  147. */
  148. if (!(gl->flg_mem_alocated_compiled & COMPILED)) {
  149. gl->flg_mem_alocated_compiled |= COMPILED;
  150. xregcomp(&(gl->preg), gl->pattern, reflags);
  151. }
  152. regmatch.rm_so = 0;
  153. regmatch.rm_eo = 0;
  154. if (regexec(&(gl->preg), line, 1, &regmatch, 0) == 0) {
  155. if (!(option_mask32 & OPT_w))
  156. ret = 1;
  157. else {
  158. char c = ' ';
  159. if (regmatch.rm_so)
  160. c = line[regmatch.rm_so - 1];
  161. if (!isalnum(c) && c != '_') {
  162. c = line[regmatch.rm_eo];
  163. if (!c || (!isalnum(c) && c != '_'))
  164. ret = 1;
  165. }
  166. }
  167. }
  168. }
  169. pattern_ptr = pattern_ptr->link;
  170. } /* while (pattern_ptr) */
  171. if (ret ^ invert_search) {
  172. if (PRINT_FILES_WITH_MATCHES || BE_QUIET)
  173. free(line);
  174. /* if we found a match but were told to be quiet, stop here */
  175. if (BE_QUIET || PRINT_FILES_WITHOUT_MATCHES)
  176. return -1;
  177. /* keep track of matches */
  178. nmatches++;
  179. /* if we're just printing filenames, we stop after the first match */
  180. if (PRINT_FILES_WITH_MATCHES)
  181. break;
  182. /* print the matched line */
  183. if (PRINT_MATCH_COUNTS == 0) {
  184. #if ENABLE_FEATURE_GREP_CONTEXT
  185. int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
  186. /* if we were told to print 'before' lines and there is at least
  187. * one line in the circular buffer, print them */
  188. if (lines_before && before_buf[prevpos] != NULL) {
  189. int first_buf_entry_line_num = linenum - lines_before;
  190. /* advance to the first entry in the circular buffer, and
  191. * figure out the line number is of the first line in the
  192. * buffer */
  193. idx = curpos;
  194. while (before_buf[idx] == NULL) {
  195. idx = (idx + 1) % lines_before;
  196. first_buf_entry_line_num++;
  197. }
  198. /* now print each line in the buffer, clearing them as we go */
  199. while (before_buf[idx] != NULL) {
  200. print_line(before_buf[idx], first_buf_entry_line_num, '-');
  201. free(before_buf[idx]);
  202. before_buf[idx] = NULL;
  203. idx = (idx + 1) % lines_before;
  204. first_buf_entry_line_num++;
  205. }
  206. }
  207. /* make a note that we need to print 'after' lines */
  208. print_n_lines_after = lines_after;
  209. #endif
  210. if (option_mask32 & OPT_o) {
  211. line[regmatch.rm_eo] = '\0';
  212. print_line(line + regmatch.rm_so, linenum, ':');
  213. } else {
  214. print_line(line, linenum, ':');
  215. }
  216. }
  217. }
  218. #if ENABLE_FEATURE_GREP_CONTEXT
  219. else { /* no match */
  220. /* Add the line to the circular 'before' buffer */
  221. if (lines_before) {
  222. free(before_buf[curpos]);
  223. before_buf[curpos] = xstrdup(line);
  224. curpos = (curpos + 1) % lines_before;
  225. }
  226. }
  227. /* if we need to print some context lines after the last match, do so */
  228. if (print_n_lines_after && (last_line_printed != linenum)) {
  229. print_line(line, linenum, '-');
  230. print_n_lines_after--;
  231. }
  232. #endif /* ENABLE_FEATURE_GREP_CONTEXT */
  233. free(line);
  234. }
  235. /* special-case file post-processing for options where we don't print line
  236. * matches, just filenames and possibly match counts */
  237. /* grep -c: print [filename:]count, even if count is zero */
  238. if (PRINT_MATCH_COUNTS) {
  239. if (print_filename)
  240. printf("%s:", cur_file);
  241. printf("%d\n", nmatches);
  242. }
  243. /* grep -l: print just the filename, but only if we grepped the line in the file */
  244. if (PRINT_FILES_WITH_MATCHES && nmatches > 0) {
  245. puts(cur_file);
  246. }
  247. /* grep -L: print just the filename, but only if we didn't grep the line in the file */
  248. if (PRINT_FILES_WITHOUT_MATCHES && nmatches == 0) {
  249. puts(cur_file);
  250. }
  251. return nmatches;
  252. }
  253. #if ENABLE_FEATURE_CLEAN_UP
  254. #define new_grep_list_data(p, m) add_grep_list_data(p, m)
  255. static char * add_grep_list_data(char *pattern, int flg_used_mem)
  256. #else
  257. #define new_grep_list_data(p, m) add_grep_list_data(p)
  258. static char * add_grep_list_data(char *pattern)
  259. #endif
  260. {
  261. grep_list_data_t *gl = xmalloc(sizeof(grep_list_data_t));
  262. gl->pattern = pattern;
  263. #if ENABLE_FEATURE_CLEAN_UP
  264. gl->flg_mem_alocated_compiled = flg_used_mem;
  265. #else
  266. gl->flg_mem_alocated_compiled = 0;
  267. #endif
  268. return (char *)gl;
  269. }
  270. static void load_regexes_from_file(llist_t *fopt)
  271. {
  272. char *line;
  273. FILE *f;
  274. while (fopt) {
  275. llist_t *cur = fopt;
  276. char *ffile = cur->data;
  277. fopt = cur->link;
  278. free(cur);
  279. f = xfopen(ffile, "r");
  280. while ((line = xmalloc_getline(f)) != NULL) {
  281. llist_add_to(&pattern_head,
  282. new_grep_list_data(line, PATTERN_MEM_A));
  283. }
  284. }
  285. }
  286. static int file_action_grep(const char *filename, struct stat *statbuf, void* matched, int depth)
  287. {
  288. FILE *file = fopen(filename, "r");
  289. if (file == NULL) {
  290. if (!SUPPRESS_ERR_MSGS)
  291. bb_perror_msg("%s", cur_file);
  292. open_errors = 1;
  293. return 0;
  294. }
  295. cur_file = filename;
  296. *(int*)matched += grep_file(file);
  297. fclose(file);
  298. return 1;
  299. }
  300. static int grep_dir(const char *dir)
  301. {
  302. int matched = 0;
  303. recursive_action(dir,
  304. /* recurse=yes */ ACTION_RECURSE |
  305. /* followLinks=no */
  306. /* depthFirst=yes */ ACTION_DEPTHFIRST,
  307. /* fileAction= */ file_action_grep,
  308. /* dirAction= */ NULL,
  309. /* userData= */ &matched,
  310. /* depth= */ 0);
  311. return matched;
  312. }
  313. int grep_main(int argc, char **argv);
  314. int grep_main(int argc, char **argv)
  315. {
  316. FILE *file;
  317. int matched;
  318. llist_t *fopt = NULL;
  319. /* do normal option parsing */
  320. #if ENABLE_FEATURE_GREP_CONTEXT
  321. char *slines_after;
  322. char *slines_before;
  323. char *Copt;
  324. opt_complementary = "H-h:e::f::C-AB";
  325. getopt32(argc, argv,
  326. OPTSTR_GREP,
  327. &pattern_head, &fopt,
  328. &slines_after, &slines_before, &Copt);
  329. if (option_mask32 & OPT_C) {
  330. /* -C unsets prev -A and -B, but following -A or -B
  331. may override it */
  332. if (!(option_mask32 & OPT_A)) /* not overridden */
  333. slines_after = Copt;
  334. if (!(option_mask32 & OPT_B)) /* not overridden */
  335. slines_before = Copt;
  336. option_mask32 |= OPT_A|OPT_B; /* for parser */
  337. }
  338. if (option_mask32 & OPT_A) {
  339. lines_after = xatoi_u(slines_after);
  340. }
  341. if (option_mask32 & OPT_B) {
  342. lines_before = xatoi_u(slines_before);
  343. }
  344. /* sanity checks */
  345. if (option_mask32 & (OPT_c|OPT_q|OPT_l|OPT_L)) {
  346. option_mask32 &= ~OPT_n;
  347. lines_before = 0;
  348. lines_after = 0;
  349. } else if (lines_before > 0)
  350. before_buf = xzalloc(lines_before * sizeof(char *));
  351. #else
  352. /* with auto sanity checks */
  353. opt_complementary = "H-h:e::f::c-n:q-n:l-n";
  354. getopt32(argc, argv, OPTSTR_GREP,
  355. &pattern_head, &fopt);
  356. #endif
  357. invert_search = ((option_mask32 & OPT_v) != 0); /* 0 | 1 */
  358. if (pattern_head != NULL) {
  359. /* convert char **argv to grep_list_data_t */
  360. llist_t *cur;
  361. for (cur = pattern_head; cur; cur = cur->link)
  362. cur->data = new_grep_list_data(cur->data, 0);
  363. }
  364. if (option_mask32 & OPT_f)
  365. load_regexes_from_file(fopt);
  366. if (ENABLE_FEATURE_GREP_FGREP_ALIAS && applet_name[0] == 'f')
  367. option_mask32 |= OPT_F;
  368. if (!(option_mask32 & (OPT_o | OPT_w)))
  369. reflags = REG_NOSUB;
  370. if (ENABLE_FEATURE_GREP_EGREP_ALIAS &&
  371. (applet_name[0] == 'e' || (option_mask32 & OPT_E)))
  372. reflags |= REG_EXTENDED;
  373. if (option_mask32 & OPT_i)
  374. reflags |= REG_ICASE;
  375. argv += optind;
  376. argc -= optind;
  377. /* if we didn't get a pattern from a -e and no command file was specified,
  378. * argv[optind] should be the pattern. no pattern, no worky */
  379. if (pattern_head == NULL) {
  380. char *pattern;
  381. if (*argv == NULL)
  382. bb_show_usage();
  383. pattern = new_grep_list_data(*argv++, 0);
  384. llist_add_to(&pattern_head, pattern);
  385. argc--;
  386. }
  387. /* argv[(optind)..(argc-1)] should be names of file to grep through. If
  388. * there is more than one file to grep, we will print the filenames. */
  389. if (argc > 1)
  390. print_filename = 1;
  391. /* -H / -h of course override */
  392. if (option_mask32 & OPT_H)
  393. print_filename = 1;
  394. if (option_mask32 & OPT_h)
  395. print_filename = 0;
  396. /* If no files were specified, or '-' was specified, take input from
  397. * stdin. Otherwise, we grep through all the files specified. */
  398. if (argc == 0)
  399. argc++;
  400. matched = 0;
  401. while (argc--) {
  402. cur_file = *argv++;
  403. file = stdin;
  404. if (!cur_file || (*cur_file == '-' && !cur_file[1])) {
  405. cur_file = "(standard input)";
  406. } else {
  407. if (option_mask32 & OPT_r) {
  408. struct stat st;
  409. if (stat(cur_file, &st) == 0 && S_ISDIR(st.st_mode)) {
  410. if (!(option_mask32 & OPT_h))
  411. print_filename = 1;
  412. matched += grep_dir(cur_file);
  413. goto grep_done;
  414. }
  415. }
  416. /* else: fopen(dir) will succeed, but reading won't */
  417. file = fopen(cur_file, "r");
  418. if (file == NULL) {
  419. if (!SUPPRESS_ERR_MSGS)
  420. bb_perror_msg("%s", cur_file);
  421. open_errors = 1;
  422. continue;
  423. }
  424. }
  425. matched += grep_file(file);
  426. fclose_if_not_stdin(file);
  427. grep_done:
  428. if (matched < 0) {
  429. /* we found a match but were told to be quiet, stop here and
  430. * return success */
  431. break;
  432. }
  433. }
  434. /* destroy all the elments in the pattern list */
  435. if (ENABLE_FEATURE_CLEAN_UP) {
  436. while (pattern_head) {
  437. llist_t *pattern_head_ptr = pattern_head;
  438. grep_list_data_t *gl =
  439. (grep_list_data_t *)pattern_head_ptr->data;
  440. pattern_head = pattern_head->link;
  441. if ((gl->flg_mem_alocated_compiled & PATTERN_MEM_A))
  442. free(gl->pattern);
  443. if ((gl->flg_mem_alocated_compiled & COMPILED))
  444. regfree(&(gl->preg));
  445. free(gl);
  446. free(pattern_head_ptr);
  447. }
  448. }
  449. /* 0 = success, 1 = failed, 2 = error */
  450. /* If the -q option is specified, the exit status shall be zero
  451. * if an input line is selected, even if an error was detected. */
  452. if (BE_QUIET && matched)
  453. return 0;
  454. if (open_errors)
  455. return 2;
  456. return !matched; /* invert return value 0 = success, 1 = failed */
  457. }