pcregrep.c 95.9 KB
Newer Older
eg's avatar
eg committed
1 2 3 4 5
/*************************************************
*               pcregrep program                 *
*************************************************/

/* This is a grep program that uses the PCRE regular expression library to do
6 7
its pattern matching. On Unix-like, Windows, and native z/OS systems it can
recurse into directories, and in z/OS it can handle PDS files.
eg's avatar
eg committed
8

9 10 11 12 13 14 15
Note that for native z/OS, in addition to defining the NATIVE_ZOS macro, an
additional header is required. That header is not included in the main PCRE
distribution because other apparatus is needed to compile pcregrep for z/OS.
The header can be found in the special z/OS distribution, which is available
from www.zaconsultants.net or from www.cbttape.org.

           Copyright (c) 1997-2014 University of Cambridge
eg's avatar
eg committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    * Neither the name of the University of Cambridge nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/

46 47 48 49
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

eg's avatar
eg committed
50
#include <ctype.h>
51
#include <locale.h>
eg's avatar
eg committed
52 53 54 55
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
56 57 58 59 60 61 62 63

#include <sys/types.h>
#include <sys/stat.h>

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

64 65 66 67 68 69 70 71
#ifdef SUPPORT_LIBZ
#include <zlib.h>
#endif

#ifdef SUPPORT_LIBBZ2
#include <bzlib.h>
#endif

eg's avatar
eg committed
72 73 74 75 76 77 78
#include "pcre.h"

#define FALSE 0
#define TRUE 1

typedef int BOOL;

79
#define OFFSET_SIZE 99
eg's avatar
eg committed
80

81
#if BUFSIZ > 8192
82
#define MAXPATLEN BUFSIZ
83
#else
84
#define MAXPATLEN 8192
85 86
#endif

87 88
#define PATBUFSIZE (MAXPATLEN + 10)   /* Allows for prefix+suffix */

89 90 91 92
/* Values for the "filenames" variable, which specifies options for file name
output. The order is important; it is assumed that a file name is wanted for
all values greater than FN_DEFAULT. */

93
enum { FN_NONE, FN_DEFAULT, FN_MATCH_ONLY, FN_NOMATCH_ONLY, FN_FORCE };
94

95 96 97 98
/* File reading styles */

enum { FR_PLAIN, FR_LIBZ, FR_LIBBZ2 };

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
/* Actions for the -d and -D options */

enum { dee_READ, dee_SKIP, dee_RECURSE };
enum { DEE_READ, DEE_SKIP };

/* Actions for special processing options (flag bits) */

#define PO_WORD_MATCH     0x0001
#define PO_LINE_MATCH     0x0002
#define PO_FIXED_STRINGS  0x0004

/* Line ending types */

enum { EL_LF, EL_CR, EL_CRLF, EL_ANY, EL_ANYCRLF };

114 115 116 117 118 119 120 121 122 123 124 125
/* Binary file options */

enum { BIN_BINARY, BIN_NOMATCH, BIN_TEXT };

/* In newer versions of gcc, with FORTIFY_SOURCE set (the default in some
environments), a warning is issued if the value of fwrite() is ignored.
Unfortunately, casting to (void) does not suppress the warning. To get round
this, we use a macro that compiles a fudge. Oddly, this does not also seem to
apply to fprintf(). */

#define FWRITE(a,b,c,d) if (fwrite(a,b,c,d)) {}

126

eg's avatar
eg committed
127 128 129 130 131

/*************************************************
*               Global variables                 *
*************************************************/

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
/* Jeffrey Friedl has some debugging requirements that are not part of the
regular code. */

#ifdef JFRIEDL_DEBUG
static int S_arg = -1;
static unsigned int jfriedl_XR = 0; /* repeat regex attempt this many times */
static unsigned int jfriedl_XT = 0; /* replicate text this many times */
static const char *jfriedl_prefix = "";
static const char *jfriedl_postfix = "";
#endif

static int  endlinetype;

static char *colour_string = (char *)"1;31";
static char *colour_option = NULL;
static char *dee_option = NULL;
static char *DEE_option = NULL;
149 150
static char *locale = NULL;
static char *main_buffer = NULL;
151
static char *newline = NULL;
152
static char *om_separator = (char *)"";
153 154 155 156 157 158
static char *stdin_name = (char *)"(standard input)";

static const unsigned char *pcretables = NULL;

static int after_context = 0;
static int before_context = 0;
159
static int binary_files = BIN_BINARY;
160
static int both_context = 0;
161 162 163 164 165 166
static int bufthird = PCREGREP_BUFSIZE;
static int bufsize = 3*PCREGREP_BUFSIZE;

#if defined HAVE_WINDOWS_H && HAVE_WINDOWS_H
static int dee_action = dee_SKIP;
#else
167
static int dee_action = dee_READ;
168 169
#endif

170 171 172
static int DEE_action = DEE_READ;
static int error_count = 0;
static int filenames = FN_DEFAULT;
173
static int pcre_options = 0;
174
static int process_options = 0;
eg's avatar
eg committed
175

176 177 178 179 180 181 182 183 184
#ifdef SUPPORT_PCREGREP_JIT
static int study_options = PCRE_STUDY_JIT_COMPILE;
#else
static int study_options = 0;
#endif

static unsigned long int match_limit = 0;
static unsigned long int match_limit_recursion = 0;

eg's avatar
eg committed
185
static BOOL count_only = FALSE;
186
static BOOL do_colour = FALSE;
187
static BOOL file_offsets = FALSE;
188
static BOOL hyphenpending = FALSE;
eg's avatar
eg committed
189
static BOOL invert = FALSE;
190
static BOOL line_buffered = FALSE;
191
static BOOL line_offsets = FALSE;
192
static BOOL multiline = FALSE;
eg's avatar
eg committed
193
static BOOL number = FALSE;
194 195
static BOOL omit_zero_count = FALSE;
static BOOL resource_error = FALSE;
196
static BOOL quiet = FALSE;
197
static BOOL show_only_matching = FALSE;
eg's avatar
eg committed
198
static BOOL silent = FALSE;
199
static BOOL utf8 = FALSE;
eg's avatar
eg committed
200

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
/* Structure for list of --only-matching capturing numbers. */

typedef struct omstr {
  struct omstr *next;
  int groupnum;
} omstr;

static omstr *only_matching = NULL;
static omstr *only_matching_last = NULL;

/* Structure for holding the two variables that describe a number chain. */

typedef struct omdatastr {
  omstr **anchor;
  omstr **lastptr;
} omdatastr;

static omdatastr only_matching_data = { &only_matching, &only_matching_last };

/* Structure for list of file names (for -f and --{in,ex}clude-from) */

typedef struct fnstr {
  struct fnstr *next;
  char *name;
} fnstr;

static fnstr *exclude_from = NULL;
static fnstr *exclude_from_last = NULL;
static fnstr *include_from = NULL;
static fnstr *include_from_last = NULL;

static fnstr *file_lists = NULL;
static fnstr *file_lists_last = NULL;
static fnstr *pattern_files = NULL;
static fnstr *pattern_files_last = NULL;

/* Structure for holding the two variables that describe a file name chain. */

typedef struct fndatastr {
  fnstr **anchor;
  fnstr **lastptr;
} fndatastr;

static fndatastr exclude_from_data = { &exclude_from, &exclude_from_last };
static fndatastr include_from_data = { &include_from, &include_from_last };
static fndatastr file_lists_data = { &file_lists, &file_lists_last };
static fndatastr pattern_files_data = { &pattern_files, &pattern_files_last };

/* Structure for pattern and its compiled form; used for matching patterns and
also for include/exclude patterns. */

typedef struct patstr {
  struct patstr *next;
  char *string;
  pcre *compiled;
  pcre_extra *hint;
} patstr;

static patstr *patterns = NULL;
static patstr *patterns_last = NULL;
static patstr *include_patterns = NULL;
static patstr *include_patterns_last = NULL;
static patstr *exclude_patterns = NULL;
static patstr *exclude_patterns_last = NULL;
static patstr *include_dir_patterns = NULL;
static patstr *include_dir_patterns_last = NULL;
static patstr *exclude_dir_patterns = NULL;
static patstr *exclude_dir_patterns_last = NULL;

/* Structure holding the two variables that describe a pattern chain. A pointer
to such structures is used for each appropriate option. */

typedef struct patdatastr {
  patstr **anchor;
  patstr **lastptr;
} patdatastr;

static patdatastr match_patdata = { &patterns, &patterns_last };
static patdatastr include_patdata = { &include_patterns, &include_patterns_last };
static patdatastr exclude_patdata = { &exclude_patterns, &exclude_patterns_last };
static patdatastr include_dir_patdata = { &include_dir_patterns, &include_dir_patterns_last };
static patdatastr exclude_dir_patdata = { &exclude_dir_patterns, &exclude_dir_patterns_last };

static patstr **incexlist[4] = { &include_patterns, &exclude_patterns,
                                 &include_dir_patterns, &exclude_dir_patterns };

static const char *incexname[4] = { "--include", "--exclude",
                                    "--include-dir", "--exclude-dir" };

eg's avatar
eg committed
290 291
/* Structure for options and list of them */

292 293
enum { OP_NODATA, OP_STRING, OP_OP_STRING, OP_NUMBER, OP_LONGNUMBER,
       OP_OP_NUMBER, OP_OP_NUMBERS, OP_PATLIST, OP_FILELIST, OP_BINFILES };
294

eg's avatar
eg committed
295
typedef struct option_item {
296
  int type;
eg's avatar
eg committed
297
  int one_char;
298
  void *dataptr;
eg's avatar
eg committed
299 300 301 302
  const char *long_name;
  const char *help_text;
} option_item;

303 304 305
/* Options without a single-letter equivalent get a negative value. This can be
used to identify them. */

306 307 308 309 310 311 312 313 314 315 316
#define N_COLOUR       (-1)
#define N_EXCLUDE      (-2)
#define N_EXCLUDE_DIR  (-3)
#define N_HELP         (-4)
#define N_INCLUDE      (-5)
#define N_INCLUDE_DIR  (-6)
#define N_LABEL        (-7)
#define N_LOCALE       (-8)
#define N_NULL         (-9)
#define N_LOFFSETS     (-10)
#define N_FOFFSETS     (-11)
317 318 319 320 321 322 323 324 325 326
#define N_LBUFFER      (-12)
#define N_M_LIMIT      (-13)
#define N_M_LIMIT_REC  (-14)
#define N_BUFSIZE      (-15)
#define N_NOJIT        (-16)
#define N_FILE_LIST    (-17)
#define N_BINARY_FILES (-18)
#define N_EXCLUDE_FROM (-19)
#define N_INCLUDE_FROM (-20)
#define N_OM_SEPARATOR (-21)
327

eg's avatar
eg committed
328
static option_item optionlist[] = {
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
  { OP_NODATA,     N_NULL,   NULL,              "",              "terminate options" },
  { OP_NODATA,     N_HELP,   NULL,              "help",          "display this help and exit" },
  { OP_NUMBER,     'A',      &after_context,    "after-context=number", "set number of following context lines" },
  { OP_NODATA,     'a',      NULL,              "text",          "treat binary files as text" },
  { OP_NUMBER,     'B',      &before_context,   "before-context=number", "set number of prior context lines" },
  { OP_BINFILES,   N_BINARY_FILES, NULL,        "binary-files=word", "set treatment of binary files" },
  { OP_NUMBER,     N_BUFSIZE,&bufthird,         "buffer-size=number", "set processing buffer size parameter" },
  { OP_OP_STRING,  N_COLOUR, &colour_option,    "color=option",  "matched text color option" },
  { OP_OP_STRING,  N_COLOUR, &colour_option,    "colour=option", "matched text colour option" },
  { OP_NUMBER,     'C',      &both_context,     "context=number", "set number of context lines, before & after" },
  { OP_NODATA,     'c',      NULL,              "count",         "print only a count of matching lines per FILE" },
  { OP_STRING,     'D',      &DEE_option,       "devices=action","how to handle devices, FIFOs, and sockets" },
  { OP_STRING,     'd',      &dee_option,       "directories=action", "how to handle directories" },
  { OP_PATLIST,    'e',      &match_patdata,    "regex(p)=pattern", "specify pattern (may be used more than once)" },
  { OP_NODATA,     'F',      NULL,              "fixed-strings", "patterns are sets of newline-separated strings" },
  { OP_FILELIST,   'f',      &pattern_files_data, "file=path",   "read patterns from file" },
  { OP_FILELIST,   N_FILE_LIST, &file_lists_data, "file-list=path","read files to search from file" },
  { OP_NODATA,     N_FOFFSETS, NULL,            "file-offsets",  "output file offsets, not text" },
  { OP_NODATA,     'H',      NULL,              "with-filename", "force the prefixing filename on output" },
  { OP_NODATA,     'h',      NULL,              "no-filename",   "suppress the prefixing filename on output" },
  { OP_NODATA,     'I',      NULL,              "",              "treat binary files as not matching (ignore)" },
  { OP_NODATA,     'i',      NULL,              "ignore-case",   "ignore case distinctions" },
#ifdef SUPPORT_PCREGREP_JIT
  { OP_NODATA,     N_NOJIT,  NULL,              "no-jit",        "do not use just-in-time compiler optimization" },
#else
  { OP_NODATA,     N_NOJIT,  NULL,              "no-jit",        "ignored: this pcregrep does not support JIT" },
#endif
  { OP_NODATA,     'l',      NULL,              "files-with-matches", "print only FILE names containing matches" },
  { OP_NODATA,     'L',      NULL,              "files-without-match","print only FILE names not containing matches" },
  { OP_STRING,     N_LABEL,  &stdin_name,       "label=name",    "set name for standard input" },
  { OP_NODATA,     N_LBUFFER, NULL,             "line-buffered", "use line buffering" },
  { OP_NODATA,     N_LOFFSETS, NULL,            "line-offsets",  "output line numbers and offsets, not text" },
  { OP_STRING,     N_LOCALE, &locale,           "locale=locale", "use the named locale" },
  { OP_LONGNUMBER, N_M_LIMIT, &match_limit,     "match-limit=number", "set PCRE match limit option" },
  { OP_LONGNUMBER, N_M_LIMIT_REC, &match_limit_recursion, "recursion-limit=number", "set PCRE match recursion limit option" },
  { OP_NODATA,     'M',      NULL,              "multiline",     "run in multiline mode" },
  { OP_STRING,     'N',      &newline,          "newline=type",  "set newline type (CR, LF, CRLF, ANYCRLF or ANY)" },
  { OP_NODATA,     'n',      NULL,              "line-number",   "print line number with output lines" },
  { OP_OP_NUMBERS, 'o',      &only_matching_data, "only-matching=n", "show only the part of the line that matched" },
  { OP_STRING,     N_OM_SEPARATOR, &om_separator, "om-separator=text", "set separator for multiple -o output" },
  { OP_NODATA,     'q',      NULL,              "quiet",         "suppress output, just set return code" },
  { OP_NODATA,     'r',      NULL,              "recursive",     "recursively scan sub-directories" },
  { OP_PATLIST,    N_EXCLUDE,&exclude_patdata,  "exclude=pattern","exclude matching files when recursing" },
  { OP_PATLIST,    N_INCLUDE,&include_patdata,  "include=pattern","include matching files when recursing" },
  { OP_PATLIST,    N_EXCLUDE_DIR,&exclude_dir_patdata, "exclude-dir=pattern","exclude matching directories when recursing" },
  { OP_PATLIST,    N_INCLUDE_DIR,&include_dir_patdata, "include-dir=pattern","include matching directories when recursing" },
  { OP_FILELIST,   N_EXCLUDE_FROM,&exclude_from_data, "exclude-from=path", "read exclude list from file" },
  { OP_FILELIST,   N_INCLUDE_FROM,&include_from_data, "include-from=path", "read include list from file" },

  /* These two were accidentally implemented with underscores instead of
  hyphens in the option names. As this was not discovered for several releases,
  the incorrect versions are left in the table for compatibility. However, the
  --help function misses out any option that has an underscore in its name. */

  { OP_PATLIST,   N_EXCLUDE_DIR,&exclude_dir_patdata, "exclude_dir=pattern","exclude matching directories when recursing" },
  { OP_PATLIST,   N_INCLUDE_DIR,&include_dir_patdata, "include_dir=pattern","include matching directories when recursing" },

386 387 388 389 390 391 392 393 394 395
#ifdef JFRIEDL_DEBUG
  { OP_OP_NUMBER, 'S',      &S_arg,            "jeffS",         "replace matched (sub)string with X" },
#endif
  { OP_NODATA,    's',      NULL,              "no-messages",   "suppress error messages" },
  { OP_NODATA,    'u',      NULL,              "utf-8",         "use UTF-8 mode" },
  { OP_NODATA,    'V',      NULL,              "version",       "print version information and exit" },
  { OP_NODATA,    'v',      NULL,              "invert-match",  "select non-matching lines" },
  { OP_NODATA,    'w',      NULL,              "word-regex(p)", "force patterns to match only as words"  },
  { OP_NODATA,    'x',      NULL,              "line-regex(p)", "force patterns to match only whole lines" },
  { OP_NODATA,    0,        NULL,               NULL,            NULL }
eg's avatar
eg committed
396 397
};

398 399 400
/* Tables for prefixing and suffixing patterns, according to the -w, -x, and -F
options. These set the 1, 2, and 4 bits in process_options, respectively. Note
that the combination of -w and -x has the same effect as -x on its own, so we
401 402 403
can treat them as the same. Note that the MAXPATLEN macro assumes the longest
prefix+suffix is 10 characters; if anything longer is added, it must be
adjusted. */
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

static const char *prefix[] = {
  "", "\\b", "^(?:", "^(?:", "\\Q", "\\b\\Q", "^(?:\\Q", "^(?:\\Q" };

static const char *suffix[] = {
  "", "\\b", ")$",   ")$",   "\\E", "\\E\\b", "\\E)$",   "\\E)$" };

/* UTF-8 tables - used only when the newline setting is "any". */

const int utf8_table3[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01};

const char utf8_table4[] = {
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
  3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 };


eg's avatar
eg committed
422

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
/*************************************************
*         Exit from the program                  *
*************************************************/

/* If there has been a resource error, give a suitable message.

Argument:  the return code
Returns:   does not return
*/

static void
pcregrep_exit(int rc)
{
if (resource_error)
  {
  fprintf(stderr, "pcregrep: Error %d, %d or %d means that a resource limit "
    "was exceeded.\n", PCRE_ERROR_MATCHLIMIT, PCRE_ERROR_RECURSIONLIMIT,
    PCRE_ERROR_JIT_STACKLIMIT);
  fprintf(stderr, "pcregrep: Check your regex for nested unlimited loops.\n");
  }
exit(rc);
}


/*************************************************
*          Add item to chain of patterns         *
*************************************************/

/* Used to add an item onto a chain, or just return an unconnected item if the
"after" argument is NULL.

Arguments:
  s          pattern string to add
  after      if not NULL points to item to insert after

Returns:     new pattern block or NULL on error
*/

static patstr *
add_pattern(char *s, patstr *after)
{
patstr *p = (patstr *)malloc(sizeof(patstr));
if (p == NULL)
  {
  fprintf(stderr, "pcregrep: malloc failed\n");
  pcregrep_exit(2);
  }
if (strlen(s) > MAXPATLEN)
  {
  fprintf(stderr, "pcregrep: pattern is too long (limit is %d bytes)\n",
    MAXPATLEN);
  free(p);
  return NULL;
  }
p->next = NULL;
p->string = s;
p->compiled = NULL;
p->hint = NULL;

if (after != NULL)
  {
  p->next = after->next;
  after->next = p;
  }
return p;
}


/*************************************************
*           Free chain of patterns               *
*************************************************/

/* Used for several chains of patterns.

Argument: pointer to start of chain
Returns:  nothing
*/

static void
free_pattern_chain(patstr *pc)
{
while (pc != NULL)
  {
  patstr *p = pc;
  pc = p->next;
  if (p->hint != NULL) pcre_free_study(p->hint);
  if (p->compiled != NULL) pcre_free(p->compiled);
  free(p);
  }
}


/*************************************************
*           Free chain of file names             *
*************************************************/

/*
Argument: pointer to start of chain
Returns:  nothing
*/

static void
free_file_chain(fnstr *fn)
{
while (fn != NULL)
  {
  fnstr *f = fn;
  fn = f->next;
  free(f);
  }
}


eg's avatar
eg committed
536
/*************************************************
537
*            OS-specific functions               *
eg's avatar
eg committed
538 539
*************************************************/

540 541 542
/* These functions are defined so that they can be made system specific.
At present there are versions for Unix-style environments, Windows, native
z/OS, and "no support". */
eg's avatar
eg committed
543 544


545
/************* Directory scanning Unix-style and z/OS ***********/
eg's avatar
eg committed
546

547
#if (defined HAVE_SYS_STAT_H && defined HAVE_DIRENT_H && defined HAVE_SYS_TYPES_H) || defined NATIVE_ZOS
eg's avatar
eg committed
548 549 550 551
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>

552 553 554 555 556 557 558 559 560 561 562
#if defined NATIVE_ZOS
/************* Directory and PDS/E scanning for z/OS ***********/
/************* z/OS looks mostly like Unix with USS ************/
/* However, z/OS needs the #include statements in this header */
#include "pcrzosfs.h"
/* That header is not included in the main PCRE distribution because
   other apparatus is needed to compile pcregrep for z/OS. The header
   can be found in the special z/OS distribution, which is available
   from www.zaconsultants.net or from www.cbttape.org. */
#endif

eg's avatar
eg committed
563
typedef DIR directory_type;
564
#define FILESEP '/'
eg's avatar
eg committed
565 566 567 568 569 570 571

static int
isdirectory(char *filename)
{
struct stat statbuf;
if (stat(filename, &statbuf) < 0)
  return 0;        /* In the expectation that opening as a file will fail */
572
return (statbuf.st_mode & S_IFMT) == S_IFDIR;
eg's avatar
eg committed
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
}

static directory_type *
opendirectory(char *filename)
{
return opendir(filename);
}

static char *
readdirectory(directory_type *dir)
{
for (;;)
  {
  struct dirent *dent = readdir(dir);
  if (dent == NULL) return NULL;
  if (strcmp(dent->d_name, ".") != 0 && strcmp(dent->d_name, "..") != 0)
    return dent->d_name;
  }
591
/* Control never reaches here */
eg's avatar
eg committed
592 593 594 595 596 597 598 599 600
}

static void
closedirectory(directory_type *dir)
{
closedir(dir);
}


601
/************* Test for regular file, Unix-style **********/
602 603 604 605 606 607 608 609 610 611 612

static int
isregfile(char *filename)
{
struct stat statbuf;
if (stat(filename, &statbuf) < 0)
  return 1;        /* In the expectation that opening as a file will fail */
return (statbuf.st_mode & S_IFMT) == S_IFREG;
}


613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
#if defined NATIVE_ZOS
/************* Test for a terminal in z/OS **********/
/* isatty() does not work in a TSO environment, so always give FALSE.*/

static BOOL
is_stdout_tty(void)
{
return FALSE;
}

static BOOL
is_file_tty(FILE *f)
{
return FALSE;
}


/************* Test for a terminal, Unix-style **********/
631

632
#else
633 634 635 636 637 638
static BOOL
is_stdout_tty(void)
{
return isatty(fileno(stdout));
}

639 640 641 642 643 644
static BOOL
is_file_tty(FILE *f)
{
return isatty(fileno(f));
}
#endif
645

646 647 648 649
/* End of Unix-style or native z/OS environment functions. */


/************* Directory scanning in Windows ***********/
eg's avatar
eg committed
650 651

/* I (Philip Hazel) have no means of testing this code. It was contributed by
652
Lionel Fourquaux. David Burgess added a patch to define INVALID_FILE_ATTRIBUTES
653 654
when it did not exist. David Byron added a patch that moved the #include of
<windows.h> to before the INVALID_FILE_ATTRIBUTES definition rather than after.
655 656
The double test below stops gcc 4.4.4 grumbling that HAVE_WINDOWS_H is
undefined when it is indeed undefined. */
eg's avatar
eg committed
657

658
#elif defined HAVE_WINDOWS_H && HAVE_WINDOWS_H
eg's avatar
eg committed
659 660 661 662 663 664 665

#ifndef STRICT
# define STRICT
#endif
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
666 667 668

#include <windows.h>

669 670 671 672
#ifndef INVALID_FILE_ATTRIBUTES
#define INVALID_FILE_ATTRIBUTES 0xFFFFFFFF
#endif

eg's avatar
eg committed
673 674 675 676 677 678 679
typedef struct directory_type
{
HANDLE handle;
BOOL first;
WIN32_FIND_DATA data;
} directory_type;

680 681
#define FILESEP '/'

eg's avatar
eg committed
682 683 684 685 686 687
int
isdirectory(char *filename)
{
DWORD attr = GetFileAttributes(filename);
if (attr == INVALID_FILE_ATTRIBUTES)
  return 0;
688
return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
eg's avatar
eg committed
689 690 691 692 693 694 695 696 697 698
}

directory_type *
opendirectory(char *filename)
{
size_t len;
char *pattern;
directory_type *dir;
DWORD err;
len = strlen(filename);
699 700
pattern = (char *)malloc(len + 3);
dir = (directory_type *)malloc(sizeof(*dir));
eg's avatar
eg committed
701 702 703
if ((pattern == NULL) || (dir == NULL))
  {
  fprintf(stderr, "pcregrep: malloc failed\n");
704
  pcregrep_exit(2);
eg's avatar
eg committed
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
  }
memcpy(pattern, filename, len);
memcpy(&(pattern[len]), "\\*", 3);
dir->handle = FindFirstFile(pattern, &(dir->data));
if (dir->handle != INVALID_HANDLE_VALUE)
  {
  free(pattern);
  dir->first = TRUE;
  return dir;
  }
err = GetLastError();
free(pattern);
free(dir);
errno = (err == ERROR_ACCESS_DENIED) ? EACCES : ENOENT;
return NULL;
}

char *
readdirectory(directory_type *dir)
{
for (;;)
  {
  if (!dir->first)
    {
    if (!FindNextFile(dir->handle, &(dir->data)))
      return NULL;
    }
  else
    {
    dir->first = FALSE;
    }
  if (strcmp(dir->data.cFileName, ".") != 0 && strcmp(dir->data.cFileName, "..") != 0)
    return dir->data.cFileName;
  }
#ifndef _MSC_VER
return NULL;   /* Keep compiler happy; never executed */
#endif
}

void
closedirectory(directory_type *dir)
{
FindClose(dir->handle);
free(dir);
}


752
/************* Test for regular file in Windows **********/
753 754 755 756 757 758

/* I don't know how to do this, or if it can be done; assume all paths are
regular if they are not directories. */

int isregfile(char *filename)
{
759
return !isdirectory(filename);
760 761 762
}


763
/************* Test for a terminal in Windows **********/
764 765 766 767 768 769

/* I don't know how to do this; assume never */

static BOOL
is_stdout_tty(void)
{
770
return FALSE;
771 772
}

773 774 775 776 777 778 779 780
static BOOL
is_file_tty(FILE *f)
{
return FALSE;
}

/* End of Windows functions */

781

eg's avatar
eg committed
782 783 784 785 786 787
/************* Directory scanning when we can't do it ***********/

/* The type is void, and apart from isdirectory(), the functions do nothing. */

#else

788
#define FILESEP 0
eg's avatar
eg committed
789 790
typedef void directory_type;

791 792 793
int isdirectory(char *filename) { return 0; }
directory_type * opendirectory(char *filename) { return (directory_type*)0;}
char *readdirectory(directory_type *dir) { return (char*)0;}
eg's avatar
eg committed
794 795
void closedirectory(directory_type *dir) {}

796

797
/************* Test for regular file when we can't do it **********/
798 799 800 801 802 803

/* Assume all files are regular. */

int isregfile(char *filename) { return 1; }


804
/************* Test for a terminal when we can't do it **********/
805 806 807 808 809 810 811

static BOOL
is_stdout_tty(void)
{
return FALSE;
}

812 813 814 815 816
static BOOL
is_file_tty(FILE *f)
{
return FALSE;
}
817

818
#endif  /* End of system-specific functions */
eg's avatar
eg committed
819 820 821



822
#ifndef HAVE_STRERROR
eg's avatar
eg committed
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
/*************************************************
*     Provide strerror() for non-ANSI libraries  *
*************************************************/

/* Some old-fashioned systems still around (e.g. SunOS4) don't have strerror()
in their libraries, but can provide the same facility by this simple
alternative function. */

extern int   sys_nerr;
extern char *sys_errlist[];

char *
strerror(int n)
{
if (n < 0 || n >= sys_nerr) return "unknown error number";
return sys_errlist[n];
}
#endif /* HAVE_STRERROR */



844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
/*************************************************
*                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 && (op->long_name)[0] == 0)
    n = 31 - printf("  -%c", op->one_char);
  else
    {
    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("\nNumbers may be followed by K or M, e.g. --buffer-size=100K.\n");
printf("The default value for --buffer-size is %d.\n", PCREGREP_BUFSIZE);
printf("When reading patterns or file names from a file, trailing white\n");
printf("space is removed and blank lines are ignored.\n");
printf("The maximum size of any pattern is %d bytes.\n", MAXPATLEN);

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");
}



/*************************************************
*            Test exclude/includes               *
*************************************************/

/* If any exclude pattern matches, the path is excluded. Otherwise, unless
there are no includes, the path must match an include pattern.

Arguments:
  path      the path to be matched
  ip        the chain of include patterns
  ep        the chain of exclude patterns

Returns:    TRUE if the path is not excluded
*/

static BOOL
test_incexc(char *path, patstr *ip, patstr *ep)
{
int plen = strlen(path);

for (; ep != NULL; ep = ep->next)
  {
  if (pcre_exec(ep->compiled, NULL, path, plen, 0, 0, NULL, 0) >= 0)
    return FALSE;
  }

if (ip == NULL) return TRUE;

for (; ip != NULL; ip = ip->next)
  {
  if (pcre_exec(ip->compiled, NULL, path, plen, 0, 0, NULL, 0) >= 0)
    return TRUE;
  }

return FALSE;
}



/*************************************************
*         Decode integer argument value          *
*************************************************/

/* Integer arguments can be followed by K or M. Avoid the use of strtoul()
because SunOS4 doesn't have it. This is used only for unpicking arguments, so
just keep it simple.

Arguments:
  option_data   the option data string
  op            the option item (for error messages)
  longop        TRUE if option given in long form

Returns:        a long integer
*/

static long int
decode_number(char *option_data, option_item *op, BOOL longop)
{
unsigned long int n = 0;
char *endptr = option_data;
while (*endptr != 0 && isspace((unsigned char)(*endptr))) endptr++;
while (isdigit((unsigned char)(*endptr)))
  n = n * 10 + (int)(*endptr++ - '0');
if (toupper(*endptr) == 'K')
  {
  n *= 1024;
  endptr++;
  }
else if (toupper(*endptr) == 'M')
  {
  n *= 1024*1024;
  endptr++;
  }

if (*endptr != 0)   /* Error */
  {
  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));
  }

return n;
}



/*************************************************
*       Add item to a chain of numbers           *
*************************************************/

/* Used to add an item onto a chain, or just return an unconnected item if the
"after" argument is NULL.

Arguments:
  n          the number to add
  after      if not NULL points to item to insert after

Returns:     new number block
*/

static omstr *
add_number(int n, omstr *after)
{
omstr *om = (omstr *)malloc(sizeof(omstr));

if (om == NULL)
  {
  fprintf(stderr, "pcregrep: malloc failed\n");
  pcregrep_exit(2);
  }
om->next = NULL;
om->groupnum = n;

if (after != NULL)
  {
  om->next = after->next;
  after->next = om;
  }
return om;
}



/*************************************************
*            Read one line of input              *
*************************************************/

/* Normally, input is read using fread() into a large buffer, so many lines may
be read at once. However, doing this for tty input means that no output appears
until a lot of input has been typed. Instead, tty input is handled line by
line. We cannot use fgets() for this, because it does not stop at a binary
zero, and therefore there is no way of telling how many characters it has read,
because there may be binary zeros embedded in the data.

Arguments:
  buffer     the buffer to read into
  length     the maximum number of characters to read
  f          the file

Returns:     the number of characters read, zero at end of file
*/

static unsigned int
read_one_line(char *buffer, int length, FILE *f)
{
int c;
int yield = 0;
while ((c = fgetc(f)) != EOF)
  {
  buffer[yield++] = c;
  if (c == '\n' || yield >= length) break;
  }
return yield;
}



eg's avatar
eg committed
1102
/*************************************************
1103
*             Find end of line                   *
eg's avatar
eg committed
1104 1105
*************************************************/

1106 1107
/* The length of the endline sequence that is found is set via lenptr. This may
be zero at the very end of the file if there is no line-ending sequence there.
eg's avatar
eg committed
1108

1109 1110 1111 1112
Arguments:
  p         current position in line
  endptr    end of available data
  lenptr    where to put the length of the eol sequence
eg's avatar
eg committed
1113

1114 1115
Returns:    pointer after the last byte of the line,
            including the newline byte(s)
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
*/

static char *
end_of_line(char *p, char *endptr, int *lenptr)
{
switch(endlinetype)
  {
  default:      /* Just in case */
  case EL_LF:
  while (p < endptr && *p != '\n') p++;
  if (p < endptr)
eg's avatar
eg committed
1127
    {
1128 1129
    *lenptr = 1;
    return p + 1;
eg's avatar
eg committed
1130
    }
1131 1132
  *lenptr = 0;
  return endptr;
eg's avatar
eg committed
1133

1134 1135 1136
  case EL_CR:
  while (p < endptr && *p != '\r') p++;
  if (p < endptr)
eg's avatar
eg committed
1137
    {
1138 1139 1140 1141 1142
    *lenptr = 1;
    return p + 1;
    }
  *lenptr = 0;
  return endptr;
eg's avatar
eg committed
1143

1144 1145 1146 1147 1148
  case EL_CRLF:
  for (;;)
    {
    while (p < endptr && *p != '\r') p++;
    if (++p >= endptr)
eg's avatar
eg committed
1149
      {
1150 1151
      *lenptr = 0;
      return endptr;
eg's avatar
eg committed
1152
      }
1153
    if (*p == '\n')
eg's avatar
eg committed
1154
      {
1155 1156
      *lenptr = 2;
      return p + 1;
eg's avatar
eg committed
1157 1158
      }
    }
1159
  break;
eg's avatar
eg committed
1160

1161 1162 1163 1164 1165
  case EL_ANYCRLF:
  while (p < endptr)
    {
    int extra = 0;
    register int c = *((unsigned char *)p);
eg's avatar
eg committed
1166

1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    if (utf8 && c >= 0xc0)
      {
      int gcii, gcss;
      extra = utf8_table4[c & 0x3f];  /* Number of additional bytes */
      gcss = 6*extra;
      c = (c & utf8_table3[extra]) << gcss;
      for (gcii = 1; gcii <= extra; gcii++)
        {
        gcss -= 6;
        c |= (p[gcii] & 0x3f) << gcss;
        }
      }
eg's avatar
eg committed
1179

1180
    p += 1 + extra;
eg's avatar
eg committed
1181

1182 1183
    switch (c)
      {
1184
      case '\n':
1185 1186
      *lenptr = 1;
      return p;
eg's avatar
eg committed
1187

1188 1189
      case '\r':
      if (p < endptr && *p == '\n')
1190 1191 1192 1193 1194 1195
        {
        *lenptr = 2;
        p++;
        }
      else *lenptr = 1;
      return p;
eg's avatar
eg committed
1196

1197 1198 1199 1200
      default:
      break;
      }
    }   /* End of loop for ANYCRLF case */
eg's avatar
eg committed
1201

1202 1203
  *lenptr = 0;  /* Must have hit the end */
  return endptr;
eg's avatar
eg committed
1204

1205 1206 1207 1208 1209
  case EL_ANY:
  while (p < endptr)
    {
    int extra = 0;
    register int c = *((unsigned char *)p);
eg's avatar
eg committed
1210

1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    if (utf8 && c >= 0xc0)
      {
      int gcii, gcss;
      extra = utf8_table4[c & 0x3f];  /* Number of additional bytes */
      gcss = 6*extra;
      c = (c & utf8_table3[extra]) << gcss;
      for (gcii = 1; gcii <= extra; gcii++)
        {
        gcss -= 6;
        c |= (p[gcii] & 0x3f) << gcss;
        }
      }
eg's avatar
eg committed
1223

1224
    p += 1 + extra;
eg's avatar
eg committed
1225

1226 1227
    switch (c)
      {
1228 1229 1230
      case '\n':    /* LF */
      case '\v':    /* VT */
      case '\f':    /* FF */
1231 1232 1233
      *lenptr = 1;
      return p;

1234 1235
      case '\r':    /* CR */
      if (p < endptr && *p == '\n')
1236 1237 1238 1239 1240 1241
        {
        *lenptr = 2;
        p++;
        }
      else *lenptr = 1;
      return p;
eg's avatar
eg committed
1242

1243 1244
#ifndef EBCDIC
      case 0x85:    /* Unicode NEL */
1245 1246
      *lenptr = utf8? 2 : 1;
      return p;
eg's avatar
eg committed
1247

1248 1249
      case 0x2028:  /* Unicode LS */
      case 0x2029:  /* Unicode PS */
1250 1251
      *lenptr = 3;
      return p;
1252
#endif  /* Not EBCDIC */
eg's avatar
eg committed
1253

1254 1255 1256 1257
      default:
      break;
      }
    }   /* End of loop for ANY case */
eg's avatar
eg committed
1258

1259 1260 1261
  *lenptr = 0;  /* Must have hit the end */
  return endptr;
  }     /* End of overall switch */
eg's avatar
eg committed
1262 1263 1264 1265 1266
}



/*************************************************
1267
*         Find start of previous line            *
eg's avatar
eg committed
1268 1269
*************************************************/

1270
/* This is called when looking back for before lines to print.
eg's avatar
eg committed
1271

1272 1273 1274
Arguments:
  p         start of the subsequent line
  startptr  start of available data
eg's avatar
eg committed
1275

1276 1277
Returns:    pointer to the start of the previous line
*/
eg's avatar
eg committed
1278

1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
static char *
previous_line(char *p, char *startptr)
{
switch(endlinetype)
  {
  default:      /* Just in case */
  case EL_LF:
  p--;
  while (p > startptr && p[-1] != '\n') p--;
  return p;

  case EL_CR:
  p--;
  while (p > startptr && p[-1] != '\n') p--;
  return p;

  case EL_CRLF:
  for (;;)
    {
    p -= 2;
    while (p > startptr && p[-1] != '\n') p--;
    if (p <= startptr + 1 || p[-2] == '\r') return p;
    }
1302
  /* Control can never get here */
eg's avatar
eg committed
1303

1304 1305 1306 1307
  case EL_ANY:
  case EL_ANYCRLF:
  if (*(--p) == '\n' && p > startptr && p[-1] == '\r') p--;
  if (utf8) while ((*p & 0xc0) == 0x80) p--;
eg's avatar
eg committed
1308

1309 1310
  while (p > startptr)
    {
1311
    register unsigned int c;
1312
    char *pp = p - 1;
eg's avatar
eg committed
1313

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    if (utf8)
      {
      int extra = 0;
      while ((*pp & 0xc0) == 0x80) pp--;
      c = *((unsigned char *)pp);
      if (c >= 0xc0)
        {
        int gcii, gcss;
        extra = utf8_table4[c & 0x3f];  /* Number of additional bytes */
        gcss = 6*extra;
        c = (c & utf8_table3[extra]) << gcss;
        for (gcii = 1; gcii <= extra; gcii++)
          {
          gcss -= 6;
          c |= (pp[gcii] & 0x3f) << gcss;
          }
        }
      }
    else c = *((unsigned char *)pp);
eg's avatar
eg committed
1333

1334 1335
    if (endlinetype == EL_ANYCRLF) switch (c)
      {
1336 1337
      case '\n':    /* LF */
      case '\r':    /* CR */
1338
      return p;
eg's avatar
eg committed
1339

1340 1341 1342
      default:
      break;
      }
eg's avatar
eg committed
1343

1344 1345
    else switch (c)
      {
1346 1347 1348 1349 1350 1351 1352 1353 1354
      case '\n':    /* LF */
      case '\v':    /* VT */
      case '\f':    /* FF */
      case '\r':    /* CR */
#ifndef EBCDIE
      case 0x85:    /* Unicode NEL */
      case 0x2028:  /* Unicode LS */
      case 0x2029:  /* Unicode PS */
#endif  /* Not EBCDIC */
1355 1356 1357 1358 1359
      return p;

      default:
      break;
      }
eg's avatar
eg committed
1360

1361 1362 1363 1364 1365
    p = pp;  /* Back one character */
    }        /* End of loop for ANY case */

  return startptr;  /* Hit start of data */
  }     /* End of overall switch */
eg's avatar
eg committed
1366 1367 1368 1369 1370
}




1371

eg's avatar
eg committed
1372
/*************************************************
1373
*       Print the previous "after" lines         *
eg's avatar
eg committed
1374 1375
*************************************************/

1376 1377 1378
/* This is called if we are about to lose said lines because of buffer filling,
and at the end of the file. The data in the line is written using fwrite() so
that a binary zero does not terminate it.
eg's avatar
eg committed
1379

1380 1381 1382 1383 1384
Arguments:
  lastmatchnumber   the number of the last matching line, plus one
  lastmatchrestart  where we restarted after the last match
  endptr            end of available data
  printname         filename for printing
eg's avatar
eg committed
1385

1386 1387
Returns:            nothing
*/
eg's avatar
eg committed
1388

1389 1390
static void
do_after_lines(unsigned long int lastmatchnumber, char *lastmatchrestart,
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
  char *endptr, char *printname)
{
if (after_context > 0 && lastmatchnumber > 0)
  {
  int count = 0;
  while (lastmatchrestart < endptr && count++ < after_context)
    {
    int ellength;
    char *pp = lastmatchrestart;
    if (printname != NULL) fprintf(stdout, "%s-", printname);
1401
    if (number) fprintf(stdout, "%lu-", lastmatchnumber++);
1402
    pp = end_of_line(pp, endptr, &ellength);
1403
    FWRITE(lastmatchrestart, 1, pp - lastmatchrestart, stdout);
1404 1405 1406 1407
    lastmatchrestart = pp;
    }
  hyphenpending = TRUE;
  }
eg's avatar
eg committed
1408 1409 1410 1411
}



1412 1413 1414 1415 1416 1417 1418 1419 1420
/*************************************************
*   Apply patterns to subject till one matches   *
*************************************************/

/* This function is called to run through all patterns, looking for a match. It
is used multiple times for the same subject when colouring is enabled, in order
to find all possible matches.

Arguments:
1421 1422 1423 1424 1425 1426
  matchptr     the start of the subject
  length       the length of the subject to match
  options      options for pcre_exec
  startoffset  where to start matching
  offsets      the offets vector to fill in
  mrc          address of where to put the result of pcre_exec()
1427 1428 1429 1430 1431 1432 1433

Returns:      TRUE if there was a match
              FALSE if there was no match
              invert if there was a non-fatal error
*/

static BOOL
1434 1435
match_patterns(char *matchptr, size_t length, unsigned int options,
  int startoffset, int *offsets, int *mrc)
1436 1437
{
int i;
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
size_t slen = length;
patstr *p = patterns;
const char *msg = "this text:\n\n";

if (slen > 200)
  {
  slen = 200;
  msg = "text that starts:\n\n";
  }
for (i = 1; p != NULL; p = p->next, i++)
1448
  {
1449 1450
  *mrc = pcre_exec(p->compiled, p->hint, matchptr, (int)length,
    startoffset, options, offsets, OFFSET_SIZE);
1451 1452
  if (*mrc >= 0) return TRUE;
  if (*mrc == PCRE_ERROR_NOMATCH) continue;
1453 1454 1455 1456 1457 1458 1459 1460
  fprintf(stderr, "pcregrep: pcre_exec() gave error %d while matching ", *mrc);
  if (patterns->next != NULL) fprintf(stderr, "pattern number %d to ", i);
  fprintf(stderr, "%s", msg);
  FWRITE(matchptr, 1, slen, stderr);   /* In case binary zero included */
  fprintf(stderr, "\n\n");
  if (*mrc == PCRE_ERROR_MATCHLIMIT || *mrc == PCRE_ERROR_RECURSIONLIMIT ||
      *mrc == PCRE_ERROR_JIT_STACKLIMIT)
    resource_error = TRUE;
1461 1462
  if (error_count++ > 20)
    {
1463 1464
    fprintf(stderr, "pcregrep: Too many errors - abandoned.\n");
    pcregrep_exit(2);
1465 1466 1467 1468 1469 1470 1471 1472 1473
    }
  return invert;    /* No more matching; don't show the line again */
  }

return FALSE;  /* No match, no errors */
}



eg's avatar
eg committed
1474
/*************************************************
1475
*            Grep an individual file             *
eg's avatar
eg committed
1476 1477
*************************************************/

1478
/* This is called from grep_or_recurse() below. It uses a buffer that is three
1479
times the value of bufthird. The matching point is never allowed to stray into
1480 1481 1482 1483 1484 1485
the top third of the buffer, thus keeping more of the file available for
context printing or for multiline scanning. For large files, the pointer will
be in the middle third most of the time, so the bottom third is available for
"before" context printing.

Arguments:
1486 1487 1488 1489
  handle       the fopened FILE stream for a normal file
               the gzFile pointer when reading is via libz
               the BZFILE pointer when reading is via libbz2
  frtype       FR_PLAIN, FR_LIBZ, or FR_LIBBZ2
1490
  filename     the file name or NULL (for errors)
1491 1492 1493 1494 1495 1496
  printname    the file name if it is to be printed for each match
               or NULL if the file name is not to be printed
               it cannot be NULL if filenames[_nomatch]_only is set

Returns:       0 if there was at least one match
               1 otherwise (no matches)
1497 1498
               2 if an overlong line is encountered
               3 if there is a read error on a .bz2 file
1499 1500 1501
*/

static int
1502
pcregrep(void *handle, int frtype, char *filename, char *printname)
eg's avatar
eg committed
1503 1504
{
int rc = 1;
1505 1506
int filepos = 0;
int offsets[OFFSET_SIZE];
1507 1508 1509
unsigned long int linenumber = 1;
unsigned long int lastmatchnumber = 0;
unsigned long int count = 0;
1510
char *lastmatchrestart = NULL;
1511
char *ptr = main_buffer;
1512 1513
char *endptr;
size_t bufflength;
1514
BOOL binary = FALSE;
1515
BOOL endhyphenpending = FALSE;
1516
BOOL input_line_buffered = line_buffered;
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
FILE *in = NULL;                    /* Ensure initialized */

#ifdef SUPPORT_LIBZ
gzFile ingz = NULL;
#endif

#ifdef SUPPORT_LIBBZ2
BZFILE *inbz2 = NULL;
#endif


/* Do the first read into the start of the buffer and set up the pointer to end
of what we have. In the case of libz, a non-zipped .gz file will be read as a
plain file. However, if a .bz2 file isn't actually bzipped, the first read will
fail. */

1533 1534
(void)frtype;

1535 1536 1537 1538
#ifdef SUPPORT_LIBZ
if (frtype == FR_LIBZ)
  {
  ingz = (gzFile)handle;
1539
  bufflength = gzread (ingz, main_buffer, bufsize);
1540 1541 1542
  }
else
#endif
eg's avatar
eg committed
1543

1544 1545 1546 1547
#ifdef SUPPORT_LIBBZ2
if (frtype == FR_LIBBZ2)
  {
  inbz2 = (BZFILE *)handle;
1548
  bufflength = BZ2_bzread(inbz2, main_buffer, bufsize);
1549 1550 1551 1552 1553 1554 1555
  if ((int)bufflength < 0) return 2;   /* Gotcha: bufflength is size_t; */
  }                                    /* without the cast it is unsigned. */
else
#endif

  {
  in = (FILE *)handle;
1556 1557 1558 1559
  if (is_file_tty(in)) input_line_buffered = TRUE;
  bufflength = input_line_buffered?
    read_one_line(main_buffer, bufsize, in) :
    fread(main_buffer, 1, bufsize, in);
1560
  }
eg's avatar
eg committed
1561

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
endptr = main_buffer + bufflength;

/* Unless binary-files=text, see if we have a binary file. This uses the same
rule as GNU grep, namely, a search for a binary zero byte near the start of the
file. */

if (binary_files != BIN_TEXT)
  {
  binary =
    memchr(main_buffer, 0, (bufflength > 1024)? 1024 : bufflength) != NULL;
  if (binary && binary_files == BIN_NOMATCH) return 1;
  }
1574 1575 1576 1577 1578 1579 1580

/* Loop while the current pointer is not at the end of the file. For large
files, endptr will be at the end of the buffer when we are in the middle of the
file, but ptr will never get there, because as soon as it gets over 2/3 of the
way, the buffer is shifted left and re-filled. */

while (ptr < endptr)
eg's avatar
eg committed
1581
  {
1582
  int endlinelength;
1583
  int mrc = 0;
1584 1585 1586
  int startoffset = 0;
  int prevoffsets[2];
  unsigned int options = 0;
1587 1588
  BOOL match;
  char *matchptr = ptr;
1589 1590
  char *t = ptr;
  size_t length, linelength;
eg's avatar
eg committed
1591

1592 1593
  prevoffsets[0] = prevoffsets[1] = -1;

1594 1595 1596
  /* At this point, ptr is at the start of a line. We need to find the length
  of the subject string to pass to pcre_exec(). In multiline mode, it is the
  length remainder of the data in the buffer. Otherwise, it is the length of
1597 1598 1599 1600
  the next line, excluding the terminating newline. After matching, we always
  advance by the length of the next line. In multiline mode the PCRE_FIRSTLINE
  option is used for compiling, so that any match is constrained to be in the
  first line. */
eg's avatar
eg committed
1601

1602 1603 1604
  t = end_of_line(t, endptr, &endlinelength);
  linelength = t - ptr - endlinelength;
  length = multiline? (size_t)(endptr - ptr) : linelength;
eg's avatar
eg committed
1605

1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
  /* Check to see if the line we are looking at extends right to the very end
  of the buffer without a line terminator. This means the line is too long to
  handle. */

  if (endlinelength == 0 && t == main_buffer + bufsize)
    {
    fprintf(stderr, "pcregrep: line %lu%s%s is too long for the internal buffer\n"
                    "pcregrep: check the --buffer-size option\n",
                    linenumber,
                    (filename == NULL)? "" : " of file ",
                    (filename == NULL)? "" : filename);
    return 2;
    }

1620
  /* Extra processing for Jeffrey Friedl's debugging. */
eg's avatar
eg committed
1621

1622 1623 1624
#ifdef JFRIEDL_DEBUG
  if (jfriedl_XT || jfriedl_XR)
  {
1625 1626
#     include <sys/time.h>
#     include <time.h>
1627 1628
      struct timeval start_time, end_time;
      struct timezone dummy;
1629
      int i;
eg's avatar
eg committed
1630

1631
      if (jfriedl_XT)
eg's avatar
eg committed
1632
      {
1633 1634 1635 1636 1637
          unsigned long newlen = length * jfriedl_XT + strlen(jfriedl_prefix) + strlen(jfriedl_postfix);
          const char *orig = ptr;
          ptr = malloc(newlen + 1);
          if (!ptr) {
                  printf("out of memory");
1638
                  pcregrep_exit(2);
1639 1640 1641 1642 1643 1644 1645 1646 1647
          }
          endptr = ptr;
          strcpy(endptr, jfriedl_prefix); endptr += strlen(jfriedl_prefix);
          for (i = 0; i < jfriedl_XT; i++) {
                  strncpy(endptr, orig,  length);
                  endptr += length;
          }
          strcpy(endptr, jfriedl_postfix); endptr += strlen(jfriedl_postfix);
          length = newlen;
eg's avatar
eg committed
1648 1649
      }

1650 1651 1652 1653 1654
      if (gettimeofday(&start_time, &dummy) != 0)
              perror("bad gettimeofday");


      for (i = 0; i < jfriedl_XR; i++)
1655
          match = (pcre_exec(patterns->compiled, patterns->hint, ptr, length, 0,
1656
              PCRE_NOTEMPTY, offsets, OFFSET_SIZE) >= 0);
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669

      if (gettimeofday(&end_time, &dummy) != 0)
              perror("bad gettimeofday");

      double delta = ((end_time.tv_sec + (end_time.tv_usec / 1000000.0))
                      -
                      (start_time.tv_sec + (start_time.tv_usec / 1000000.0)));

      printf("%s TIMER[%.4f]\n", match ? "MATCH" : "FAIL", delta);
      return 0;
  }
#endif

1670 1671 1672
  /* We come back here after a match when show_only_matching is set, in order
  to find any further matches in the same line. This applies to
  --only-matching, --file-offsets, and --line-offsets. */
1673

1674
  ONLY_MATCHING_RESTART:
1675

1676 1677
  /* Run through all the patterns until one matches or there is an error other
  than NOMATCH. This code is in a subroutine so that it can be re-used for
1678 1679 1680
  finding subsequent matches when colouring matched lines. After finding one
  match, set PCRE_NOTEMPTY to disable any further matches of null strings in
  this line. */
1681

1682 1683
  match = match_patterns(matchptr, length, options, startoffset, offsets, &mrc);
  options = PCRE_NOTEMPTY;
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694

  /* If it's a match or a not-match (as required), do what's wanted. */

  if (match != invert)
    {
    BOOL hyphenprinted = FALSE;

    /* We've failed if we want a file that doesn't have any matches. */

    if (filenames == FN_NOMATCH_ONLY) return 1;

1695 1696 1697 1698
    /* If all we want is a yes/no answer, stop now. */

    if (quiet) return 0;

1699 1700
    /* Just count if just counting is wanted. */

1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
    else if (count_only) count++;

    /* When handling a binary file and binary-files==binary, the "binary"
    variable will be set true (it's false in all other cases). In this
    situation we just want to output the file name. No need to scan further. */

    else if (binary)
      {
      fprintf(stdout, "Binary file %s matches\n", filename);
      return 0;
      }
1712 1713 1714 1715

    /* If all we want is a file name, there is no need to scan any more lines
    in the file. */

1716
    else if (filenames == FN_MATCH_ONLY)
1717 1718 1719 1720 1721
      {
      fprintf(stdout, "%s\n", printname);
      return 0;
      }

1722 1723 1724 1725 1726 1727 1728 1729
    /* The --only-matching option prints just the substring that matched,
    and/or one or more captured portions of it, as long as these strings are
    not empty. The --file-offsets and --line-offsets options output offsets for
    the matching substring (all three set show_only_matching). None of these
    mutually exclusive options prints any context. Afterwards, adjust the start
    and then jump back to look for further matches in the same line. If we are
    in invert mode, however, nothing is printed and we do not restart - this
    could still be useful because the return code is set. */
1730

1731
    else if (show_only_matching)
1732
      {
1733 1734
      if (!invert)
        {
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
        int oldstartoffset = startoffset;

        /* It is possible, when a lookbehind assertion contains \K, for the
        same string to be found again. The code below advances startoffset, but
        until it is past the "bumpalong" offset that gave the match, the same
        substring will be returned. The PCRE1 library does not return the
        bumpalong offset, so all we can do is ignore repeated strings. (PCRE2
        does this better.) */

        if (prevoffsets[0] != offsets[0] || prevoffsets[1] != offsets[1])
1745
          {
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
          prevoffsets[0] = offsets[0];
          prevoffsets[1] = offsets[1];

          if (printname != NULL) fprintf(stdout, "%s:", printname);
          if (number) fprintf(stdout, "%lu:", linenumber);

          /* Handle --line-offsets */

          if (line_offsets)
            fprintf(stdout, "%d,%d\n", (int)(matchptr + offsets[0] - ptr),
              offsets[1] - offsets[0]);

          /* Handle --file-offsets */

          else if (file_offsets)
            fprintf(stdout, "%d,%d\n",
              (int)(filepos + matchptr + offsets[0] - ptr),
              offsets[1] - offsets[0]);

          /* Handle --only-matching, which may occur many times */

          else
            {
            BOOL printed = FALSE;
            omstr *om;

            for (om = only_matching; om != NULL; om = om->next)
              {
              int n = om->groupnum;
              if (n < mrc)
                {
                int plen = offsets[2*n + 1] - offsets[2*n];
                if (plen > 0)
                  {
                  if (printed) fprintf(stdout, "%s", om_separator);
                  if (do_colour) fprintf(stdout, "%c[%sm", 0x1b, colour_string);
                  FWRITE(matchptr + offsets[n*2], 1, plen, stdout);
                  if (do_colour) fprintf(stdout, "%c[00m", 0x1b);
                  printed = TRUE;
                  }
                }
              }

            if (printed || printname != NULL || number) fprintf(stdout, "\n");
            }
1791
          }
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802

        /* Prepare to repeat to find the next match. If the patterned contained
        a lookbehind tht included \K, it is possible that the end of the match
        might be at or before the actual strting offset we have just used. We
        need to start one character further on. Unfortunately, for unanchored
        patterns, the actual start offset can be greater that the one that was
        set as a result of "bumpalong". PCRE1 does not return the actual start
        offset, so we have to check against the original start offset. This may
        lead to duplicates - we we need the fudge above to avoid printing them.
        (PCRE2 does this better.) */

1803
        match = FALSE;
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
        if (line_buffered) fflush(stdout);
        rc = 0;                      /* Had some success */

        startoffset = offsets[1];    /* Restart after the match */
        if (startoffset <= oldstartoffset)
          {
          if ((size_t)startoffset >= length)
            goto END_ONE_MATCH;              /* We were at the end */
          startoffset = oldstartoffset + 1;
          if (utf8)
            while ((matchptr[startoffset] & 0xc0) == 0x80) startoffset++;
          }

        /* If the current match ended past the end of the line (only possible
        in multiline mode), we must move on to the line in which it did end
        before searching for more matches. */

        while (startoffset > (int)linelength)
          {
          matchptr = ptr += linelength + endlinelength;
          filepos += (int)(linelength + endlinelength);
          linenumber++;
          startoffset -= (int)(linelength + endlinelength);
          t = end_of_line(ptr, endptr, &endlinelength);
          linelength = t - ptr - endlinelength;
          length = (size_t)(endptr - ptr);
          }

1832 1833
        goto ONLY_MATCHING_RESTART;
        }
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
      }

    /* This is the default case when none of the above options is set. We print
    the matching lines(s), possibly preceded and/or followed by other lines of
    context. */

    else
      {
      /* See if there is a requirement to print some "after" lines from a
      previous match. We never print any overlaps. */

      if (after_context > 0 && lastmatchnumber > 0)
        {
        int ellength;
        int linecount = 0;
        char *p = lastmatchrestart;

        while (p < ptr && linecount < after_context)
          {
          p = end_of_line(p, ptr, &ellength);
          linecount++;
          }

        /* It is important to advance lastmatchrestart during this printing so
        that it interacts correctly with any "before" printing below. Print
        each line's data using fwrite() in case there are binary zeroes. */

        while (lastmatchrestart < p)
          {
          char *pp = lastmatchrestart;
          if (printname != NULL) fprintf(stdout, "%s-", printname);
1865
          if (number) fprintf(stdout, "%lu-", lastmatchnumber++);
1866
          pp = end_of_line(pp, endptr, &ellength);
1867
          FWRITE(lastmatchrestart, 1, pp - lastmatchrestart, stdout);
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
          lastmatchrestart = pp;
          }
        if (lastmatchrestart != ptr) hyphenpending = TRUE;
        }

      /* If there were non-contiguous lines printed above, insert hyphens. */

      if (hyphenpending)
        {
        fprintf(stdout, "--\n");
        hyphenpending = FALSE;
        hyphenprinted = TRUE;
        }

      /* See if there is a requirement to print some "before" lines for this
      match. Again, don't print overlaps. */

      if (before_context > 0)
        {
        int linecount = 0;
        char *p = ptr;

1890
        while (p > main_buffer && (lastmatchnumber == 0 || p > lastmatchrestart) &&
1891 1892 1893
               linecount < before_context)
          {
          linecount++;
1894
          p = previous_line(p, main_buffer);
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
          }

        if (lastmatchnumber > 0 && p > lastmatchrestart && !hyphenprinted)
          fprintf(stdout, "--\n");

        while (p < ptr)
          {
          int ellength;
          char *pp = p;
          if (printname != NULL) fprintf(stdout, "%s-", printname);
1905
          if (number) fprintf(stdout, "%lu-", linenumber - linecount--);
1906
          pp = end_of_line(pp, endptr, &ellength);
1907