/[pcre]/code/trunk/pcregrep.c
ViewVC logotype

Diff of /code/trunk/pcregrep.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 586 by ph10, Wed Jan 12 17:36:47 2011 UTC revision 1355 by ph10, Tue Aug 13 17:34:02 2013 UTC
# Line 3  Line 3 
3  *************************************************/  *************************************************/
4    
5  /* This is a grep program that uses the PCRE regular expression library to do  /* This is a grep program that uses the PCRE regular expression library to do
6  its pattern matching. On a Unix or Win32 system it can recurse into  its pattern matching. On Unix-like, Windows, and native z/OS systems it can
7  directories.  recurse into directories, and in z/OS it can handle PDS files.
8    
9             Copyright (c) 1997-2011 University of Cambridge  Note that for native z/OS, in addition to defining the NATIVE_ZOS macro, an
10    additional header is required. That header is not included in the main PCRE
11    distribution because other apparatus is needed to compile pcregrep for z/OS.
12    The header can be found in the special z/OS distribution, which is available
13    from www.zaconsultants.net or from www.cbttape.org.
14    
15               Copyright (c) 1997-2013 University of Cambridge
16    
17  -----------------------------------------------------------------------------  -----------------------------------------------------------------------------
18  Redistribution and use in source and binary forms, with or without  Redistribution and use in source and binary forms, with or without
# Line 70  POSSIBILITY OF SUCH DAMAGE. Line 76  POSSIBILITY OF SUCH DAMAGE.
76    
77  typedef int BOOL;  typedef int BOOL;
78    
 #define MAX_PATTERN_COUNT 100  
79  #define OFFSET_SIZE 99  #define OFFSET_SIZE 99
80    
81  #if BUFSIZ > 8192  #if BUFSIZ > 8192
82  #define MBUFTHIRD BUFSIZ  #define MAXPATLEN BUFSIZ
83  #else  #else
84  #define MBUFTHIRD 8192  #define MAXPATLEN 8192
85  #endif  #endif
86    
87    #define PATBUFSIZE (MAXPATLEN + 10)   /* Allows for prefix+suffix */
88    
89  /* Values for the "filenames" variable, which specifies options for file name  /* Values for the "filenames" variable, which specifies options for file name
90  output. The order is important; it is assumed that a file name is wanted for  output. The order is important; it is assumed that a file name is wanted for
91  all values greater than FN_DEFAULT. */  all values greater than FN_DEFAULT. */
# Line 104  enum { DEE_READ, DEE_SKIP }; Line 111  enum { DEE_READ, DEE_SKIP };
111    
112  enum { EL_LF, EL_CR, EL_CRLF, EL_ANY, EL_ANYCRLF };  enum { EL_LF, EL_CR, EL_CRLF, EL_ANY, EL_ANYCRLF };
113    
114    /* Binary file options */
115    
116    enum { BIN_BINARY, BIN_NOMATCH, BIN_TEXT };
117    
118  /* In newer versions of gcc, with FORTIFY_SOURCE set (the default in some  /* In newer versions of gcc, with FORTIFY_SOURCE set (the default in some
119  environments), a warning is issued if the value of fwrite() is ignored.  environments), a warning is issued if the value of fwrite() is ignored.
120  Unfortunately, casting to (void) does not suppress the warning. To get round  Unfortunately, casting to (void) does not suppress the warning. To get round
# Line 135  static char *colour_string = (char *)"1; Line 146  static char *colour_string = (char *)"1;
146  static char *colour_option = NULL;  static char *colour_option = NULL;
147  static char *dee_option = NULL;  static char *dee_option = NULL;
148  static char *DEE_option = NULL;  static char *DEE_option = NULL;
149    static char *locale = NULL;
150    static char *main_buffer = NULL;
151  static char *newline = NULL;  static char *newline = NULL;
152  static char *pattern_filename = NULL;  static char *om_separator = (char *)"";
153  static char *stdin_name = (char *)"(standard input)";  static char *stdin_name = (char *)"(standard input)";
 static char *locale = NULL;  
154    
155  static const unsigned char *pcretables = NULL;  static const unsigned char *pcretables = NULL;
156    
 static int  pattern_count = 0;  
 static pcre **pattern_list = NULL;  
 static pcre_extra **hints_list = NULL;  
   
 static char *include_pattern = NULL;  
 static char *exclude_pattern = NULL;  
 static char *include_dir_pattern = NULL;  
 static char *exclude_dir_pattern = NULL;  
   
 static pcre *include_compiled = NULL;  
 static pcre *exclude_compiled = NULL;  
 static pcre *include_dir_compiled = NULL;  
 static pcre *exclude_dir_compiled = NULL;  
   
157  static int after_context = 0;  static int after_context = 0;
158  static int before_context = 0;  static int before_context = 0;
159    static int binary_files = BIN_BINARY;
160  static int both_context = 0;  static int both_context = 0;
161    static int bufthird = PCREGREP_BUFSIZE;
162    static int bufsize = 3*PCREGREP_BUFSIZE;
163    
164    #if defined HAVE_WINDOWS_H && HAVE_WINDOWS_H
165    static int dee_action = dee_SKIP;
166    #else
167  static int dee_action = dee_READ;  static int dee_action = dee_READ;
168    #endif
169    
170  static int DEE_action = DEE_READ;  static int DEE_action = DEE_READ;
171  static int error_count = 0;  static int error_count = 0;
172  static int filenames = FN_DEFAULT;  static int filenames = FN_DEFAULT;
173  static int only_matching = -1;  static int pcre_options = 0;
174  static int process_options = 0;  static int process_options = 0;
175    
176    #ifdef SUPPORT_PCREGREP_JIT
177    static int study_options = PCRE_STUDY_JIT_COMPILE;
178    #else
179    static int study_options = 0;
180    #endif
181    
182  static unsigned long int match_limit = 0;  static unsigned long int match_limit = 0;
183  static unsigned long int match_limit_recursion = 0;  static unsigned long int match_limit_recursion = 0;
184    
# Line 181  static BOOL number = FALSE; Line 194  static BOOL number = FALSE;
194  static BOOL omit_zero_count = FALSE;  static BOOL omit_zero_count = FALSE;
195  static BOOL resource_error = FALSE;  static BOOL resource_error = FALSE;
196  static BOOL quiet = FALSE;  static BOOL quiet = FALSE;
197    static BOOL show_only_matching = FALSE;
198  static BOOL silent = FALSE;  static BOOL silent = FALSE;
199  static BOOL utf8 = FALSE;  static BOOL utf8 = FALSE;
200    
201    /* Structure for list of --only-matching capturing numbers. */
202    
203    typedef struct omstr {
204      struct omstr *next;
205      int groupnum;
206    } omstr;
207    
208    static omstr *only_matching = NULL;
209    static omstr *only_matching_last = NULL;
210    
211    /* Structure for holding the two variables that describe a number chain. */
212    
213    typedef struct omdatastr {
214      omstr **anchor;
215      omstr **lastptr;
216    } omdatastr;
217    
218    static omdatastr only_matching_data = { &only_matching, &only_matching_last };
219    
220    /* Structure for list of file names (for -f and --{in,ex}clude-from) */
221    
222    typedef struct fnstr {
223      struct fnstr *next;
224      char *name;
225    } fnstr;
226    
227    static fnstr *exclude_from = NULL;
228    static fnstr *exclude_from_last = NULL;
229    static fnstr *include_from = NULL;
230    static fnstr *include_from_last = NULL;
231    
232    static fnstr *file_lists = NULL;
233    static fnstr *file_lists_last = NULL;
234    static fnstr *pattern_files = NULL;
235    static fnstr *pattern_files_last = NULL;
236    
237    /* Structure for holding the two variables that describe a file name chain. */
238    
239    typedef struct fndatastr {
240      fnstr **anchor;
241      fnstr **lastptr;
242    } fndatastr;
243    
244    static fndatastr exclude_from_data = { &exclude_from, &exclude_from_last };
245    static fndatastr include_from_data = { &include_from, &include_from_last };
246    static fndatastr file_lists_data = { &file_lists, &file_lists_last };
247    static fndatastr pattern_files_data = { &pattern_files, &pattern_files_last };
248    
249    /* Structure for pattern and its compiled form; used for matching patterns and
250    also for include/exclude patterns. */
251    
252    typedef struct patstr {
253      struct patstr *next;
254      char *string;
255      pcre *compiled;
256      pcre_extra *hint;
257    } patstr;
258    
259    static patstr *patterns = NULL;
260    static patstr *patterns_last = NULL;
261    static patstr *include_patterns = NULL;
262    static patstr *include_patterns_last = NULL;
263    static patstr *exclude_patterns = NULL;
264    static patstr *exclude_patterns_last = NULL;
265    static patstr *include_dir_patterns = NULL;
266    static patstr *include_dir_patterns_last = NULL;
267    static patstr *exclude_dir_patterns = NULL;
268    static patstr *exclude_dir_patterns_last = NULL;
269    
270    /* Structure holding the two variables that describe a pattern chain. A pointer
271    to such structures is used for each appropriate option. */
272    
273    typedef struct patdatastr {
274      patstr **anchor;
275      patstr **lastptr;
276    } patdatastr;
277    
278    static patdatastr match_patdata = { &patterns, &patterns_last };
279    static patdatastr include_patdata = { &include_patterns, &include_patterns_last };
280    static patdatastr exclude_patdata = { &exclude_patterns, &exclude_patterns_last };
281    static patdatastr include_dir_patdata = { &include_dir_patterns, &include_dir_patterns_last };
282    static patdatastr exclude_dir_patdata = { &exclude_dir_patterns, &exclude_dir_patterns_last };
283    
284    static patstr **incexlist[4] = { &include_patterns, &exclude_patterns,
285                                     &include_dir_patterns, &exclude_dir_patterns };
286    
287    static const char *incexname[4] = { "--include", "--exclude",
288                                        "--include-dir", "--exclude-dir" };
289    
290  /* Structure for options and list of them */  /* Structure for options and list of them */
291    
292  enum { OP_NODATA, OP_STRING, OP_OP_STRING, OP_NUMBER, OP_LONGNUMBER,  enum { OP_NODATA, OP_STRING, OP_OP_STRING, OP_NUMBER, OP_LONGNUMBER,
293         OP_OP_NUMBER, OP_PATLIST };         OP_OP_NUMBER, OP_OP_NUMBERS, OP_PATLIST, OP_FILELIST, OP_BINFILES };
294    
295  typedef struct option_item {  typedef struct option_item {
296    int type;    int type;
# Line 214  used to identify them. */ Line 317  used to identify them. */
317  #define N_LBUFFER      (-12)  #define N_LBUFFER      (-12)
318  #define N_M_LIMIT      (-13)  #define N_M_LIMIT      (-13)
319  #define N_M_LIMIT_REC  (-14)  #define N_M_LIMIT_REC  (-14)
320    #define N_BUFSIZE      (-15)
321    #define N_NOJIT        (-16)
322    #define N_FILE_LIST    (-17)
323    #define N_BINARY_FILES (-18)
324    #define N_EXCLUDE_FROM (-19)
325    #define N_INCLUDE_FROM (-20)
326    #define N_OM_SEPARATOR (-21)
327    
328  static option_item optionlist[] = {  static option_item optionlist[] = {
329    { OP_NODATA,     N_NULL,   NULL,              "",              "  terminate options" },    { OP_NODATA,     N_NULL,   NULL,              "",              "terminate options" },
330    { OP_NODATA,     N_HELP,   NULL,              "help",          "display this help and exit" },    { OP_NODATA,     N_HELP,   NULL,              "help",          "display this help and exit" },
331    { OP_NUMBER,     'A',      &after_context,    "after-context=number", "set number of following context lines" },    { OP_NUMBER,     'A',      &after_context,    "after-context=number", "set number of following context lines" },
332      { OP_NODATA,     'a',      NULL,              "text",          "treat binary files as text" },
333    { OP_NUMBER,     'B',      &before_context,   "before-context=number", "set number of prior context lines" },    { OP_NUMBER,     'B',      &before_context,   "before-context=number", "set number of prior context lines" },
334      { OP_BINFILES,   N_BINARY_FILES, NULL,        "binary-files=word", "set treatment of binary files" },
335      { OP_NUMBER,     N_BUFSIZE,&bufthird,         "buffer-size=number", "set processing buffer size parameter" },
336    { OP_OP_STRING,  N_COLOUR, &colour_option,    "color=option",  "matched text color option" },    { OP_OP_STRING,  N_COLOUR, &colour_option,    "color=option",  "matched text color option" },
337    { OP_OP_STRING,  N_COLOUR, &colour_option,    "colour=option", "matched text colour option" },    { OP_OP_STRING,  N_COLOUR, &colour_option,    "colour=option", "matched text colour option" },
338    { OP_NUMBER,     'C',      &both_context,     "context=number", "set number of context lines, before & after" },    { OP_NUMBER,     'C',      &both_context,     "context=number", "set number of context lines, before & after" },
339    { OP_NODATA,     'c',      NULL,              "count",         "print only a count of matching lines per FILE" },    { OP_NODATA,     'c',      NULL,              "count",         "print only a count of matching lines per FILE" },
340    { OP_STRING,     'D',      &DEE_option,       "devices=action","how to handle devices, FIFOs, and sockets" },    { OP_STRING,     'D',      &DEE_option,       "devices=action","how to handle devices, FIFOs, and sockets" },
341    { OP_STRING,     'd',      &dee_option,       "directories=action", "how to handle directories" },    { OP_STRING,     'd',      &dee_option,       "directories=action", "how to handle directories" },
342    { OP_PATLIST,    'e',      NULL,              "regex(p)=pattern", "specify pattern (may be used more than once)" },    { OP_PATLIST,    'e',      &match_patdata,    "regex(p)=pattern", "specify pattern (may be used more than once)" },
343    { OP_NODATA,     'F',      NULL,              "fixed-strings", "patterns are sets of newline-separated strings" },    { OP_NODATA,     'F',      NULL,              "fixed-strings", "patterns are sets of newline-separated strings" },
344    { OP_STRING,     'f',      &pattern_filename, "file=path",     "read patterns from file" },    { OP_FILELIST,   'f',      &pattern_files_data, "file=path",   "read patterns from file" },
345      { OP_FILELIST,   N_FILE_LIST, &file_lists_data, "file-list=path","read files to search from file" },
346    { OP_NODATA,     N_FOFFSETS, NULL,            "file-offsets",  "output file offsets, not text" },    { OP_NODATA,     N_FOFFSETS, NULL,            "file-offsets",  "output file offsets, not text" },
347    { OP_NODATA,     'H',      NULL,              "with-filename", "force the prefixing filename on output" },    { OP_NODATA,     'H',      NULL,              "with-filename", "force the prefixing filename on output" },
348    { OP_NODATA,     'h',      NULL,              "no-filename",   "suppress the prefixing filename on output" },    { OP_NODATA,     'h',      NULL,              "no-filename",   "suppress the prefixing filename on output" },
349      { OP_NODATA,     'I',      NULL,              "",              "treat binary files as not matching (ignore)" },
350    { OP_NODATA,     'i',      NULL,              "ignore-case",   "ignore case distinctions" },    { OP_NODATA,     'i',      NULL,              "ignore-case",   "ignore case distinctions" },
351    #ifdef SUPPORT_PCREGREP_JIT
352      { OP_NODATA,     N_NOJIT,  NULL,              "no-jit",        "do not use just-in-time compiler optimization" },
353    #else
354      { OP_NODATA,     N_NOJIT,  NULL,              "no-jit",        "ignored: this pcregrep does not support JIT" },
355    #endif
356    { OP_NODATA,     'l',      NULL,              "files-with-matches", "print only FILE names containing matches" },    { OP_NODATA,     'l',      NULL,              "files-with-matches", "print only FILE names containing matches" },
357    { OP_NODATA,     'L',      NULL,              "files-without-match","print only FILE names not containing matches" },    { OP_NODATA,     'L',      NULL,              "files-without-match","print only FILE names not containing matches" },
358    { OP_STRING,     N_LABEL,  &stdin_name,       "label=name",    "set name for standard input" },    { OP_STRING,     N_LABEL,  &stdin_name,       "label=name",    "set name for standard input" },
# Line 244  static option_item optionlist[] = { Line 364  static option_item optionlist[] = {
364    { OP_NODATA,     'M',      NULL,              "multiline",     "run in multiline mode" },    { OP_NODATA,     'M',      NULL,              "multiline",     "run in multiline mode" },
365    { OP_STRING,     'N',      &newline,          "newline=type",  "set newline type (CR, LF, CRLF, ANYCRLF or ANY)" },    { OP_STRING,     'N',      &newline,          "newline=type",  "set newline type (CR, LF, CRLF, ANYCRLF or ANY)" },
366    { OP_NODATA,     'n',      NULL,              "line-number",   "print line number with output lines" },    { OP_NODATA,     'n',      NULL,              "line-number",   "print line number with output lines" },
367    { OP_OP_NUMBER,  'o',      &only_matching,    "only-matching=n", "show only the part of the line that matched" },    { OP_OP_NUMBERS, 'o',      &only_matching_data, "only-matching=n", "show only the part of the line that matched" },
368      { OP_STRING,     N_OM_SEPARATOR, &om_separator, "om-separator=text", "set separator for multiple -o output" },
369    { OP_NODATA,     'q',      NULL,              "quiet",         "suppress output, just set return code" },    { OP_NODATA,     'q',      NULL,              "quiet",         "suppress output, just set return code" },
370    { OP_NODATA,     'r',      NULL,              "recursive",     "recursively scan sub-directories" },    { OP_NODATA,     'r',      NULL,              "recursive",     "recursively scan sub-directories" },
371    { OP_STRING,     N_EXCLUDE,&exclude_pattern,  "exclude=pattern","exclude matching files when recursing" },    { OP_PATLIST,    N_EXCLUDE,&exclude_patdata,  "exclude=pattern","exclude matching files when recursing" },
372    { OP_STRING,     N_INCLUDE,&include_pattern,  "include=pattern","include matching files when recursing" },    { OP_PATLIST,    N_INCLUDE,&include_patdata,  "include=pattern","include matching files when recursing" },
373    { OP_STRING,     N_EXCLUDE_DIR,&exclude_dir_pattern, "exclude-dir=pattern","exclude matching directories when recursing" },    { OP_PATLIST,    N_EXCLUDE_DIR,&exclude_dir_patdata, "exclude-dir=pattern","exclude matching directories when recursing" },
374    { OP_STRING,     N_INCLUDE_DIR,&include_dir_pattern, "include-dir=pattern","include matching directories when recursing" },    { OP_PATLIST,    N_INCLUDE_DIR,&include_dir_patdata, "include-dir=pattern","include matching directories when recursing" },
375      { OP_FILELIST,   N_EXCLUDE_FROM,&exclude_from_data, "exclude-from=path", "read exclude list from file" },
376      { OP_FILELIST,   N_INCLUDE_FROM,&include_from_data, "include-from=path", "read include list from file" },
377    
378    /* These two were accidentally implemented with underscores instead of    /* These two were accidentally implemented with underscores instead of
379    hyphens in the option names. As this was not discovered for several releases,    hyphens in the option names. As this was not discovered for several releases,
380    the incorrect versions are left in the table for compatibility. However, the    the incorrect versions are left in the table for compatibility. However, the
381    --help function misses out any option that has an underscore in its name. */    --help function misses out any option that has an underscore in its name. */
382    
383    { OP_STRING,    N_EXCLUDE_DIR,&exclude_dir_pattern, "exclude_dir=pattern","exclude matching directories when recursing" },    { OP_PATLIST,   N_EXCLUDE_DIR,&exclude_dir_patdata, "exclude_dir=pattern","exclude matching directories when recursing" },
384    { OP_STRING,    N_INCLUDE_DIR,&include_dir_pattern, "include_dir=pattern","include matching directories when recursing" },    { OP_PATLIST,   N_INCLUDE_DIR,&include_dir_patdata, "include_dir=pattern","include matching directories when recursing" },
385    
386  #ifdef JFRIEDL_DEBUG  #ifdef JFRIEDL_DEBUG
387    { OP_OP_NUMBER, 'S',      &S_arg,            "jeffS",         "replace matched (sub)string with X" },    { OP_OP_NUMBER, 'S',      &S_arg,            "jeffS",         "replace matched (sub)string with X" },
# Line 275  static option_item optionlist[] = { Line 398  static option_item optionlist[] = {
398  /* Tables for prefixing and suffixing patterns, according to the -w, -x, and -F  /* Tables for prefixing and suffixing patterns, according to the -w, -x, and -F
399  options. These set the 1, 2, and 4 bits in process_options, respectively. Note  options. These set the 1, 2, and 4 bits in process_options, respectively. Note
400  that the combination of -w and -x has the same effect as -x on its own, so we  that the combination of -w and -x has the same effect as -x on its own, so we
401  can treat them as the same. */  can treat them as the same. Note that the MAXPATLEN macro assumes the longest
402    prefix+suffix is 10 characters; if anything longer is added, it must be
403    adjusted. */
404    
405  static const char *prefix[] = {  static const char *prefix[] = {
406    "", "\\b", "^(?:", "^(?:", "\\Q", "\\b\\Q", "^(?:\\Q", "^(?:\\Q" };    "", "\\b", "^(?:", "^(?:", "\\Q", "\\b\\Q", "^(?:\\Q", "^(?:\\Q" };
# Line 310  pcregrep_exit(int rc) Line 435  pcregrep_exit(int rc)
435  {  {
436  if (resource_error)  if (resource_error)
437    {    {
438    fprintf(stderr, "pcregrep: Error %d or %d means that a resource limit "    fprintf(stderr, "pcregrep: Error %d, %d or %d means that a resource limit "
439      "was exceeded.\n", PCRE_ERROR_MATCHLIMIT, PCRE_ERROR_RECURSIONLIMIT);      "was exceeded.\n", PCRE_ERROR_MATCHLIMIT, PCRE_ERROR_RECURSIONLIMIT,
440        PCRE_ERROR_JIT_STACKLIMIT);
441    fprintf(stderr, "pcregrep: Check your regex for nested unlimited loops.\n");    fprintf(stderr, "pcregrep: Check your regex for nested unlimited loops.\n");
442    }    }
   
443  exit(rc);  exit(rc);
444  }  }
445    
446    
447  /*************************************************  /*************************************************
448    *          Add item to chain of patterns         *
449    *************************************************/
450    
451    /* Used to add an item onto a chain, or just return an unconnected item if the
452    "after" argument is NULL.
453    
454    Arguments:
455      s          pattern string to add
456      after      if not NULL points to item to insert after
457    
458    Returns:     new pattern block
459    */
460    
461    static patstr *
462    add_pattern(char *s, patstr *after)
463    {
464    patstr *p = (patstr *)malloc(sizeof(patstr));
465    if (p == NULL)
466      {
467      fprintf(stderr, "pcregrep: malloc failed\n");
468      pcregrep_exit(2);
469      }
470    if (strlen(s) > MAXPATLEN)
471      {
472      fprintf(stderr, "pcregrep: pattern is too long (limit is %d bytes)\n",
473        MAXPATLEN);
474      return NULL;
475      }
476    p->next = NULL;
477    p->string = s;
478    p->compiled = NULL;
479    p->hint = NULL;
480    
481    if (after != NULL)
482      {
483      p->next = after->next;
484      after->next = p;
485      }
486    return p;
487    }
488    
489    
490    /*************************************************
491    *           Free chain of patterns               *
492    *************************************************/
493    
494    /* Used for several chains of patterns.
495    
496    Argument: pointer to start of chain
497    Returns:  nothing
498    */
499    
500    static void
501    free_pattern_chain(patstr *pc)
502    {
503    while (pc != NULL)
504      {
505      patstr *p = pc;
506      pc = p->next;
507      if (p->hint != NULL) pcre_free_study(p->hint);
508      if (p->compiled != NULL) pcre_free(p->compiled);
509      free(p);
510      }
511    }
512    
513    
514    /*************************************************
515    *           Free chain of file names             *
516    *************************************************/
517    
518    /*
519    Argument: pointer to start of chain
520    Returns:  nothing
521    */
522    
523    static void
524    free_file_chain(fnstr *fn)
525    {
526    while (fn != NULL)
527      {
528      fnstr *f = fn;
529      fn = f->next;
530      free(f);
531      }
532    }
533    
534    
535    /*************************************************
536  *            OS-specific functions               *  *            OS-specific functions               *
537  *************************************************/  *************************************************/
538    
539  /* These functions are defined so that they can be made system specific,  /* These functions are defined so that they can be made system specific.
540  although at present the only ones are for Unix, Win32, and for "no support". */  At present there are versions for Unix-style environments, Windows, native
541    z/OS, and "no support". */
542    
543    
544  /************* Directory scanning in Unix ***********/  /************* Directory scanning Unix-style and z/OS ***********/
545    
546  #if defined HAVE_SYS_STAT_H && defined HAVE_DIRENT_H && defined HAVE_SYS_TYPES_H  #if (defined HAVE_SYS_STAT_H && defined HAVE_DIRENT_H && defined HAVE_SYS_TYPES_H) || defined NATIVE_ZOS
547  #include <sys/types.h>  #include <sys/types.h>
548  #include <sys/stat.h>  #include <sys/stat.h>
549  #include <dirent.h>  #include <dirent.h>
550    
551    #if defined NATIVE_ZOS
552    /************* Directory and PDS/E scanning for z/OS ***********/
553    /************* z/OS looks mostly like Unix with USS ************/
554    /* However, z/OS needs the #include statements in this header */
555    #include "pcrzosfs.h"
556    /* That header is not included in the main PCRE distribution because
557       other apparatus is needed to compile pcregrep for z/OS. The header
558       can be found in the special z/OS distribution, which is available
559       from www.zaconsultants.net or from www.cbttape.org. */
560    #endif
561    
562  typedef DIR directory_type;  typedef DIR directory_type;
563    #define FILESEP '/'
564    
565  static int  static int
566  isdirectory(char *filename)  isdirectory(char *filename)
# Line 342  isdirectory(char *filename) Line 568  isdirectory(char *filename)
568  struct stat statbuf;  struct stat statbuf;
569  if (stat(filename, &statbuf) < 0)  if (stat(filename, &statbuf) < 0)
570    return 0;        /* In the expectation that opening as a file will fail */    return 0;        /* In the expectation that opening as a file will fail */
571  return ((statbuf.st_mode & S_IFMT) == S_IFDIR)? '/' : 0;  return (statbuf.st_mode & S_IFMT) == S_IFDIR;
572  }  }
573    
574  static directory_type *  static directory_type *
# Line 371  closedir(dir); Line 597  closedir(dir);
597  }  }
598    
599    
600  /************* Test for regular file in Unix **********/  /************* Test for regular file, Unix-style **********/
601    
602  static int  static int
603  isregfile(char *filename)  isregfile(char *filename)
# Line 383  return (statbuf.st_mode & S_IFMT) == S_I Line 609  return (statbuf.st_mode & S_IFMT) == S_I
609  }  }
610    
611    
612  /************* Test for a terminal in Unix **********/  #if defined NATIVE_ZOS
613    /************* Test for a terminal in z/OS **********/
614    /* isatty() does not work in a TSO environment, so always give FALSE.*/
615    
616    static BOOL
617    is_stdout_tty(void)
618    {
619    return FALSE;
620    }
621    
622    static BOOL
623    is_file_tty(FILE *f)
624    {
625    return FALSE;
626    }
627    
628    
629    /************* Test for a terminal, Unix-style **********/
630    
631    #else
632  static BOOL  static BOOL
633  is_stdout_tty(void)  is_stdout_tty(void)
634  {  {
# Line 396  is_file_tty(FILE *f) Line 640  is_file_tty(FILE *f)
640  {  {
641  return isatty(fileno(f));  return isatty(fileno(f));
642  }  }
643    #endif
644    
645    /* End of Unix-style or native z/OS environment functions. */
646    
647    
648  /************* Directory scanning in Win32 ***********/  /************* Directory scanning in Windows ***********/
649    
650  /* I (Philip Hazel) have no means of testing this code. It was contributed by  /* I (Philip Hazel) have no means of testing this code. It was contributed by
651  Lionel Fourquaux. David Burgess added a patch to define INVALID_FILE_ATTRIBUTES  Lionel Fourquaux. David Burgess added a patch to define INVALID_FILE_ATTRIBUTES
# Line 429  BOOL first; Line 676  BOOL first;
676  WIN32_FIND_DATA data;  WIN32_FIND_DATA data;
677  } directory_type;  } directory_type;
678    
679    #define FILESEP '/'
680    
681  int  int
682  isdirectory(char *filename)  isdirectory(char *filename)
683  {  {
684  DWORD attr = GetFileAttributes(filename);  DWORD attr = GetFileAttributes(filename);
685  if (attr == INVALID_FILE_ATTRIBUTES)  if (attr == INVALID_FILE_ATTRIBUTES)
686    return 0;    return 0;
687  return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) ? '/' : 0;  return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
688  }  }
689    
690  directory_type *  directory_type *
# Line 446  char *pattern; Line 695  char *pattern;
695  directory_type *dir;  directory_type *dir;
696  DWORD err;  DWORD err;
697  len = strlen(filename);  len = strlen(filename);
698  pattern = (char *) malloc(len + 3);  pattern = (char *)malloc(len + 3);
699  dir = (directory_type *) malloc(sizeof(*dir));  dir = (directory_type *)malloc(sizeof(*dir));
700  if ((pattern == NULL) || (dir == NULL))  if ((pattern == NULL) || (dir == NULL))
701    {    {
702    fprintf(stderr, "pcregrep: malloc failed\n");    fprintf(stderr, "pcregrep: malloc failed\n");
# Line 499  free(dir); Line 748  free(dir);
748  }  }
749    
750    
751  /************* Test for regular file in Win32 **********/  /************* Test for regular file in Windows **********/
752    
753  /* I don't know how to do this, or if it can be done; assume all paths are  /* I don't know how to do this, or if it can be done; assume all paths are
754  regular if they are not directories. */  regular if they are not directories. */
# Line 510  return !isdirectory(filename); Line 759  return !isdirectory(filename);
759  }  }
760    
761    
762  /************* Test for a terminal in Win32 **********/  /************* Test for a terminal in Windows **********/
763    
764  /* I don't know how to do this; assume never */  /* I don't know how to do this; assume never */
765    
# Line 526  is_file_tty(FILE *f) Line 775  is_file_tty(FILE *f)
775  return FALSE;  return FALSE;
776  }  }
777    
778    /* End of Windows functions */
779    
780    
781  /************* Directory scanning when we can't do it ***********/  /************* Directory scanning when we can't do it ***********/
782    
# Line 533  return FALSE; Line 784  return FALSE;
784    
785  #else  #else
786    
787    #define FILESEP 0
788  typedef void directory_type;  typedef void directory_type;
789    
790  int isdirectory(char *filename) { return 0; }  int isdirectory(char *filename) { return 0; }
# Line 541  char *readdirectory(directory_type *dir) Line 793  char *readdirectory(directory_type *dir)
793  void closedirectory(directory_type *dir) {}  void closedirectory(directory_type *dir) {}
794    
795    
796  /************* Test for regular when we can't do it **********/  /************* Test for regular file when we can't do it **********/
797    
798  /* Assume all files are regular. */  /* Assume all files are regular. */
799    
# Line 562  is_file_tty(FILE *f) Line 814  is_file_tty(FILE *f)
814  return FALSE;  return FALSE;
815  }  }
816    
817  #endif  #endif  /* End of system-specific functions */
818    
819    
820    
# Line 589  return sys_errlist[n]; Line 841  return sys_errlist[n];
841    
842    
843  /*************************************************  /*************************************************
844    *                Usage function                  *
845    *************************************************/
846    
847    static int
848    usage(int rc)
849    {
850    option_item *op;
851    fprintf(stderr, "Usage: pcregrep [-");
852    for (op = optionlist; op->one_char != 0; op++)
853      {
854      if (op->one_char > 0) fprintf(stderr, "%c", op->one_char);
855      }
856    fprintf(stderr, "] [long options] [pattern] [files]\n");
857    fprintf(stderr, "Type `pcregrep --help' for more information and the long "
858      "options.\n");
859    return rc;
860    }
861    
862    
863    
864    /*************************************************
865    *                Help function                   *
866    *************************************************/
867    
868    static void
869    help(void)
870    {
871    option_item *op;
872    
873    printf("Usage: pcregrep [OPTION]... [PATTERN] [FILE1 FILE2 ...]\n");
874    printf("Search for PATTERN in each FILE or standard input.\n");
875    printf("PATTERN must be present if neither -e nor -f is used.\n");
876    printf("\"-\" can be used as a file name to mean STDIN.\n");
877    
878    #ifdef SUPPORT_LIBZ
879    printf("Files whose names end in .gz are read using zlib.\n");
880    #endif
881    
882    #ifdef SUPPORT_LIBBZ2
883    printf("Files whose names end in .bz2 are read using bzlib2.\n");
884    #endif
885    
886    #if defined SUPPORT_LIBZ || defined SUPPORT_LIBBZ2
887    printf("Other files and the standard input are read as plain files.\n\n");
888    #else
889    printf("All files are read as plain files, without any interpretation.\n\n");
890    #endif
891    
892    printf("Example: pcregrep -i 'hello.*world' menu.h main.c\n\n");
893    printf("Options:\n");
894    
895    for (op = optionlist; op->one_char != 0; op++)
896      {
897      int n;
898      char s[4];
899    
900      /* Two options were accidentally implemented and documented with underscores
901      instead of hyphens in their names, something that was not noticed for quite a
902      few releases. When fixing this, I left the underscored versions in the list
903      in case people were using them. However, we don't want to display them in the
904      help data. There are no other options that contain underscores, and we do not
905      expect ever to implement such options. Therefore, just omit any option that
906      contains an underscore. */
907    
908      if (strchr(op->long_name, '_') != NULL) continue;
909    
910      if (op->one_char > 0 && (op->long_name)[0] == 0)
911        n = 31 - printf("  -%c", op->one_char);
912      else
913        {
914        if (op->one_char > 0) sprintf(s, "-%c,", op->one_char);
915          else strcpy(s, "   ");
916        n = 31 - printf("  %s --%s", s, op->long_name);
917        }
918    
919      if (n < 1) n = 1;
920      printf("%.*s%s\n", n, "                           ", op->help_text);
921      }
922    
923    printf("\nNumbers may be followed by K or M, e.g. --buffer-size=100K.\n");
924    printf("The default value for --buffer-size is %d.\n", PCREGREP_BUFSIZE);
925    printf("When reading patterns or file names from a file, trailing white\n");
926    printf("space is removed and blank lines are ignored.\n");
927    printf("The maximum size of any pattern is %d bytes.\n", MAXPATLEN);
928    
929    printf("\nWith no FILEs, read standard input. If fewer than two FILEs given, assume -h.\n");
930    printf("Exit status is 0 if any matches, 1 if no matches, and 2 if trouble.\n");
931    }
932    
933    
934    
935    /*************************************************
936    *            Test exclude/includes               *
937    *************************************************/
938    
939    /* If any exclude pattern matches, the path is excluded. Otherwise, unless
940    there are no includes, the path must match an include pattern.
941    
942    Arguments:
943      path      the path to be matched
944      ip        the chain of include patterns
945      ep        the chain of exclude patterns
946    
947    Returns:    TRUE if the path is not excluded
948    */
949    
950    static BOOL
951    test_incexc(char *path, patstr *ip, patstr *ep)
952    {
953    int plen = strlen(path);
954    
955    for (; ep != NULL; ep = ep->next)
956      {
957      if (pcre_exec(ep->compiled, NULL, path, plen, 0, 0, NULL, 0) >= 0)
958        return FALSE;
959      }
960    
961    if (ip == NULL) return TRUE;
962    
963    for (; ip != NULL; ip = ip->next)
964      {
965      if (pcre_exec(ip->compiled, NULL, path, plen, 0, 0, NULL, 0) >= 0)
966        return TRUE;
967      }
968    
969    return FALSE;
970    }
971    
972    
973    
974    /*************************************************
975    *         Decode integer argument value          *
976    *************************************************/
977    
978    /* Integer arguments can be followed by K or M. Avoid the use of strtoul()
979    because SunOS4 doesn't have it. This is used only for unpicking arguments, so
980    just keep it simple.
981    
982    Arguments:
983      option_data   the option data string
984      op            the option item (for error messages)
985      longop        TRUE if option given in long form
986    
987    Returns:        a long integer
988    */
989    
990    static long int
991    decode_number(char *option_data, option_item *op, BOOL longop)
992    {
993    unsigned long int n = 0;
994    char *endptr = option_data;
995    while (*endptr != 0 && isspace((unsigned char)(*endptr))) endptr++;
996    while (isdigit((unsigned char)(*endptr)))
997      n = n * 10 + (int)(*endptr++ - '0');
998    if (toupper(*endptr) == 'K')
999      {
1000      n *= 1024;
1001      endptr++;
1002      }
1003    else if (toupper(*endptr) == 'M')
1004      {
1005      n *= 1024*1024;
1006      endptr++;
1007      }
1008    
1009    if (*endptr != 0)   /* Error */
1010      {
1011      if (longop)
1012        {
1013        char *equals = strchr(op->long_name, '=');
1014        int nlen = (equals == NULL)? (int)strlen(op->long_name) :
1015          (int)(equals - op->long_name);
1016        fprintf(stderr, "pcregrep: Malformed number \"%s\" after --%.*s\n",
1017          option_data, nlen, op->long_name);
1018        }
1019      else
1020        fprintf(stderr, "pcregrep: Malformed number \"%s\" after -%c\n",
1021          option_data, op->one_char);
1022      pcregrep_exit(usage(2));
1023      }
1024    
1025    return n;
1026    }
1027    
1028    
1029    
1030    /*************************************************
1031    *       Add item to a chain of numbers           *
1032    *************************************************/
1033    
1034    /* Used to add an item onto a chain, or just return an unconnected item if the
1035    "after" argument is NULL.
1036    
1037    Arguments:
1038      n          the number to add
1039      after      if not NULL points to item to insert after
1040    
1041    Returns:     new number block
1042    */
1043    
1044    static omstr *
1045    add_number(int n, omstr *after)
1046    {
1047    omstr *om = (omstr *)malloc(sizeof(omstr));
1048    
1049    if (om == NULL)
1050      {
1051      fprintf(stderr, "pcregrep: malloc failed\n");
1052      pcregrep_exit(2);
1053      }
1054    om->next = NULL;
1055    om->groupnum = n;
1056    
1057    if (after != NULL)
1058      {
1059      om->next = after->next;
1060      after->next = om;
1061      }
1062    return om;
1063    }
1064    
1065    
1066    
1067    /*************************************************
1068  *            Read one line of input              *  *            Read one line of input              *
1069  *************************************************/  *************************************************/
1070    
# Line 607  Arguments: Line 1083  Arguments:
1083  Returns:     the number of characters read, zero at end of file  Returns:     the number of characters read, zero at end of file
1084  */  */
1085    
1086  static int  static unsigned int
1087  read_one_line(char *buffer, int length, FILE *f)  read_one_line(char *buffer, int length, FILE *f)
1088  {  {
1089  int c;  int c;
# Line 634  Arguments: Line 1110  Arguments:
1110    endptr    end of available data    endptr    end of available data
1111    lenptr    where to put the length of the eol sequence    lenptr    where to put the length of the eol sequence
1112    
1113  Returns:    pointer to the last byte of the line  Returns:    pointer after the last byte of the line,
1114                including the newline byte(s)
1115  */  */
1116    
1117  static char *  static char *
# Line 703  switch(endlinetype) Line 1180  switch(endlinetype)
1180    
1181      switch (c)      switch (c)
1182        {        {
1183        case 0x0a:    /* LF */        case '\n':
1184        *lenptr = 1;        *lenptr = 1;
1185        return p;        return p;
1186    
1187        case 0x0d:    /* CR */        case '\r':
1188        if (p < endptr && *p == 0x0a)        if (p < endptr && *p == '\n')
1189          {          {
1190          *lenptr = 2;          *lenptr = 2;
1191          p++;          p++;
# Line 747  switch(endlinetype) Line 1224  switch(endlinetype)
1224    
1225      switch (c)      switch (c)
1226        {        {
1227        case 0x0a:    /* LF */        case '\n':    /* LF */
1228        case 0x0b:    /* VT */        case '\v':    /* VT */
1229        case 0x0c:    /* FF */        case '\f':    /* FF */
1230        *lenptr = 1;        *lenptr = 1;
1231        return p;        return p;
1232    
1233        case 0x0d:    /* CR */        case '\r':    /* CR */
1234        if (p < endptr && *p == 0x0a)        if (p < endptr && *p == '\n')
1235          {          {
1236          *lenptr = 2;          *lenptr = 2;
1237          p++;          p++;
# Line 762  switch(endlinetype) Line 1239  switch(endlinetype)
1239        else *lenptr = 1;        else *lenptr = 1;
1240        return p;        return p;
1241    
1242        case 0x85:    /* NEL */  #ifndef EBCDIC
1243          case 0x85:    /* Unicode NEL */
1244        *lenptr = utf8? 2 : 1;        *lenptr = utf8? 2 : 1;
1245        return p;        return p;
1246    
1247        case 0x2028:  /* LS */        case 0x2028:  /* Unicode LS */
1248        case 0x2029:  /* PS */        case 0x2029:  /* Unicode PS */
1249        *lenptr = 3;        *lenptr = 3;
1250        return p;        return p;
1251    #endif  /* Not EBCDIC */
1252    
1253        default:        default:
1254        break;        break;
# Line 828  switch(endlinetype) Line 1307  switch(endlinetype)
1307    
1308    while (p > startptr)    while (p > startptr)
1309      {      {
1310      register int c;      register unsigned int c;
1311      char *pp = p - 1;      char *pp = p - 1;
1312    
1313      if (utf8)      if (utf8)
# Line 853  switch(endlinetype) Line 1332  switch(endlinetype)
1332    
1333      if (endlinetype == EL_ANYCRLF) switch (c)      if (endlinetype == EL_ANYCRLF) switch (c)
1334        {        {
1335        case 0x0a:    /* LF */        case '\n':    /* LF */
1336        case 0x0d:    /* CR */        case '\r':    /* CR */
1337        return p;        return p;
1338    
1339        default:        default:
# Line 863  switch(endlinetype) Line 1342  switch(endlinetype)
1342    
1343      else switch (c)      else switch (c)
1344        {        {
1345        case 0x0a:    /* LF */        case '\n':    /* LF */
1346        case 0x0b:    /* VT */        case '\v':    /* VT */
1347        case 0x0c:    /* FF */        case '\f':    /* FF */
1348        case 0x0d:    /* CR */        case '\r':    /* CR */
1349        case 0x85:    /* NEL */  #ifndef EBCDIE
1350        case 0x2028:  /* LS */        case 0x85:    /* Unicode NEL */
1351        case 0x2029:  /* PS */        case 0x2028:  /* Unicode LS */
1352          case 0x2029:  /* Unicode PS */
1353    #endif  /* Not EBCDIC */
1354        return p;        return p;
1355    
1356        default:        default:
# Line 904  Arguments: Line 1385  Arguments:
1385  Returns:            nothing  Returns:            nothing
1386  */  */
1387    
1388  static void do_after_lines(int lastmatchnumber, char *lastmatchrestart,  static void
1389    char *endptr, char *printname)  do_after_lines(int lastmatchnumber, char *lastmatchrestart, char *endptr,
1390      char *printname)
1391  {  {
1392  if (after_context > 0 && lastmatchnumber > 0)  if (after_context > 0 && lastmatchnumber > 0)
1393    {    {
# Line 935  is used multiple times for the same subj Line 1417  is used multiple times for the same subj
1417  to find all possible matches.  to find all possible matches.
1418    
1419  Arguments:  Arguments:
1420    matchptr    the start of the subject    matchptr     the start of the subject
1421    length      the length of the subject to match    length       the length of the subject to match
1422    offsets     the offets vector to fill in    options      options for pcre_exec
1423    mrc         address of where to put the result of pcre_exec()    startoffset  where to start matching
1424      offsets      the offets vector to fill in
1425      mrc          address of where to put the result of pcre_exec()
1426    
1427  Returns:      TRUE if there was a match  Returns:      TRUE if there was a match
1428                FALSE if there was no match                FALSE if there was no match
# Line 946  Returns:      TRUE if there was a match Line 1430  Returns:      TRUE if there was a match
1430  */  */
1431    
1432  static BOOL  static BOOL
1433  match_patterns(char *matchptr, size_t length, int *offsets, int *mrc)  match_patterns(char *matchptr, size_t length, unsigned int options,
1434      int startoffset, int *offsets, int *mrc)
1435  {  {
1436  int i;  int i;
1437  size_t slen = length;  size_t slen = length;
1438    patstr *p = patterns;
1439  const char *msg = "this text:\n\n";  const char *msg = "this text:\n\n";
1440    
1441  if (slen > 200)  if (slen > 200)
1442    {    {
1443    slen = 200;    slen = 200;
1444    msg = "text that starts:\n\n";    msg = "text that starts:\n\n";
1445    }    }
1446  for (i = 0; i < pattern_count; i++)  for (i = 1; p != NULL; p = p->next, i++)
1447    {    {
1448    *mrc = pcre_exec(pattern_list[i], hints_list[i], matchptr, (int)length, 0,    *mrc = pcre_exec(p->compiled, p->hint, matchptr, (int)length,
1449      PCRE_NOTEMPTY, offsets, OFFSET_SIZE);      startoffset, options, offsets, OFFSET_SIZE);
1450    if (*mrc >= 0) return TRUE;    if (*mrc >= 0) return TRUE;
1451    if (*mrc == PCRE_ERROR_NOMATCH) continue;    if (*mrc == PCRE_ERROR_NOMATCH) continue;
1452    fprintf(stderr, "pcregrep: pcre_exec() gave error %d while matching ", *mrc);    fprintf(stderr, "pcregrep: pcre_exec() gave error %d while matching ", *mrc);
1453    if (pattern_count > 1) fprintf(stderr, "pattern number %d to ", i+1);    if (patterns->next != NULL) fprintf(stderr, "pattern number %d to ", i);
1454    fprintf(stderr, "%s", msg);    fprintf(stderr, "%s", msg);
1455    FWRITE(matchptr, 1, slen, stderr);   /* In case binary zero included */    FWRITE(matchptr, 1, slen, stderr);   /* In case binary zero included */
1456    fprintf(stderr, "\n\n");    fprintf(stderr, "\n\n");
1457    if (*mrc == PCRE_ERROR_MATCHLIMIT || *mrc == PCRE_ERROR_RECURSIONLIMIT)    if (*mrc == PCRE_ERROR_MATCHLIMIT || *mrc == PCRE_ERROR_RECURSIONLIMIT ||
1458          *mrc == PCRE_ERROR_JIT_STACKLIMIT)
1459      resource_error = TRUE;      resource_error = TRUE;
1460    if (error_count++ > 20)    if (error_count++ > 20)
1461      {      {
# Line 987  return FALSE;  /* No match, no errors */ Line 1475  return FALSE;  /* No match, no errors */
1475  *************************************************/  *************************************************/
1476    
1477  /* This is called from grep_or_recurse() below. It uses a buffer that is three  /* This is called from grep_or_recurse() below. It uses a buffer that is three
1478  times the value of MBUFTHIRD. The matching point is never allowed to stray into  times the value of bufthird. The matching point is never allowed to stray into
1479  the top third of the buffer, thus keeping more of the file available for  the top third of the buffer, thus keeping more of the file available for
1480  context printing or for multiline scanning. For large files, the pointer will  context printing or for multiline scanning. For large files, the pointer will
1481  be in the middle third most of the time, so the bottom third is available for  be in the middle third most of the time, so the bottom third is available for
# Line 998  Arguments: Line 1486  Arguments:
1486                 the gzFile pointer when reading is via libz                 the gzFile pointer when reading is via libz
1487                 the BZFILE pointer when reading is via libbz2                 the BZFILE pointer when reading is via libbz2
1488    frtype       FR_PLAIN, FR_LIBZ, or FR_LIBBZ2    frtype       FR_PLAIN, FR_LIBZ, or FR_LIBBZ2
1489      filename     the file name or NULL (for errors)
1490    printname    the file name if it is to be printed for each match    printname    the file name if it is to be printed for each match
1491                 or NULL if the file name is not to be printed                 or NULL if the file name is not to be printed
1492                 it cannot be NULL if filenames[_nomatch]_only is set                 it cannot be NULL if filenames[_nomatch]_only is set
1493    
1494  Returns:       0 if there was at least one match  Returns:       0 if there was at least one match
1495                 1 otherwise (no matches)                 1 otherwise (no matches)
1496                 2 if there is a read error on a .bz2 file                 2 if an overlong line is encountered
1497                   3 if there is a read error on a .bz2 file
1498  */  */
1499    
1500  static int  static int
1501  pcregrep(void *handle, int frtype, char *printname)  pcregrep(void *handle, int frtype, char *filename, char *printname)
1502  {  {
1503  int rc = 1;  int rc = 1;
1504  int linenumber = 1;  int linenumber = 1;
# Line 1017  int count = 0; Line 1507  int count = 0;
1507  int filepos = 0;  int filepos = 0;
1508  int offsets[OFFSET_SIZE];  int offsets[OFFSET_SIZE];
1509  char *lastmatchrestart = NULL;  char *lastmatchrestart = NULL;
1510  char buffer[3*MBUFTHIRD];  char *ptr = main_buffer;
 char *ptr = buffer;  
1511  char *endptr;  char *endptr;
1512  size_t bufflength;  size_t bufflength;
1513    BOOL binary = FALSE;
1514  BOOL endhyphenpending = FALSE;  BOOL endhyphenpending = FALSE;
1515  BOOL input_line_buffered = line_buffered;  BOOL input_line_buffered = line_buffered;
1516  FILE *in = NULL;                    /* Ensure initialized */  FILE *in = NULL;                    /* Ensure initialized */
# Line 1039  of what we have. In the case of libz, a Line 1529  of what we have. In the case of libz, a
1529  plain file. However, if a .bz2 file isn't actually bzipped, the first read will  plain file. However, if a .bz2 file isn't actually bzipped, the first read will
1530  fail. */  fail. */
1531    
1532    (void)frtype;
1533    
1534  #ifdef SUPPORT_LIBZ  #ifdef SUPPORT_LIBZ
1535  if (frtype == FR_LIBZ)  if (frtype == FR_LIBZ)
1536    {    {
1537    ingz = (gzFile)handle;    ingz = (gzFile)handle;
1538    bufflength = gzread (ingz, buffer, 3*MBUFTHIRD);    bufflength = gzread (ingz, main_buffer, bufsize);
1539    }    }
1540  else  else
1541  #endif  #endif
# Line 1052  else Line 1544  else
1544  if (frtype == FR_LIBBZ2)  if (frtype == FR_LIBBZ2)
1545    {    {
1546    inbz2 = (BZFILE *)handle;    inbz2 = (BZFILE *)handle;
1547    bufflength = BZ2_bzread(inbz2, buffer, 3*MBUFTHIRD);    bufflength = BZ2_bzread(inbz2, main_buffer, bufsize);
1548    if ((int)bufflength < 0) return 2;   /* Gotcha: bufflength is size_t; */    if ((int)bufflength < 0) return 2;   /* Gotcha: bufflength is size_t; */
1549    }                                    /* without the cast it is unsigned. */    }                                    /* without the cast it is unsigned. */
1550  else  else
# Line 1062  else Line 1554  else
1554    in = (FILE *)handle;    in = (FILE *)handle;
1555    if (is_file_tty(in)) input_line_buffered = TRUE;    if (is_file_tty(in)) input_line_buffered = TRUE;
1556    bufflength = input_line_buffered?    bufflength = input_line_buffered?
1557      read_one_line(buffer, 3*MBUFTHIRD, in) :      read_one_line(main_buffer, bufsize, in) :
1558      fread(buffer, 1, 3*MBUFTHIRD, in);      fread(main_buffer, 1, bufsize, in);
1559    }    }
1560    
1561  endptr = buffer + bufflength;  endptr = main_buffer + bufflength;
1562    
1563    /* Unless binary-files=text, see if we have a binary file. This uses the same
1564    rule as GNU grep, namely, a search for a binary zero byte near the start of the
1565    file. */
1566    
1567    if (binary_files != BIN_TEXT)
1568      {
1569      binary =
1570        memchr(main_buffer, 0, (bufflength > 1024)? 1024 : bufflength) != NULL;
1571      if (binary && binary_files == BIN_NOMATCH) return 1;
1572      }
1573    
1574  /* Loop while the current pointer is not at the end of the file. For large  /* Loop while the current pointer is not at the end of the file. For large
1575  files, endptr will be at the end of the buffer when we are in the middle of the  files, endptr will be at the end of the buffer when we are in the middle of the
# Line 1077  while (ptr < endptr) Line 1580  while (ptr < endptr)
1580    {    {
1581    int endlinelength;    int endlinelength;
1582    int mrc = 0;    int mrc = 0;
1583      int startoffset = 0;
1584      unsigned int options = 0;
1585    BOOL match;    BOOL match;
1586    char *matchptr = ptr;    char *matchptr = ptr;
1587    char *t = ptr;    char *t = ptr;
# Line 1094  while (ptr < endptr) Line 1599  while (ptr < endptr)
1599    linelength = t - ptr - endlinelength;    linelength = t - ptr - endlinelength;
1600    length = multiline? (size_t)(endptr - ptr) : linelength;    length = multiline? (size_t)(endptr - ptr) : linelength;
1601    
1602      /* Check to see if the line we are looking at extends right to the very end
1603      of the buffer without a line terminator. This means the line is too long to
1604      handle. */
1605    
1606      if (endlinelength == 0 && t == main_buffer + bufsize)
1607        {
1608        fprintf(stderr, "pcregrep: line %d%s%s is too long for the internal buffer\n"
1609                        "pcregrep: check the --buffer-size option\n",
1610                        linenumber,
1611                        (filename == NULL)? "" : " of file ",
1612                        (filename == NULL)? "" : filename);
1613        return 2;
1614        }
1615    
1616    /* Extra processing for Jeffrey Friedl's debugging. */    /* Extra processing for Jeffrey Friedl's debugging. */
1617    
1618  #ifdef JFRIEDL_DEBUG  #ifdef JFRIEDL_DEBUG
1619    if (jfriedl_XT || jfriedl_XR)    if (jfriedl_XT || jfriedl_XR)
1620    {    {
1621        #include <sys/time.h>  #     include <sys/time.h>
1622        #include <time.h>  #     include <time.h>
1623        struct timeval start_time, end_time;        struct timeval start_time, end_time;
1624        struct timezone dummy;        struct timezone dummy;
1625        int i;        int i;
# Line 1129  while (ptr < endptr) Line 1648  while (ptr < endptr)
1648    
1649    
1650        for (i = 0; i < jfriedl_XR; i++)        for (i = 0; i < jfriedl_XR; i++)
1651            match = (pcre_exec(pattern_list[0], hints_list[0], ptr, length, 0,            match = (pcre_exec(patterns->compiled, patterns->hint, ptr, length, 0,
1652                PCRE_NOTEMPTY, offsets, OFFSET_SIZE) >= 0);                PCRE_NOTEMPTY, offsets, OFFSET_SIZE) >= 0);
1653    
1654        if (gettimeofday(&end_time, &dummy) != 0)        if (gettimeofday(&end_time, &dummy) != 0)
# Line 1144  while (ptr < endptr) Line 1663  while (ptr < endptr)
1663    }    }
1664  #endif  #endif
1665    
1666    /* We come back here after a match when the -o option (only_matching) is set,    /* We come back here after a match when show_only_matching is set, in order
1667    in order to find any further matches in the same line. */    to find any further matches in the same line. This applies to
1668      --only-matching, --file-offsets, and --line-offsets. */
1669    
1670    ONLY_MATCHING_RESTART:    ONLY_MATCHING_RESTART:
1671    
1672    /* Run through all the patterns until one matches or there is an error other    /* Run through all the patterns until one matches or there is an error other
1673    than NOMATCH. This code is in a subroutine so that it can be re-used for    than NOMATCH. This code is in a subroutine so that it can be re-used for
1674    finding subsequent matches when colouring matched lines. */    finding subsequent matches when colouring matched lines. After finding one
1675      match, set PCRE_NOTEMPTY to disable any further matches of null strings in
1676      this line. */
1677    
1678    match = match_patterns(matchptr, length, offsets, &mrc);    match = match_patterns(matchptr, length, options, startoffset, offsets, &mrc);
1679      options = PCRE_NOTEMPTY;
1680    
1681    /* If it's a match or a not-match (as required), do what's wanted. */    /* If it's a match or a not-match (as required), do what's wanted. */
1682    
# Line 1169  while (ptr < endptr) Line 1692  while (ptr < endptr)
1692    
1693      if (count_only) count++;      if (count_only) count++;
1694    
1695        /* When handling a binary file and binary-files==binary, the "binary"
1696        variable will be set true (it's false in all other cases). In this
1697        situation we just want to output the file name. No need to scan further. */
1698    
1699        else if (binary)
1700          {
1701          fprintf(stdout, "Binary file %s matches\n", filename);
1702          return 0;
1703          }
1704    
1705      /* If all we want is a file name, there is no need to scan any more lines      /* If all we want is a file name, there is no need to scan any more lines
1706      in the file. */      in the file. */
1707    
# Line 1182  while (ptr < endptr) Line 1715  while (ptr < endptr)
1715    
1716      else if (quiet) return 0;      else if (quiet) return 0;
1717    
1718      /* The --only-matching option prints just the substring that matched, or a      /* The --only-matching option prints just the substring that matched,
1719      captured portion of it, as long as this string is not empty, and the      and/or one or more captured portions of it, as long as these strings are
1720      --file-offsets and --line-offsets options output offsets for the matching      not empty. The --file-offsets and --line-offsets options output offsets for
1721      substring (they both force --only-matching = 0). None of these options      the matching substring (all three set show_only_matching). None of these
1722      prints any context. Afterwards, adjust the start and length, and then jump      mutually exclusive options prints any context. Afterwards, adjust the start
1723      back to look for further matches in the same line. If we are in invert      and then jump back to look for further matches in the same line. If we are
1724      mode, however, nothing is printed and we do not restart - this could still      in invert mode, however, nothing is printed and we do not restart - this
1725      be useful because the return code is set. */      could still be useful because the return code is set. */
1726    
1727      else if (only_matching >= 0)      else if (show_only_matching)
1728        {        {
1729        if (!invert)        if (!invert)
1730          {          {
1731          if (printname != NULL) fprintf(stdout, "%s:", printname);          if (printname != NULL) fprintf(stdout, "%s:", printname);
1732          if (number) fprintf(stdout, "%d:", linenumber);          if (number) fprintf(stdout, "%d:", linenumber);
1733          if (line_offsets)  
1734            /* Handle --line-offsets */
1735    
1736            if (line_offsets)
1737            fprintf(stdout, "%d,%d\n", (int)(matchptr + offsets[0] - ptr),            fprintf(stdout, "%d,%d\n", (int)(matchptr + offsets[0] - ptr),
1738              offsets[1] - offsets[0]);              offsets[1] - offsets[0]);
1739    
1740            /* Handle --file-offsets */
1741    
1742          else if (file_offsets)          else if (file_offsets)
1743            fprintf(stdout, "%d,%d\n",            fprintf(stdout, "%d,%d\n",
1744              (int)(filepos + matchptr + offsets[0] - ptr),              (int)(filepos + matchptr + offsets[0] - ptr),
1745              offsets[1] - offsets[0]);              offsets[1] - offsets[0]);
1746          else if (only_matching < mrc)  
1747            /* Handle --only-matching, which may occur many times */
1748    
1749            else
1750            {            {
1751            int plen = offsets[2*only_matching + 1] - offsets[2*only_matching];            BOOL printed = FALSE;
1752            if (plen > 0)            omstr *om;
1753    
1754              for (om = only_matching; om != NULL; om = om->next)
1755              {              {
1756              if (do_colour) fprintf(stdout, "%c[%sm", 0x1b, colour_string);              int n = om->groupnum;
1757              FWRITE(matchptr + offsets[only_matching*2], 1, plen, stdout);              if (n < mrc)
1758              if (do_colour) fprintf(stdout, "%c[00m", 0x1b);                {
1759              fprintf(stdout, "\n");                int plen = offsets[2*n + 1] - offsets[2*n];
1760                  if (plen > 0)
1761                    {
1762                    if (printed) fprintf(stdout, "%s", om_separator);
1763                    if (do_colour) fprintf(stdout, "%c[%sm", 0x1b, colour_string);
1764                    FWRITE(matchptr + offsets[n*2], 1, plen, stdout);
1765                    if (do_colour) fprintf(stdout, "%c[00m", 0x1b);
1766                    printed = TRUE;
1767                    }
1768                  }
1769              }              }
1770    
1771              if (printed || printname != NULL || number) fprintf(stdout, "\n");
1772            }            }
1773          else if (printname != NULL || number) fprintf(stdout, "\n");  
1774          matchptr += offsets[1];          /* Prepare to repeat to find the next match */
1775          length -= offsets[1];  
1776          match = FALSE;          match = FALSE;
1777          if (line_buffered) fflush(stdout);          if (line_buffered) fflush(stdout);
1778          rc = 0;    /* Had some success */          rc = 0;                      /* Had some success */
1779            startoffset = offsets[1];    /* Restart after the match */
1780          goto ONLY_MATCHING_RESTART;          goto ONLY_MATCHING_RESTART;
1781          }          }
1782        }        }
# Line 1279  while (ptr < endptr) Line 1835  while (ptr < endptr)
1835          int linecount = 0;          int linecount = 0;
1836          char *p = ptr;          char *p = ptr;
1837    
1838          while (p > buffer && (lastmatchnumber == 0 || p > lastmatchrestart) &&          while (p > main_buffer && (lastmatchnumber == 0 || p > lastmatchrestart) &&
1839                 linecount < before_context)                 linecount < before_context)
1840            {            {
1841            linecount++;            linecount++;
1842            p = previous_line(p, buffer);            p = previous_line(p, main_buffer);
1843            }            }
1844    
1845          if (lastmatchnumber > 0 && p > lastmatchrestart && !hyphenprinted)          if (lastmatchnumber > 0 && p > lastmatchrestart && !hyphenprinted)
# Line 1316  while (ptr < endptr) Line 1872  while (ptr < endptr)
1872        (invert not set). Because the PCRE_FIRSTLINE option is set, the start of        (invert not set). Because the PCRE_FIRSTLINE option is set, the start of
1873        the match will always be before the first newline sequence. */        the match will always be before the first newline sequence. */
1874    
1875        if (multiline)        if (multiline & !invert)
1876          {          {
1877          int ellength;          char *endmatch = ptr + offsets[1];
1878          char *endmatch = ptr;          t = ptr;
1879          if (!invert)          while (t <= endmatch)
1880            {            {
1881            endmatch += offsets[1];            t = end_of_line(t, endptr, &endlinelength);
1882            t = ptr;            if (t < endmatch) linenumber++; else break;
           while (t < endmatch)  
             {  
             t = end_of_line(t, endptr, &ellength);  
             if (t <= endmatch) linenumber++; else break;  
             }  
1883            }            }
1884          endmatch = end_of_line(endmatch, endptr, &ellength);          linelength = t - ptr - endlinelength;
         linelength = endmatch - ptr - ellength;  
1885          }          }
1886    
1887        /*** NOTE: Use only fwrite() to output the data line, so that binary        /*** NOTE: Use only fwrite() to output the data line, so that binary
# Line 1358  while (ptr < endptr) Line 1908  while (ptr < endptr)
1908    
1909        if (do_colour && !invert)        if (do_colour && !invert)
1910          {          {
1911          int last_offset = 0;          int plength;
1912          FWRITE(ptr, 1, offsets[0], stdout);          FWRITE(ptr, 1, offsets[0], stdout);
1913          fprintf(stdout, "%c[%sm", 0x1b, colour_string);          fprintf(stdout, "%c[%sm", 0x1b, colour_string);
1914          FWRITE(ptr + offsets[0], 1, offsets[1] - offsets[0], stdout);          FWRITE(ptr + offsets[0], 1, offsets[1] - offsets[0], stdout);
1915          fprintf(stdout, "%c[00m", 0x1b);          fprintf(stdout, "%c[00m", 0x1b);
1916          for (;;)          for (;;)
1917            {            {
1918            last_offset += offsets[1];            startoffset = offsets[1];
1919            matchptr += offsets[1];            if (startoffset >= (int)linelength + endlinelength ||
1920            length -= offsets[1];                !match_patterns(matchptr, length, options, startoffset, offsets,
1921            if (!match_patterns(matchptr, length, offsets, &mrc)) break;                  &mrc))
1922            FWRITE(matchptr, 1, offsets[0], stdout);              break;
1923              FWRITE(matchptr + startoffset, 1, offsets[0] - startoffset, stdout);
1924            fprintf(stdout, "%c[%sm", 0x1b, colour_string);            fprintf(stdout, "%c[%sm", 0x1b, colour_string);
1925            FWRITE(matchptr + offsets[0], 1, offsets[1] - offsets[0], stdout);            FWRITE(matchptr + offsets[0], 1, offsets[1] - offsets[0], stdout);
1926            fprintf(stdout, "%c[00m", 0x1b);            fprintf(stdout, "%c[00m", 0x1b);
1927            }            }
1928          FWRITE(ptr + last_offset, 1,  
1929            (linelength + endlinelength) - last_offset, stdout);          /* In multiline mode, we may have already printed the complete line
1930            and its line-ending characters (if they matched the pattern), so there
1931            may be no more to print. */
1932    
1933            plength = (int)((linelength + endlinelength) - startoffset);
1934            if (plength > 0) FWRITE(ptr + startoffset, 1, plength, stdout);
1935          }          }
1936    
1937        /* Not colouring; no need to search for further matches */        /* Not colouring; no need to search for further matches */
# Line 1424  while (ptr < endptr) Line 1980  while (ptr < endptr)
1980    /* If input is line buffered, and the buffer is not yet full, read another    /* If input is line buffered, and the buffer is not yet full, read another
1981    line and add it into the buffer. */    line and add it into the buffer. */
1982    
1983    if (input_line_buffered && bufflength < sizeof(buffer))    if (input_line_buffered && bufflength < (size_t)bufsize)
1984      {      {
1985      int add = read_one_line(ptr, sizeof(buffer) - (ptr - buffer), in);      int add = read_one_line(ptr, bufsize - (int)(ptr - main_buffer), in);
1986      bufflength += add;      bufflength += add;
1987      endptr += add;      endptr += add;
1988      }      }
# Line 1436  while (ptr < endptr) Line 1992  while (ptr < endptr)
1992    1/3 and refill it. Before we do this, if some unprinted "after" lines are    1/3 and refill it. Before we do this, if some unprinted "after" lines are
1993    about to be lost, print them. */    about to be lost, print them. */
1994    
1995    if (bufflength >= sizeof(buffer) && ptr > buffer + 2*MBUFTHIRD)    if (bufflength >= (size_t)bufsize && ptr > main_buffer + 2*bufthird)
1996      {      {
1997      if (after_context > 0 &&      if (after_context > 0 &&
1998          lastmatchnumber > 0 &&          lastmatchnumber > 0 &&
1999          lastmatchrestart < buffer + MBUFTHIRD)          lastmatchrestart < main_buffer + bufthird)
2000        {        {
2001        do_after_lines(lastmatchnumber, lastmatchrestart, endptr, printname);        do_after_lines(lastmatchnumber, lastmatchrestart, endptr, printname);
2002        lastmatchnumber = 0;        lastmatchnumber = 0;
# Line 1448  while (ptr < endptr) Line 2004  while (ptr < endptr)
2004    
2005      /* Now do the shuffle */      /* Now do the shuffle */
2006    
2007      memmove(buffer, buffer + MBUFTHIRD, 2*MBUFTHIRD);      memmove(main_buffer, main_buffer + bufthird, 2*bufthird);
2008      ptr -= MBUFTHIRD;      ptr -= bufthird;
2009    
2010  #ifdef SUPPORT_LIBZ  #ifdef SUPPORT_LIBZ
2011      if (frtype == FR_LIBZ)      if (frtype == FR_LIBZ)
2012        bufflength = 2*MBUFTHIRD +        bufflength = 2*bufthird +
2013          gzread (ingz, buffer + 2*MBUFTHIRD, MBUFTHIRD);          gzread (ingz, main_buffer + 2*bufthird, bufthird);
2014      else      else
2015  #endif  #endif
2016    
2017  #ifdef SUPPORT_LIBBZ2  #ifdef SUPPORT_LIBBZ2
2018      if (frtype == FR_LIBBZ2)      if (frtype == FR_LIBBZ2)
2019        bufflength = 2*MBUFTHIRD +        bufflength = 2*bufthird +
2020          BZ2_bzread(inbz2, buffer + 2*MBUFTHIRD, MBUFTHIRD);          BZ2_bzread(inbz2, main_buffer + 2*bufthird, bufthird);
2021      else      else
2022  #endif  #endif
2023    
2024      bufflength = 2*MBUFTHIRD +      bufflength = 2*bufthird +
2025        (input_line_buffered?        (input_line_buffered?
2026         read_one_line(buffer + 2*MBUFTHIRD, MBUFTHIRD, in) :         read_one_line(main_buffer + 2*bufthird, bufthird, in) :
2027         fread(buffer + 2*MBUFTHIRD, 1, MBUFTHIRD, in));         fread(main_buffer + 2*bufthird, 1, bufthird, in));
2028      endptr = buffer + bufflength;      endptr = main_buffer + bufflength;
2029    
2030      /* Adjust any last match point */      /* Adjust any last match point */
2031    
2032      if (lastmatchnumber > 0) lastmatchrestart -= MBUFTHIRD;      if (lastmatchnumber > 0) lastmatchrestart -= bufthird;
2033      }      }
2034    }     /* Loop through the whole file */    }     /* Loop through the whole file */
2035    
2036  /* End of file; print final "after" lines if wanted; do_after_lines sets  /* End of file; print final "after" lines if wanted; do_after_lines sets
2037  hyphenpending if it prints something. */  hyphenpending if it prints something. */
2038    
2039  if (only_matching < 0 && !count_only)  if (!show_only_matching && !count_only)
2040    {    {
2041    do_after_lines(lastmatchnumber, lastmatchrestart, endptr, printname);    do_after_lines(lastmatchnumber, lastmatchrestart, endptr, printname);
2042    hyphenpending |= endhyphenpending;    hyphenpending |= endhyphenpending;
# Line 1524  Arguments: Line 2080  Arguments:
2080    dir_recurse       TRUE if recursing is wanted (-r or -drecurse)    dir_recurse       TRUE if recursing is wanted (-r or -drecurse)
2081    only_one_at_top   TRUE if the path is the only one at toplevel    only_one_at_top   TRUE if the path is the only one at toplevel
2082    
2083  Returns:   0 if there was at least one match  Returns:  -1 the file/directory was skipped
2084               0 if there was at least one match
2085             1 if there were no matches             1 if there were no matches
2086             2 there was some kind of error             2 there was some kind of error
2087    
# Line 1535  static int Line 2092  static int
2092  grep_or_recurse(char *pathname, BOOL dir_recurse, BOOL only_one_at_top)  grep_or_recurse(char *pathname, BOOL dir_recurse, BOOL only_one_at_top)
2093  {  {
2094  int rc = 1;  int rc = 1;
 int sep;  
2095  int frtype;  int frtype;
 int pathlen;  
2096  void *handle;  void *handle;
2097    char *lastcomp;
2098  FILE *in = NULL;           /* Ensure initialized */  FILE *in = NULL;           /* Ensure initialized */
2099    
2100  #ifdef SUPPORT_LIBZ  #ifdef SUPPORT_LIBZ
# Line 1549  gzFile ingz = NULL; Line 2105  gzFile ingz = NULL;
2105  BZFILE *inbz2 = NULL;  BZFILE *inbz2 = NULL;
2106  #endif  #endif
2107    
2108    #if defined SUPPORT_LIBZ || defined SUPPORT_LIBBZ2
2109    int pathlen;
2110    #endif
2111    
2112    #if defined NATIVE_ZOS
2113    int zos_type;
2114    FILE *zos_test_file;
2115    #endif
2116    
2117  /* If the file name is "-" we scan stdin */  /* If the file name is "-" we scan stdin */
2118    
2119  if (strcmp(pathname, "-") == 0)  if (strcmp(pathname, "-") == 0)
2120    {    {
2121    return pcregrep(stdin, FR_PLAIN,    return pcregrep(stdin, FR_PLAIN, stdin_name,
2122      (filenames > FN_DEFAULT || (filenames == FN_DEFAULT && !only_one_at_top))?      (filenames > FN_DEFAULT || (filenames == FN_DEFAULT && !only_one_at_top))?
2123        stdin_name : NULL);        stdin_name : NULL);
2124    }    }
2125    
2126  /* If the file is a directory, skip if skipping or if we are recursing, scan  /* Inclusion and exclusion: --include-dir and --exclude-dir apply only to
2127  each file and directory within it, subject to any include or exclude patterns  directories, whereas --include and --exclude apply to everything else. The test
2128  that were set. The scanning code is localized so it can be made  is against the final component of the path. */
2129  system-specific. */  
2130    lastcomp = strrchr(pathname, FILESEP);
2131    lastcomp = (lastcomp == NULL)? pathname : lastcomp + 1;
2132    
2133    /* If the file is a directory, skip if not recursing or if explicitly excluded.
2134    Otherwise, scan the directory and recurse for each path within it. The scanning
2135    code is localized so it can be made system-specific. */
2136    
2137    
2138    /* For z/OS, determine the file type. */
2139    
2140    #if defined NATIVE_ZOS
2141    zos_test_file =  fopen(pathname,"rb");
2142    
2143    if (zos_test_file == NULL)
2144       {
2145       if (!silent) fprintf(stderr, "pcregrep: failed to test next file %s\n",
2146         pathname, strerror(errno));
2147       return -1;
2148       }
2149    zos_type = identifyzosfiletype (zos_test_file);
2150    fclose (zos_test_file);
2151    
2152    /* Handle a PDS in separate code */
2153    
2154    if (zos_type == __ZOS_PDS || zos_type == __ZOS_PDSE)
2155       {
2156       return travelonpdsdir (pathname, only_one_at_top);
2157       }
2158    
2159    /* Deal with regular files in the normal way below. These types are:
2160       zos_type == __ZOS_PDS_MEMBER
2161       zos_type == __ZOS_PS
2162       zos_type == __ZOS_VSAM_KSDS
2163       zos_type == __ZOS_VSAM_ESDS
2164       zos_type == __ZOS_VSAM_RRDS
2165    */
2166    
2167    /* Handle a z/OS directory using common code. */
2168    
2169    else if (zos_type == __ZOS_HFS)
2170     {
2171    #endif  /* NATIVE_ZOS */
2172    
2173    
2174  if ((sep = isdirectory(pathname)) != 0)  /* Handle directories: common code for all OS */
2175    
2176    if (isdirectory(pathname))
2177    {    {
2178    if (dee_action == dee_SKIP) return 1;    if (dee_action == dee_SKIP ||
2179          !test_incexc(lastcomp, include_dir_patterns, exclude_dir_patterns))
2180        return -1;
2181    
2182    if (dee_action == dee_RECURSE)    if (dee_action == dee_RECURSE)
2183      {      {
2184      char buffer[1024];      char buffer[1024];
# Line 1582  if ((sep = isdirectory(pathname)) != 0) Line 2195  if ((sep = isdirectory(pathname)) != 0)
2195    
2196      while ((nextfile = readdirectory(dir)) != NULL)      while ((nextfile = readdirectory(dir)) != NULL)
2197        {        {
2198        int frc, nflen;        int frc;
2199        sprintf(buffer, "%.512s%c%.128s", pathname, sep, nextfile);        sprintf(buffer, "%.512s%c%.128s", pathname, FILESEP, nextfile);
       nflen = (int)(strlen(nextfile));  
   
       if (isdirectory(buffer))  
         {  
         if (exclude_dir_compiled != NULL &&  
             pcre_exec(exclude_dir_compiled, NULL, nextfile, nflen, 0, 0, NULL, 0) >= 0)  
           continue;  
   
         if (include_dir_compiled != NULL &&  
             pcre_exec(include_dir_compiled, NULL, nextfile, nflen, 0, 0, NULL, 0) < 0)  
           continue;  
         }  
       else  
         {  
         if (exclude_compiled != NULL &&  
             pcre_exec(exclude_compiled, NULL, nextfile, nflen, 0, 0, NULL, 0) >= 0)  
           continue;  
   
         if (include_compiled != NULL &&  
             pcre_exec(include_compiled, NULL, nextfile, nflen, 0, 0, NULL, 0) < 0)  
           continue;  
         }  
   
2200        frc = grep_or_recurse(buffer, dir_recurse, FALSE);        frc = grep_or_recurse(buffer, dir_recurse, FALSE);
2201        if (frc > 1) rc = frc;        if (frc > 1) rc = frc;
2202         else if (frc == 0 && rc == 1) rc = 0;         else if (frc == 0 && rc == 1) rc = 0;
# Line 1617  if ((sep = isdirectory(pathname)) != 0) Line 2207  if ((sep = isdirectory(pathname)) != 0)
2207      }      }
2208    }    }
2209    
2210  /* If the file is not a directory and not a regular file, skip it if that's  #if defined NATIVE_ZOS
2211  been requested. */   }
2212    #endif
2213    
2214  else if (!isregfile(pathname) && DEE_action == DEE_SKIP) return 1;  /* If the file is not a directory, check for a regular file, and if it is not,
2215    skip it if that's been requested. Otherwise, check for an explicit inclusion or
2216    exclusion. */
2217    
2218    else if (
2219    #if defined NATIVE_ZOS
2220            (zos_type == __ZOS_NOFILE && DEE_action == DEE_SKIP) ||
2221    #else  /* all other OS */
2222            (!isregfile(pathname) && DEE_action == DEE_SKIP) ||
2223    #endif
2224            !test_incexc(lastcomp, include_patterns, exclude_patterns))
2225      return -1;  /* File skipped */
2226    
2227  /* Control reaches here if we have a regular file, or if we have a directory  /* Control reaches here if we have a regular file, or if we have a directory
2228  and recursion or skipping was not requested, or if we have anything else and  and recursion or skipping was not requested, or if we have anything else and
# Line 1628  skipping was not requested. The scan pro Line 2230  skipping was not requested. The scan pro
2230  argument at top level, we don't show the file name, unless we are only showing  argument at top level, we don't show the file name, unless we are only showing
2231  the file name, or the filename was forced (-H). */  the file name, or the filename was forced (-H). */
2232    
2233    #if defined SUPPORT_LIBZ || defined SUPPORT_LIBBZ2
2234  pathlen = (int)(strlen(pathname));  pathlen = (int)(strlen(pathname));
2235    #endif
2236    
2237  /* Open using zlib if it is supported and the file name ends with .gz. */  /* Open using zlib if it is supported and the file name ends with .gz. */
2238    
# Line 1685  if (handle == NULL) Line 2289  if (handle == NULL)
2289    
2290  /* Now grep the file */  /* Now grep the file */
2291    
2292  rc = pcregrep(handle, frtype, (filenames > FN_DEFAULT ||  rc = pcregrep(handle, frtype, pathname, (filenames > FN_DEFAULT ||
2293    (filenames == FN_DEFAULT && !only_one_at_top))? pathname : NULL);    (filenames == FN_DEFAULT && !only_one_at_top))? pathname : NULL);
2294    
2295  /* Close in an appropriate manner. */  /* Close in an appropriate manner. */
# Line 1696  if (frtype == FR_LIBZ) Line 2300  if (frtype == FR_LIBZ)
2300  else  else
2301  #endif  #endif
2302    
2303  /* If it is a .bz2 file and the result is 2, it means that the first attempt to  /* If it is a .bz2 file and the result is 3, it means that the first attempt to
2304  read failed. If the error indicates that the file isn't in fact bzipped, try  read failed. If the error indicates that the file isn't in fact bzipped, try
2305  again as a normal file. */  again as a normal file. */
2306    
2307  #ifdef SUPPORT_LIBBZ2  #ifdef SUPPORT_LIBBZ2
2308  if (frtype == FR_LIBBZ2)  if (frtype == FR_LIBBZ2)
2309    {    {
2310    if (rc == 2)    if (rc == 3)
2311      {      {
2312      int errnum;      int errnum;
2313      const char *err = BZ2_bzerror(inbz2, &errnum);      const char *err = BZ2_bzerror(inbz2, &errnum);
# Line 1715  if (frtype == FR_LIBBZ2) Line 2319  if (frtype == FR_LIBBZ2)
2319      else if (!silent)      else if (!silent)
2320        fprintf(stderr, "pcregrep: Failed to read %s using bzlib: %s\n",        fprintf(stderr, "pcregrep: Failed to read %s using bzlib: %s\n",
2321          pathname, err);          pathname, err);
2322        rc = 2;    /* The normal "something went wrong" code */
2323      }      }
2324    BZ2_bzclose(inbz2);    BZ2_bzclose(inbz2);
2325    }    }
# Line 1732  return rc; Line 2337  return rc;
2337    
2338    
2339    
   
 /*************************************************  
 *                Usage function                  *  
 *************************************************/  
   
 static int  
 usage(int rc)  
 {  
 option_item *op;  
 fprintf(stderr, "Usage: pcregrep [-");  
 for (op = optionlist; op->one_char != 0; op++)  
   {  
   if (op->one_char > 0) fprintf(stderr, "%c", op->one_char);  
   }  
 fprintf(stderr, "] [long options] [pattern] [files]\n");  
 fprintf(stderr, "Type `pcregrep --help' for more information and the long "  
   "options.\n");  
 return rc;  
 }  
   
   
   
   
 /*************************************************  
 *                Help function                   *  
 *************************************************/  
   
 static void  
 help(void)  
 {  
 option_item *op;  
   
 printf("Usage: pcregrep [OPTION]... [PATTERN] [FILE1 FILE2 ...]\n");  
 printf("Search for PATTERN in each FILE or standard input.\n");  
 printf("PATTERN must be present if neither -e nor -f is used.\n");  
 printf("\"-\" can be used as a file name to mean STDIN.\n");  
   
 #ifdef SUPPORT_LIBZ  
 printf("Files whose names end in .gz are read using zlib.\n");  
 #endif  
   
 #ifdef SUPPORT_LIBBZ2  
 printf("Files whose names end in .bz2 are read using bzlib2.\n");  
 #endif  
   
 #if defined SUPPORT_LIBZ || defined SUPPORT_LIBBZ2  
 printf("Other files and the standard input are read as plain files.\n\n");  
 #else  
 printf("All files are read as plain files, without any interpretation.\n\n");  
 #endif  
   
 printf("Example: pcregrep -i 'hello.*world' menu.h main.c\n\n");  
 printf("Options:\n");  
   
 for (op = optionlist; op->one_char != 0; op++)  
   {  
   int n;  
   char s[4];  
   
   /* Two options were accidentally implemented and documented with underscores  
   instead of hyphens in their names, something that was not noticed for quite a  
   few releases. When fixing this, I left the underscored versions in the list  
   in case people were using them. However, we don't want to display them in the  
   help data. There are no other options that contain underscores, and we do not  
   expect ever to implement such options. Therefore, just omit any option that  
   contains an underscore. */  
   
   if (strchr(op->long_name, '_') != NULL) continue;  
   
   if (op->one_char > 0) sprintf(s, "-%c,", op->one_char); else strcpy(s, "   ");  
   n = 31 - printf("  %s --%s", s, op->long_name);  
   if (n < 1) n = 1;  
   printf("%.*s%s\n", n, "                     ", op->help_text);  
   }  
   
 printf("\nWhen reading patterns from a file instead of using a command line option,\n");  
 printf("trailing white space is removed and blank lines are ignored.\n");  
 printf("There is a maximum of %d patterns.\n", MAX_PATTERN_COUNT);  
   
 printf("\nWith no FILEs, read standard input. If fewer than two FILEs given, assume -h.\n");  
 printf("Exit status is 0 if any matches, 1 if no matches, and 2 if trouble.\n");  
 }  
   
   
   
   
2340  /*************************************************  /*************************************************
2341  *    Handle a single-letter, no data option      *  *    Handle a single-letter, no data option      *
2342  *************************************************/  *************************************************/
# Line 1829  switch(letter) Line 2348  switch(letter)
2348    {    {
2349    case N_FOFFSETS: file_offsets = TRUE; break;    case N_FOFFSETS: file_offsets = TRUE; break;
2350    case N_HELP: help(); pcregrep_exit(0);    case N_HELP: help(); pcregrep_exit(0);
   case N_LOFFSETS: line_offsets = number = TRUE; break;  
2351    case N_LBUFFER: line_buffered = TRUE; break;    case N_LBUFFER: line_buffered = TRUE; break;
2352      case N_LOFFSETS: line_offsets = number = TRUE; break;
2353      case N_NOJIT: study_options &= ~PCRE_STUDY_JIT_COMPILE; break;
2354      case 'a': binary_files = BIN_TEXT; break;
2355    case 'c': count_only = TRUE; break;    case 'c': count_only = TRUE; break;
2356    case 'F': process_options |= PO_FIXED_STRINGS; break;    case 'F': process_options |= PO_FIXED_STRINGS; break;
2357    case 'H': filenames = FN_FORCE; break;    case 'H': filenames = FN_FORCE; break;
2358      case 'I': binary_files = BIN_NOMATCH; break;
2359    case 'h': filenames = FN_NONE; break;    case 'h': filenames = FN_NONE; break;
2360    case 'i': options |= PCRE_CASELESS; break;    case 'i': options |= PCRE_CASELESS; break;
2361    case 'l': omit_zero_count = TRUE; filenames = FN_MATCH_ONLY; break;    case 'l': omit_zero_count = TRUE; filenames = FN_MATCH_ONLY; break;
2362    case 'L': filenames = FN_NOMATCH_ONLY; break;    case 'L': filenames = FN_NOMATCH_ONLY; break;
2363    case 'M': multiline = TRUE; options |= PCRE_MULTILINE|PCRE_FIRSTLINE; break;    case 'M': multiline = TRUE; options |= PCRE_MULTILINE|PCRE_FIRSTLINE; break;
2364    case 'n': number = TRUE; break;    case 'n': number = TRUE; break;
2365    case 'o': only_matching = 0; break;  
2366      case 'o':
2367      only_matching_last = add_number(0, only_matching_last);
2368      if (only_matching == NULL) only_matching = only_matching_last;
2369      break;
2370    
2371    case 'q': quiet = TRUE; break;    case 'q': quiet = TRUE; break;
2372    case 'r': dee_action = dee_RECURSE; break;    case 'r': dee_action = dee_RECURSE; break;
2373    case 's': silent = TRUE; break;    case 's': silent = TRUE; break;
# Line 1850  switch(letter) Line 2377  switch(letter)
2377    case 'x': process_options |= PO_LINE_MATCH; break;    case 'x': process_options |= PO_LINE_MATCH; break;
2378    
2379    case 'V':    case 'V':
2380    fprintf(stderr, "pcregrep version %s\n", pcre_version());    fprintf(stdout, "pcregrep version %s\n", pcre_version());
2381    pcregrep_exit(0);    pcregrep_exit(0);
2382    break;    break;
2383    
# Line 1894  return buffer; Line 2421  return buffer;
2421  *          Compile a single pattern              *  *          Compile a single pattern              *
2422  *************************************************/  *************************************************/
2423    
2424  /* When the -F option has been used, this is called for each substring.  /* Do nothing if the pattern has already been compiled. This is the case for
2425  Otherwise it's called for each supplied pattern.  include/exclude patterns read from a file.
2426    
2427    When the -F option has been used, each "pattern" may be a list of strings,
2428    separated by line breaks. They will be matched literally. We split such a
2429    string and compile the first substring, inserting an additional block into the
2430    pattern chain.
2431    
2432  Arguments:  Arguments:
2433    pattern        the pattern string    p              points to the pattern block
2434    options        the PCRE options    options        the PCRE options
2435    filename       the file name, or NULL for a command-line pattern    popts          the processing options
2436      fromfile       TRUE if the pattern was read from a file
2437      fromtext       file name or identifying text (e.g. "include")
2438    count          0 if this is the only command line pattern, or    count          0 if this is the only command line pattern, or
2439                   number of the command line pattern, or                   number of the command line pattern, or
2440                   linenumber for a pattern from a file                   linenumber for a pattern from a file
# Line 1909  Returns:         TRUE on success, FALSE Line 2443  Returns:         TRUE on success, FALSE
2443  */  */
2444    
2445  static BOOL  static BOOL
2446  compile_single_pattern(char *pattern, int options, char *filename, int count)  compile_pattern(patstr *p, int options, int popts, int fromfile,
2447      const char *fromtext, int count)
2448  {  {
2449  char buffer[MBUFTHIRD + 16];  char buffer[PATBUFSIZE];
2450  const char *error;  const char *error;
2451    char *ps = p->string;
2452    int patlen = strlen(ps);
2453  int errptr;  int errptr;
2454    
2455  if (pattern_count >= MAX_PATTERN_COUNT)  if (p->compiled != NULL) return TRUE;
   {  
   fprintf(stderr, "pcregrep: Too many %spatterns (max %d)\n",  
     (filename == NULL)? "command-line " : "", MAX_PATTERN_COUNT);  
   return FALSE;  
   }  
2456    
2457  sprintf(buffer, "%s%.*s%s", prefix[process_options], MBUFTHIRD, pattern,  if ((popts & PO_FIXED_STRINGS) != 0)
   suffix[process_options]);  
 pattern_list[pattern_count] =  
   pcre_compile(buffer, options, &error, &errptr, pcretables);  
 if (pattern_list[pattern_count] != NULL)  
2458    {    {
2459    pattern_count++;    int ellength;
2460    return TRUE;    char *eop = ps + patlen;
2461      char *pe = end_of_line(ps, eop, &ellength);
2462    
2463      if (ellength != 0)
2464        {
2465        if (add_pattern(pe, p) == NULL) return FALSE;
2466        patlen = (int)(pe - ps - ellength);
2467        }
2468    }    }
2469    
2470    sprintf(buffer, "%s%.*s%s", prefix[popts], patlen, ps, suffix[popts]);
2471    p->compiled = pcre_compile(buffer, options, &error, &errptr, pcretables);
2472    if (p->compiled != NULL) return TRUE;
2473    
2474  /* Handle compile errors */  /* Handle compile errors */
2475    
2476  errptr -= (int)strlen(prefix[process_options]);  errptr -= (int)strlen(prefix[popts]);
2477  if (errptr > (int)strlen(pattern)) errptr = (int)strlen(pattern);  if (errptr > patlen) errptr = patlen;
2478    
2479  if (filename == NULL)  if (fromfile)
2480    {    {
2481    if (count == 0)    fprintf(stderr, "pcregrep: Error in regex in line %d of %s "
2482      fprintf(stderr, "pcregrep: Error in command-line regex "      "at offset %d: %s\n", count, fromtext, errptr, error);
       "at offset %d: %s\n", errptr, error);  
   else  
     fprintf(stderr, "pcregrep: Error in %s command-line regex "  
       "at offset %d: %s\n", ordin(count), errptr, error);  
2483    }    }
2484  else  else
2485    {    {
2486    fprintf(stderr, "pcregrep: Error in regex in line %d of %s "    if (count == 0)
2487      "at offset %d: %s\n", count, filename, errptr, error);      fprintf(stderr, "pcregrep: Error in %s regex at offset %d: %s\n",
2488          fromtext, errptr, error);
2489      else
2490        fprintf(stderr, "pcregrep: Error in %s %s regex at offset %d: %s\n",
2491          ordin(count), fromtext, errptr, error);
2492    }    }
2493    
2494  return FALSE;  return FALSE;
# Line 1958  return FALSE; Line 2497  return FALSE;
2497    
2498    
2499  /*************************************************  /*************************************************
2500  *           Compile one supplied pattern         *  *     Read and compile a file of patterns        *
2501  *************************************************/  *************************************************/
2502    
2503  /* When the -F option has been used, each string may be a list of strings,  /* This is used for --filelist, --include-from, and --exclude-from.
 separated by line breaks. They will be matched literally.  
2504    
2505  Arguments:  Arguments:
2506    pattern        the pattern string    name         the name of the file; "-" is stdin
2507    options        the PCRE options    patptr       pointer to the pattern chain anchor
2508    filename       the file name, or NULL for a command-line pattern    patlastptr   pointer to the last pattern pointer
2509    count          0 if this is the only command line pattern, or    popts        the process options to pass to pattern_compile()
                  number of the command line pattern, or  
                  linenumber for a pattern from a file  
2510    
2511  Returns:         TRUE on success, FALSE after an error  Returns:       TRUE if all went well
2512  */  */
2513    
2514  static BOOL  static BOOL
2515  compile_pattern(char *pattern, int options, char *filename, int count)  read_pattern_file(char *name, patstr **patptr, patstr **patlastptr, int popts)
2516  {  {
2517  if ((process_options & PO_FIXED_STRINGS) != 0)  int linenumber = 0;
2518    FILE *f;
2519    char *filename;
2520    char buffer[PATBUFSIZE];
2521    
2522    if (strcmp(name, "-") == 0)
2523      {
2524      f = stdin;
2525      filename = stdin_name;
2526      }
2527    else
2528    {    {
2529    char *eop = pattern + strlen(pattern);    f = fopen(name, "r");
2530    char buffer[MBUFTHIRD];    if (f == NULL)
2531        {
2532        fprintf(stderr, "pcregrep: Failed to open %s: %s\n", name, strerror(errno));
2533        return FALSE;
2534        }
2535      filename = name;
2536      }
2537    
2538    while (fgets(buffer, PATBUFSIZE, f) != NULL)
2539      {
2540      char *s = buffer + (int)strlen(buffer);
2541      while (s > buffer && isspace((unsigned char)(s[-1]))) s--;
2542      *s = 0;
2543      linenumber++;
2544      if (buffer[0] == 0) continue;   /* Skip blank lines */
2545    
2546      /* Note: this call to add_pattern() puts a pointer to the local variable
2547      "buffer" into the pattern chain. However, that pointer is used only when
2548      compiling the pattern, which happens immediately below, so we flatten it
2549      afterwards, as a precaution against any later code trying to use it. */
2550    
2551      *patlastptr = add_pattern(buffer, *patlastptr);
2552      if (*patlastptr == NULL) return FALSE;
2553      if (*patptr == NULL) *patptr = *patlastptr;
2554    
2555      /* This loop is needed because compiling a "pattern" when -F is set may add
2556      on additional literal patterns if the original contains a newline. In the
2557      common case, it never will, because fgets() stops at a newline. However,
2558      the -N option can be used to give pcregrep a different newline setting. */
2559    
2560    for(;;)    for(;;)
2561      {      {
2562      int ellength;      if (!compile_pattern(*patlastptr, pcre_options, popts, TRUE, filename,
2563      char *p = end_of_line(pattern, eop, &ellength);          linenumber))
     if (ellength == 0)  
       return compile_single_pattern(pattern, options, filename, count);  
     sprintf(buffer, "%.*s", (int)(p - pattern - ellength), pattern);  
     pattern = p;  
     if (!compile_single_pattern(buffer, options, filename, count))  
2564        return FALSE;        return FALSE;
2565        (*patlastptr)->string = NULL;            /* Insurance */
2566        if ((*patlastptr)->next == NULL) break;
2567        *patlastptr = (*patlastptr)->next;
2568      }      }
2569    }    }
2570  else return compile_single_pattern(pattern, options, filename, count);  
2571    if (f != stdin) fclose(f);
2572    return TRUE;
2573  }  }
2574    
2575    
# Line 2010  main(int argc, char **argv) Line 2585  main(int argc, char **argv)
2585  {  {
2586  int i, j;  int i, j;
2587  int rc = 1;  int rc = 1;
 int pcre_options = 0;  
 int cmd_pattern_count = 0;  
 int hint_count = 0;  
 int errptr;  
2588  BOOL only_one_at_top;  BOOL only_one_at_top;
2589  char *patterns[MAX_PATTERN_COUNT];  patstr *cp;
2590    fnstr *fn;
2591  const char *locale_from = "--locale";  const char *locale_from = "--locale";
2592  const char *error;  const char *error;
2593    
2594    #ifdef SUPPORT_PCREGREP_JIT
2595    pcre_jit_stack *jit_stack = NULL;
2596    #endif
2597    
2598  /* Set the default line ending value from the default in the PCRE library;  /* Set the default line ending value from the default in the PCRE library;
2599  "lf", "cr", "crlf", and "any" are supported. Anything else is treated as "lf".  "lf", "cr", "crlf", and "any" are supported. Anything else is treated as "lf".
2600  Note that the return values from pcre_config(), though derived from the ASCII  Note that the return values from pcre_config(), though derived from the ASCII
# Line 2051  for (i = 1; i < argc; i++) Line 2627  for (i = 1; i < argc; i++)
2627    
2628    if (argv[i][1] == 0)    if (argv[i][1] == 0)
2629      {      {
2630      if (pattern_filename != NULL || pattern_count > 0) break;      if (pattern_files != NULL || patterns != NULL) break;
2631        else pcregrep_exit(usage(2));        else pcregrep_exit(usage(2));
2632      }      }
2633    
# Line 2177  for (i = 1; i < argc; i++) Line 2753  for (i = 1; i < argc; i++)
2753      {      {
2754      char *s = argv[i] + 1;      char *s = argv[i] + 1;
2755      longop = FALSE;      longop = FALSE;
2756    
2757      while (*s != 0)      while (*s != 0)
2758        {        {
2759        for (op = optionlist; op->one_char != 0; op++)        for (op = optionlist; op->one_char != 0; op++)
# Line 2190  for (i = 1; i < argc; i++) Line 2767  for (i = 1; i < argc; i++)
2767          pcregrep_exit(usage(2));          pcregrep_exit(usage(2));
2768          }          }
2769    
2770        /* Check for a single-character option that has data: OP_OP_NUMBER        option_data = s+1;
2771        is used for one that either has a numerical number or defaults, i.e. the  
2772        data is optional. If a digit follows, there is data; if not, carry on        /* Break out if this is the last character in the string; it's handled
2773          below like a single multi-char option. */
2774    
2775          if (*option_data == 0) break;
2776    
2777          /* Check for a single-character option that has data: OP_OP_NUMBER(S)
2778          are used for ones that either have a numerical number or defaults, i.e.
2779          the data is optional. If a digit follows, there is data; if not, carry on
2780        with other single-character options in the same string. */        with other single-character options in the same string. */
2781    
2782        option_data = s+1;        if (op->type == OP_OP_NUMBER || op->type == OP_OP_NUMBERS)
       if (op->type == OP_OP_NUMBER)  
2783          {          {
2784          if (isdigit((unsigned char)s[1])) break;          if (isdigit((unsigned char)s[1])) break;
2785          }          }
2786        else   /* Check for end or a dataless option */        else   /* Check for an option with data */
2787          {          {
2788          if (op->type != OP_NODATA || s[1] == 0) break;          if (op->type != OP_NODATA) break;
2789          }          }
2790    
2791        /* Handle a single-character option with no data, then loop for the        /* Handle a single-character option with no data, then loop for the
# Line 2222  for (i = 1; i < argc; i++) Line 2805  for (i = 1; i < argc; i++)
2805      continue;      continue;
2806      }      }
2807    
2808    /* If the option type is OP_OP_STRING or OP_OP_NUMBER, it's an option that    /* If the option type is OP_OP_STRING or OP_OP_NUMBER(S), it's an option that
2809    either has a value or defaults to something. It cannot have data in a    either has a value or defaults to something. It cannot have data in a
2810    separate item. At the moment, the only such options are "colo(u)r",    separate item. At the moment, the only such options are "colo(u)r",
2811    "only-matching", and Jeffrey Friedl's special -S debugging option. */    "only-matching", and Jeffrey Friedl's special -S debugging option. */
2812    
2813    if (*option_data == 0 &&    if (*option_data == 0 &&
2814        (op->type == OP_OP_STRING || op->type == OP_OP_NUMBER))        (op->type == OP_OP_STRING || op->type == OP_OP_NUMBER ||
2815           op->type == OP_OP_NUMBERS))
2816      {      {
2817      switch (op->one_char)      switch (op->one_char)
2818        {        {
# Line 2237  for (i = 1; i < argc; i++) Line 2821  for (i = 1; i < argc; i++)
2821        break;        break;
2822    
2823        case 'o':        case 'o':
2824        only_matching = 0;        only_matching_last = add_number(0, only_matching_last);
2825          if (only_matching == NULL) only_matching = only_matching_last;
2826        break;        break;
2827    
2828  #ifdef JFRIEDL_DEBUG  #ifdef JFRIEDL_DEBUG
# Line 2261  for (i = 1; i < argc; i++) Line 2846  for (i = 1; i < argc; i++)
2846      option_data = argv[++i];      option_data = argv[++i];
2847      }      }
2848    
2849    /* If the option type is OP_PATLIST, it's the -e option, which can be called    /* If the option type is OP_OP_NUMBERS, the value is a number that is to be
2850    multiple times to create a list of patterns. */    added to a chain of numbers. */
2851    
2852    if (op->type == OP_PATLIST)    if (op->type == OP_OP_NUMBERS)
2853      {      {
2854      if (cmd_pattern_count >= MAX_PATTERN_COUNT)      unsigned long int n = decode_number(option_data, op, longop);
2855        omdatastr *omd = (omdatastr *)op->dataptr;
2856        *(omd->lastptr) = add_number((int)n, *(omd->lastptr));
2857        if (*(omd->anchor) == NULL) *(omd->anchor) = *(omd->lastptr);
2858        }
2859    
2860      /* If the option type is OP_PATLIST, it's the -e option, or one of the
2861      include/exclude options, which can be called multiple times to create lists
2862      of patterns. */
2863    
2864      else if (op->type == OP_PATLIST)
2865        {
2866        patdatastr *pd = (patdatastr *)op->dataptr;
2867        *(pd->lastptr) = add_pattern(option_data, *(pd->lastptr));
2868        if (*(pd->lastptr) == NULL) goto EXIT2;
2869        if (*(pd->anchor) == NULL) *(pd->anchor) = *(pd->lastptr);
2870        }
2871    
2872      /* If the option type is OP_FILELIST, it's one of the options that names a
2873      file. */
2874    
2875      else if (op->type == OP_FILELIST)
2876        {
2877        fndatastr *fd = (fndatastr *)op->dataptr;
2878        fn = (fnstr *)malloc(sizeof(fnstr));
2879        if (fn == NULL)
2880        {        {
2881        fprintf(stderr, "pcregrep: Too many command-line patterns (max %d)\n",        fprintf(stderr, "pcregrep: malloc failed\n");
2882          MAX_PATTERN_COUNT);        goto EXIT2;
2883        return 2;        }
2884        fn->next = NULL;
2885        fn->name = option_data;
2886        if (*(fd->anchor) == NULL)
2887          *(fd->anchor) = fn;
2888        else
2889          (*(fd->lastptr))->next = fn;
2890        *(fd->lastptr) = fn;
2891        }
2892    
2893      /* Handle OP_BINARY_FILES */
2894    
2895      else if (op->type == OP_BINFILES)
2896        {
2897        if (strcmp(option_data, "binary") == 0)
2898          binary_files = BIN_BINARY;
2899        else if (strcmp(option_data, "without-match") == 0)
2900          binary_files = BIN_NOMATCH;
2901        else if (strcmp(option_data, "text") == 0)
2902          binary_files = BIN_TEXT;
2903        else
2904          {
2905          fprintf(stderr, "pcregrep: unknown value \"%s\" for binary-files\n",
2906            option_data);
2907          pcregrep_exit(usage(2));
2908        }        }
     patterns[cmd_pattern_count++] = option_data;  
2909      }      }
2910    
2911    /* Otherwise, deal with single string or numeric data values. */    /* Otherwise, deal with a single string or numeric data value. */
2912    
2913    else if (op->type != OP_NUMBER && op->type != OP_LONGNUMBER &&    else if (op->type != OP_NUMBER && op->type != OP_LONGNUMBER &&
2914             op->type != OP_OP_NUMBER)             op->type != OP_OP_NUMBER)
2915      {      {
2916      *((char **)op->dataptr) = option_data;      *((char **)op->dataptr) = option_data;
2917      }      }
   
   /* Avoid the use of strtoul() because SunOS4 doesn't have it. This is used  
   only for unpicking arguments, so just keep it simple. */  
   
2918    else    else
2919      {      {
2920      unsigned long int n = 0;      unsigned long int n = decode_number(option_data, op, longop);
2921      char *endptr = option_data;      if (op->type == OP_LONGNUMBER) *((unsigned long int *)op->dataptr) = n;
2922      while (*endptr != 0 && isspace((unsigned char)(*endptr))) endptr++;        else *((int *)op->dataptr) = n;
     while (isdigit((unsigned char)(*endptr)))  
       n = n * 10 + (int)(*endptr++ - '0');  
     if (*endptr != 0)  
       {  
       if (longop)  
         {  
         char *equals = strchr(op->long_name, '=');  
         int nlen = (equals == NULL)? (int)strlen(op->long_name) :  
           (int)(equals - op->long_name);  
         fprintf(stderr, "pcregrep: Malformed number \"%s\" after --%.*s\n",  
           option_data, nlen, op->long_name);  
         }  
       else  
         fprintf(stderr, "pcregrep: Malformed number \"%s\" after -%c\n",  
           option_data, op->one_char);  
       pcregrep_exit(usage(2));  
       }  
     if (op->type == OP_LONGNUMBER)  
         *((unsigned long int *)op->dataptr) = n;  
     else  
         *((int *)op->dataptr) = n;  
2923      }      }
2924    }    }
2925    
# Line 2325  if (both_context > 0) Line 2933  if (both_context > 0)
2933    }    }
2934    
2935  /* Only one of --only-matching, --file-offsets, or --line-offsets is permitted.  /* Only one of --only-matching, --file-offsets, or --line-offsets is permitted.
2936  However, the latter two set only_matching. */  However, all three set show_only_matching because they display, each in their
2937    own way, only the data that has matched. */
2938    
2939  if ((only_matching >= 0 && (file_offsets || line_offsets)) ||  if ((only_matching != NULL && (file_offsets || line_offsets)) ||
2940      (file_offsets && line_offsets))      (file_offsets && line_offsets))
2941    {    {
2942    fprintf(stderr, "pcregrep: Cannot mix --only-matching, --file-offsets "    fprintf(stderr, "pcregrep: Cannot mix --only-matching, --file-offsets "
# Line 2335  if ((only_matching >= 0 && (file_offsets Line 2944  if ((only_matching >= 0 && (file_offsets
2944    pcregrep_exit(usage(2));    pcregrep_exit(usage(2));
2945    }    }
2946    
2947  if (file_offsets || line_offsets) only_matching = 0;  if (only_matching != NULL || file_offsets || line_offsets)
2948      show_only_matching = TRUE;
2949    
2950  /* If a locale has not been provided as an option, see if the LC_CTYPE or  /* If a locale has not been provided as an option, see if the LC_CTYPE or
2951  LC_ALL environment variable is set, and if so, use it. */  LC_ALL environment variable is set, and if so, use it. */
# Line 2459  if (jfriedl_XT != 0 || jfriedl_XR != 0) Line 3069  if (jfriedl_XT != 0 || jfriedl_XR != 0)
3069    }    }
3070  #endif  #endif
3071    
3072  /* Get memory to store the pattern and hints lists. */  /* Get memory for the main buffer. */
3073    
3074  pattern_list = (pcre **)malloc(MAX_PATTERN_COUNT * sizeof(pcre *));  bufsize = 3*bufthird;
3075  hints_list = (pcre_extra **)malloc(MAX_PATTERN_COUNT * sizeof(pcre_extra *));  main_buffer = (char *)malloc(bufsize);
3076    
3077  if (pattern_list == NULL || hints_list == NULL)  if (main_buffer == NULL)
3078    {    {
3079    fprintf(stderr, "pcregrep: malloc failed\n");    fprintf(stderr, "pcregrep: malloc failed\n");
3080    goto EXIT2;    goto EXIT2;
3081    }    }
3082    
3083  /* If no patterns were provided by -e, and there is no file provided by -f,  /* If no patterns were provided by -e, and there are no files provided by -f,
3084  the first argument is the one and only pattern, and it must exist. */  the first argument is the one and only pattern, and it must exist. */
3085    
3086  if (cmd_pattern_count == 0 && pattern_filename == NULL)  if (patterns == NULL && pattern_files == NULL)
3087    {    {
3088    if (i >= argc) return usage(2);    if (i >= argc) return usage(2);
3089    patterns[cmd_pattern_count++] = argv[i++];    patterns = patterns_last = add_pattern(argv[i++], NULL);
3090      if (patterns == NULL) goto EXIT2;
3091    }    }
3092    
3093  /* Compile the patterns that were provided on the command line, either by  /* Compile the patterns that were provided on the command line, either by
3094  multiple uses of -e or as a single unkeyed pattern. */  multiple uses of -e or as a single unkeyed pattern. We cannot do this until
3095    after all the command-line options are read so that we know which PCRE options
3096    to use. When -F is used, compile_pattern() may add another block into the
3097    chain, so we must not access the next pointer till after the compile. */
3098    
3099  for (j = 0; j < cmd_pattern_count; j++)  for (j = 1, cp = patterns; cp != NULL; j++, cp = cp->next)
3100    {    {
3101    if (!compile_pattern(patterns[j], pcre_options, NULL,    if (!compile_pattern(cp, pcre_options, process_options, FALSE, "command-line",
3102         (j == 0 && cmd_pattern_count == 1)? 0 : j + 1))         (j == 1 && patterns->next == NULL)? 0 : j))
3103      goto EXIT2;      goto EXIT2;
3104    }    }
3105    
3106  /* Compile the regular expressions that are provided in a file. */  /* Read and compile the regular expressions that are provided in files. */
3107    
3108  if (pattern_filename != NULL)  for (fn = pattern_files; fn != NULL; fn = fn->next)
3109    {    {
3110    int linenumber = 0;    if (!read_pattern_file(fn->name, &patterns, &patterns_last, process_options))
3111    FILE *f;      goto EXIT2;
3112    char *filename;    }
   char buffer[MBUFTHIRD];  
3113    
3114    if (strcmp(pattern_filename, "-") == 0)  /* Study the regular expressions, as we will be running them many times. If an
3115      {  extra block is needed for a limit, set PCRE_STUDY_EXTRA_NEEDED so that one is
3116      f = stdin;  returned, even if studying produces no data. */
     filename = stdin_name;  
     }  
   else  
     {  
     f = fopen(pattern_filename, "r");  
     if (f == NULL)  
       {  
       fprintf(stderr, "pcregrep: Failed to open %s: %s\n", pattern_filename,  
         strerror(errno));  
       goto EXIT2;  
       }  
     filename = pattern_filename;  
     }  
3117    
3118    while (fgets(buffer, MBUFTHIRD, f) != NULL)  if (match_limit > 0 || match_limit_recursion > 0)
3119      {    study_options |= PCRE_STUDY_EXTRA_NEEDED;
     char *s = buffer + (int)strlen(buffer);  
     while (s > buffer && isspace((unsigned char)(s[-1]))) s--;  
     *s = 0;  
     linenumber++;  
     if (buffer[0] == 0) continue;   /* Skip blank lines */  
     if (!compile_pattern(buffer, pcre_options, filename, linenumber))  
       goto EXIT2;  
     }  
3120    
3121    if (f != stdin) fclose(f);  /* Unless JIT has been explicitly disabled, arrange a stack for it to use. */
   }  
3122    
3123  /* Study the regular expressions, as we will be running them many times */  #ifdef SUPPORT_PCREGREP_JIT
3124    if ((study_options & PCRE_STUDY_JIT_COMPILE) != 0)
3125      jit_stack = pcre_jit_stack_alloc(32*1024, 1024*1024);
3126    #endif
3127    
3128  for (j = 0; j < pattern_count; j++)  for (j = 1, cp = patterns; cp != NULL; j++, cp = cp->next)
3129    {    {
3130    hints_list[j] = pcre_study(pattern_list[j], 0, &error);    cp->hint = pcre_study(cp->compiled, study_options, &error);
3131    if (error != NULL)    if (error != NULL)
3132      {      {
3133      char s[16];      char s[16];
3134      if (pattern_count == 1) s[0] = 0; else sprintf(s, " number %d", j);      if (patterns->next == NULL) s[0] = 0; else sprintf(s, " number %d", j);
3135      fprintf(stderr, "pcregrep: Error while studying regex%s: %s\n", s, error);      fprintf(stderr, "pcregrep: Error while studying regex%s: %s\n", s, error);
3136      goto EXIT2;      goto EXIT2;
3137      }      }
3138    hint_count++;  #ifdef SUPPORT_PCREGREP_JIT
3139      if (jit_stack != NULL && cp->hint != NULL)
3140        pcre_assign_jit_stack(cp->hint, NULL, jit_stack);
3141    #endif
3142    }    }
3143    
3144  /* If --match-limit or --recursion-limit was set, put the value(s) into the  /* If --match-limit or --recursion-limit was set, put the value(s) into the
3145  pcre_extra block for each pattern. */  pcre_extra block for each pattern. There will always be an extra block because
3146    of the use of PCRE_STUDY_EXTRA_NEEDED above. */
3147    
3148  if (match_limit > 0 || match_limit_recursion > 0)  for (cp = patterns; cp != NULL; cp = cp->next)
3149    {    {
3150    for (j = 0; j < pattern_count; j++)    if (match_limit > 0)
3151      {      {
3152      if (hints_list[j] == NULL)      cp->hint->flags |= PCRE_EXTRA_MATCH_LIMIT;
3153        {      cp->hint->match_limit = match_limit;
       hints_list[j] = malloc(sizeof(pcre_extra));  
       if (hints_list[j] == NULL)  
         {  
         fprintf(stderr, "pcregrep: malloc failed\n");  
         pcregrep_exit(2);  
         }  
       }  
     if (match_limit > 0)  
       {  
       hints_list[j]->flags |= PCRE_EXTRA_MATCH_LIMIT;  
       hints_list[j]->match_limit = match_limit;  
       }  
     if (match_limit_recursion > 0)  
       {  
       hints_list[j]->flags |= PCRE_EXTRA_MATCH_LIMIT_RECURSION;  
       hints_list[j]->match_limit_recursion = match_limit_recursion;  
       }  
3154      }      }
   }  
   
 /* If there are include or exclude patterns, compile them. */  
3155    
3156  if (exclude_pattern != NULL)    if (match_limit_recursion > 0)
   {  
   exclude_compiled = pcre_compile(exclude_pattern, 0, &error, &errptr,  
     pcretables);  
   if (exclude_compiled == NULL)  
3157      {      {
3158      fprintf(stderr, "pcregrep: Error in 'exclude' regex at offset %d: %s\n",      cp->hint->flags |= PCRE_EXTRA_MATCH_LIMIT_RECURSION;
3159        errptr, error);      cp->hint->match_limit_recursion = match_limit_recursion;
     goto EXIT2;  
3160      }      }
3161    }    }
3162    
3163  if (include_pattern != NULL)  /* If there are include or exclude patterns read from the command line, compile
3164    them. -F, -w, and -x do not apply, so the third argument of compile_pattern is
3165    0. */
3166    
3167    for (j = 0; j < 4; j++)
3168    {    {
3169    include_compiled = pcre_compile(include_pattern, 0, &error, &errptr,    int k;
3170      pcretables);    for (k = 1, cp = *(incexlist[j]); cp != NULL; k++, cp = cp->next)
   if (include_compiled == NULL)  
3171      {      {
3172      fprintf(stderr, "pcregrep: Error in 'include' regex at offset %d: %s\n",      if (!compile_pattern(cp, pcre_options, 0, FALSE, incexname[j],
3173        errptr, error);           (k == 1 && cp->next == NULL)? 0 : k))
3174      goto EXIT2;        goto EXIT2;
3175      }      }
3176    }    }
3177    
3178  if (exclude_dir_pattern != NULL)  /* Read and compile include/exclude patterns from files. */
3179    
3180    for (fn = include_from; fn != NULL; fn = fn->next)
3181    {    {
3182    exclude_dir_compiled = pcre_compile(exclude_dir_pattern, 0, &error, &errptr,    if (!read_pattern_file(fn->name, &include_patterns, &include_patterns_last, 0))
     pcretables);  
   if (exclude_dir_compiled == NULL)  
     {  
     fprintf(stderr, "pcregrep: Error in 'exclude_dir' regex at offset %d: %s\n",  
       errptr, error);  
3183      goto EXIT2;      goto EXIT2;
     }  
3184    }    }
3185    
3186  if (include_dir_pattern != NULL)  for (fn = exclude_from; fn != NULL; fn = fn->next)
3187    {    {
3188    include_dir_compiled = pcre_compile(include_dir_pattern, 0, &error, &errptr,    if (!read_pattern_file(fn->name, &exclude_patterns, &exclude_patterns_last, 0))
     pcretables);  
   if (include_dir_compiled == NULL)  
     {  
     fprintf(stderr, "pcregrep: Error in 'include_dir' regex at offset %d: %s\n",  
       errptr, error);  
3189      goto EXIT2;      goto EXIT2;
     }  
3190    }    }
3191    
3192  /* If there are no further arguments, do the business on stdin and exit. */  /* If there are no files that contain lists of files to search, and there are
3193    no file arguments, search stdin, and then exit. */
3194    
3195  if (i >= argc)  if (file_lists == NULL && i >= argc)
3196    {    {
3197    rc = pcregrep(stdin, FR_PLAIN, (filenames > FN_DEFAULT)? stdin_name : NULL);    rc = pcregrep(stdin, FR_PLAIN, stdin_name,
3198        (filenames > FN_DEFAULT)? stdin_name : NULL);
3199    goto EXIT;    goto EXIT;
3200    }    }
3201    
3202  /* Otherwise, work through the remaining arguments as files or directories.  /* If any files that contains a list of files to search have been specified,
3203  Pass in the fact that there is only one argument at top level - this suppresses  read them line by line and search the given files. */
 the file name if the argument is not a directory and filenames are not  
 otherwise forced. */  
3204    
3205  only_one_at_top = i == argc - 1;   /* Catch initial value of i */  for (fn = file_lists; fn != NULL; fn = fn->next)
3206      {
3207      char buffer[PATBUFSIZE];
3208      FILE *fl;
3209      if (strcmp(fn->name, "-") == 0) fl = stdin; else
3210        {
3211        fl = fopen(fn->name, "rb");
3212        if (fl == NULL)
3213          {
3214          fprintf(stderr, "pcregrep: Failed to open %s: %s\n", fn->name,
3215            strerror(errno));
3216          goto EXIT2;
3217          }
3218        }
3219      while (fgets(buffer, PATBUFSIZE, fl) != NULL)
3220        {
3221        int frc;
3222        char *end = buffer + (int)strlen(buffer);
3223        while (end > buffer && isspace(end[-1])) end--;
3224        *end = 0;
3225        if (*buffer != 0)
3226          {
3227          frc = grep_or_recurse(buffer, dee_action == dee_RECURSE, FALSE);
3228          if (frc > 1) rc = frc;
3229            else if (frc == 0 && rc == 1) rc = 0;
3230          }
3231        }
3232      if (fl != stdin) fclose(fl);
3233      }
3234    
3235    /* After handling file-list, work through remaining arguments. Pass in the fact
3236    that there is only one argument at top level - this suppresses the file name if
3237    the argument is not a directory and filenames are not otherwise forced. */
3238    
3239    only_one_at_top = i == argc - 1 && file_lists == NULL;
3240    
3241  for (; i < argc; i++)  for (; i < argc; i++)
3242    {    {
# Line 2647  for (; i < argc; i++) Line 3247  for (; i < argc; i++)
3247    }    }
3248    
3249  EXIT:  EXIT:
3250  if (pattern_list != NULL)  #ifdef SUPPORT_PCREGREP_JIT
3251    {  if (jit_stack != NULL) pcre_jit_stack_free(jit_stack);
3252    for (i = 0; i < pattern_count; i++) free(pattern_list[i]);  #endif
3253    free(pattern_list);  
3254    }  if (main_buffer != NULL) free(main_buffer);
3255  if (hints_list != NULL)  
3256    free_pattern_chain(patterns);
3257    free_pattern_chain(include_patterns);
3258    free_pattern_chain(include_dir_patterns);
3259    free_pattern_chain(exclude_patterns);
3260    free_pattern_chain(exclude_dir_patterns);
3261    
3262    free_file_chain(exclude_from);
3263    free_file_chain(include_from);
3264    free_file_chain(pattern_files);
3265    free_file_chain(file_lists);
3266    
3267    while (only_matching != NULL)
3268    {    {
3269    for (i = 0; i < hint_count; i++)    omstr *this = only_matching;
3270      {    only_matching = this->next;
3271      if (hints_list[i] != NULL) free(hints_list[i]);    free(this);
     }  
   free(hints_list);  
3272    }    }
3273    
3274  pcregrep_exit(rc);  pcregrep_exit(rc);
3275    
3276  EXIT2:  EXIT2:

Legend:
Removed from v.586  
changed lines
  Added in v.1355

  ViewVC Help
Powered by ViewVC 1.1.5