-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpcregrep.c
2672 lines (2187 loc) · 75.3 KB
/
pcregrep.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
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
/*************************************************
* pcregrep program *
*************************************************/
/* This is a grep program that uses the PCRE regular expression library to do
its pattern matching. On a Unix or Win32 system it can recurse into
directories.
Copyright (c) 1997-2011 University of Cambridge
-----------------------------------------------------------------------------
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.
-----------------------------------------------------------------------------
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <ctype.h>
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef SUPPORT_LIBZ
#include <zlib.h>
#endif
#ifdef SUPPORT_LIBBZ2
#include <bzlib.h>
#endif
#include "pcre.h"
#define FALSE 0
#define TRUE 1
typedef int BOOL;
#define MAX_PATTERN_COUNT 100
#define OFFSET_SIZE 99
#if BUFSIZ > 8192
#define MBUFTHIRD BUFSIZ
#else
#define MBUFTHIRD 8192
#endif
/* 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. */
enum { FN_NONE, FN_DEFAULT, FN_MATCH_ONLY, FN_NOMATCH_ONLY, FN_FORCE };
/* File reading styles */
enum { FR_PLAIN, FR_LIBZ, FR_LIBBZ2 };
/* 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 };
/* 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)) {}
/*************************************************
* Global variables *
*************************************************/
/* 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;
static char *newline = NULL;
static char *pattern_filename = NULL;
static char *stdin_name = (char *)"(standard input)";
static char *locale = NULL;
static const unsigned char *pcretables = NULL;
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;
static int after_context = 0;
static int before_context = 0;
static int both_context = 0;
static int dee_action = dee_READ;
static int DEE_action = DEE_READ;
static int error_count = 0;
static int filenames = FN_DEFAULT;
static int only_matching = -1;
static int process_options = 0;
static unsigned long int match_limit = 0;
static unsigned long int match_limit_recursion = 0;
static BOOL count_only = FALSE;
static BOOL do_colour = FALSE;
static BOOL file_offsets = FALSE;
static BOOL hyphenpending = FALSE;
static BOOL invert = FALSE;
static BOOL line_buffered = FALSE;
static BOOL line_offsets = FALSE;
static BOOL multiline = FALSE;
static BOOL number = FALSE;
static BOOL omit_zero_count = FALSE;
static BOOL resource_error = FALSE;
static BOOL quiet = FALSE;
static BOOL silent = FALSE;
static BOOL utf8 = FALSE;
/* Structure for options and list of them */
enum { OP_NODATA, OP_STRING, OP_OP_STRING, OP_NUMBER, OP_LONGNUMBER,
OP_OP_NUMBER, OP_PATLIST };
typedef struct option_item {
int type;
int one_char;
void *dataptr;
const char *long_name;
const char *help_text;
} option_item;
/* Options without a single-letter equivalent get a negative value. This can be
used to identify them. */
#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)
#define N_LBUFFER (-12)
#define N_M_LIMIT (-13)
#define N_M_LIMIT_REC (-14)
static option_item optionlist[] = {
{ 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_NUMBER, 'B', &before_context, "before-context=number", "set number of prior context lines" },
{ 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', NULL, "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_STRING, 'f', &pattern_filename, "file=path", "read patterns 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, "ignore-case", "ignore case distinctions" },
{ 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_NUMBER, 'o', &only_matching, "only-matching=n", "show only the part of the line that matched" },
{ OP_NODATA, 'q', NULL, "quiet", "suppress output, just set return code" },
{ OP_NODATA, 'r', NULL, "recursive", "recursively scan sub-directories" },
{ OP_STRING, N_EXCLUDE,&exclude_pattern, "exclude=pattern","exclude matching files when recursing" },
{ OP_STRING, N_INCLUDE,&include_pattern, "include=pattern","include matching files when recursing" },
{ OP_STRING, N_EXCLUDE_DIR,&exclude_dir_pattern, "exclude-dir=pattern","exclude matching directories when recursing" },
{ OP_STRING, N_INCLUDE_DIR,&include_dir_pattern, "include-dir=pattern","include matching directories when recursing" },
/* 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_STRING, N_EXCLUDE_DIR,&exclude_dir_pattern, "exclude_dir=pattern","exclude matching directories when recursing" },
{ OP_STRING, N_INCLUDE_DIR,&include_dir_pattern, "include_dir=pattern","include matching directories when recursing" },
#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 }
};
/* 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
can treat them as the same. */
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 };
/*************************************************
* 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 or %d means that a resource limit "
"was exceeded.\n", PCRE_ERROR_MATCHLIMIT, PCRE_ERROR_RECURSIONLIMIT);
fprintf(stderr, "pcregrep: Check your regex for nested unlimited loops.\n");
}
exit(rc);
}
/*************************************************
* OS-specific functions *
*************************************************/
/* These functions are defined so that they can be made system specific,
although at present the only ones are for Unix, Win32, and for "no support". */
/************* Directory scanning in Unix ***********/
#if defined HAVE_SYS_STAT_H && defined HAVE_DIRENT_H && defined HAVE_SYS_TYPES_H
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
typedef DIR directory_type;
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 */
return ((statbuf.st_mode & S_IFMT) == S_IFDIR)? '/' : 0;
}
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;
}
/* Control never reaches here */
}
static void
closedirectory(directory_type *dir)
{
closedir(dir);
}
/************* Test for regular file in Unix **********/
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;
}
/************* Test for a terminal in Unix **********/
static BOOL
is_stdout_tty(void)
{
return isatty(fileno(stdout));
}
static BOOL
is_file_tty(FILE *f)
{
return isatty(fileno(f));
}
/************* Directory scanning in Win32 ***********/
/* I (Philip Hazel) have no means of testing this code. It was contributed by
Lionel Fourquaux. David Burgess added a patch to define INVALID_FILE_ATTRIBUTES
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.
The double test below stops gcc 4.4.4 grumbling that HAVE_WINDOWS_H is
undefined when it is indeed undefined. */
#elif defined HAVE_WINDOWS_H && HAVE_WINDOWS_H
#ifndef STRICT
# define STRICT
#endif
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#ifndef INVALID_FILE_ATTRIBUTES
#define INVALID_FILE_ATTRIBUTES 0xFFFFFFFF
#endif
typedef struct directory_type
{
HANDLE handle;
BOOL first;
WIN32_FIND_DATA data;
} directory_type;
int
isdirectory(char *filename)
{
DWORD attr = GetFileAttributes(filename);
if (attr == INVALID_FILE_ATTRIBUTES)
return 0;
return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) ? '/' : 0;
}
directory_type *
opendirectory(char *filename)
{
size_t len;
char *pattern;
directory_type *dir;
DWORD err;
len = strlen(filename);
pattern = (char *) malloc(len + 3);
dir = (directory_type *) malloc(sizeof(*dir));
if ((pattern == NULL) || (dir == NULL))
{
fprintf(stderr, "pcregrep: malloc failed\n");
pcregrep_exit(2);
}
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);
}
/************* Test for regular file in Win32 **********/
/* 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)
{
return !isdirectory(filename);
}
/************* Test for a terminal in Win32 **********/
/* I don't know how to do this; assume never */
static BOOL
is_stdout_tty(void)
{
return FALSE;
}
static BOOL
is_file_tty(FILE *f)
{
return FALSE;
}
/************* Directory scanning when we can't do it ***********/
/* The type is void, and apart from isdirectory(), the functions do nothing. */
#else
typedef void directory_type;
int isdirectory(char *filename) { return 0; }
directory_type * opendirectory(char *filename) { return (directory_type*)0;}
char *readdirectory(directory_type *dir) { return (char*)0;}
void closedirectory(directory_type *dir) {}
/************* Test for regular when we can't do it **********/
/* Assume all files are regular. */
int isregfile(char *filename) { return 1; }
/************* Test for a terminal when we can't do it **********/
static BOOL
is_stdout_tty(void)
{
return FALSE;
}
static BOOL
is_file_tty(FILE *f)
{
return FALSE;
}
#endif
#ifndef HAVE_STRERROR
/*************************************************
* 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 */
/*************************************************
* 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 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;
}
/*************************************************
* Find end of line *
*************************************************/
/* 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.
Arguments:
p current position in line
endptr end of available data
lenptr where to put the length of the eol sequence
Returns: pointer to the last byte of the line, including the newline byte(s)
*/
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)
{
*lenptr = 1;
return p + 1;
}
*lenptr = 0;
return endptr;
case EL_CR:
while (p < endptr && *p != '\r') p++;
if (p < endptr)
{
*lenptr = 1;
return p + 1;
}
*lenptr = 0;
return endptr;
case EL_CRLF:
for (;;)
{
while (p < endptr && *p != '\r') p++;
if (++p >= endptr)
{
*lenptr = 0;
return endptr;
}
if (*p == '\n')
{
*lenptr = 2;
return p + 1;
}
}
break;
case EL_ANYCRLF:
while (p < endptr)
{
int extra = 0;
register int c = *((unsigned char *)p);
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;
}
}
p += 1 + extra;
switch (c)
{
case 0x0a: /* LF */
*lenptr = 1;
return p;
case 0x0d: /* CR */
if (p < endptr && *p == 0x0a)
{
*lenptr = 2;
p++;
}
else *lenptr = 1;
return p;
default:
break;
}
} /* End of loop for ANYCRLF case */
*lenptr = 0; /* Must have hit the end */
return endptr;
case EL_ANY:
while (p < endptr)
{
int extra = 0;
register int c = *((unsigned char *)p);
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;
}
}
p += 1 + extra;
switch (c)
{
case 0x0a: /* LF */
case 0x0b: /* VT */
case 0x0c: /* FF */
*lenptr = 1;
return p;
case 0x0d: /* CR */
if (p < endptr && *p == 0x0a)
{
*lenptr = 2;
p++;
}
else *lenptr = 1;
return p;
case 0x85: /* NEL */
*lenptr = utf8? 2 : 1;
return p;
case 0x2028: /* LS */
case 0x2029: /* PS */
*lenptr = 3;
return p;
default:
break;
}
} /* End of loop for ANY case */
*lenptr = 0; /* Must have hit the end */
return endptr;
} /* End of overall switch */
}
/*************************************************
* Find start of previous line *
*************************************************/
/* This is called when looking back for before lines to print.
Arguments:
p start of the subsequent line
startptr start of available data
Returns: pointer to the start of the previous line
*/
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;
}
return p; /* But control should never get here */
case EL_ANY:
case EL_ANYCRLF:
if (*(--p) == '\n' && p > startptr && p[-1] == '\r') p--;
if (utf8) while ((*p & 0xc0) == 0x80) p--;
while (p > startptr)
{
register int c;
char *pp = p - 1;
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);
if (endlinetype == EL_ANYCRLF) switch (c)
{
case 0x0a: /* LF */
case 0x0d: /* CR */
return p;
default:
break;
}
else switch (c)
{
case 0x0a: /* LF */
case 0x0b: /* VT */
case 0x0c: /* FF */
case 0x0d: /* CR */
case 0x85: /* NEL */
case 0x2028: /* LS */
case 0x2029: /* PS */
return p;
default:
break;
}
p = pp; /* Back one character */
} /* End of loop for ANY case */
return startptr; /* Hit start of data */
} /* End of overall switch */
}
/*************************************************
* Print the previous "after" lines *
*************************************************/
/* 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.
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
Returns: nothing
*/
static void do_after_lines(int lastmatchnumber, char *lastmatchrestart,
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);
if (number) fprintf(stdout, "%d-", lastmatchnumber++);
pp = end_of_line(pp, endptr, &ellength);
FWRITE(lastmatchrestart, 1, pp - lastmatchrestart, stdout);
lastmatchrestart = pp;
}
hyphenpending = TRUE;
}
}
/*************************************************
* 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:
matchptr the start of the subject
length the length of the subject to match
offsets the offets vector to fill in
mrc address of where to put the result of pcre_exec()
Returns: TRUE if there was a match
FALSE if there was no match
invert if there was a non-fatal error
*/
static BOOL
match_patterns(char *matchptr, size_t length, int *offsets, int *mrc)
{
int i;
size_t slen = length;
const char *msg = "this text:\n\n";
if (slen > 200)
{
slen = 200;
msg = "text that starts:\n\n";
}
for (i = 0; i < pattern_count; i++)
{
*mrc = pcre_exec(pattern_list[i], hints_list[i], matchptr, (int)length, 0,
PCRE_NOTEMPTY, offsets, OFFSET_SIZE);
if (*mrc >= 0) return TRUE;
if (*mrc == PCRE_ERROR_NOMATCH) continue;
fprintf(stderr, "pcregrep: pcre_exec() gave error %d while matching ", *mrc);
if (pattern_count > 1) fprintf(stderr, "pattern number %d to ", i+1);
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)
resource_error = TRUE;
if (error_count++ > 20)
{
fprintf(stderr, "pcregrep: Too many errors - abandoned.\n");
pcregrep_exit(2);
}
return invert; /* No more matching; don't show the line again */
}
return FALSE; /* No match, no errors */
}
/*************************************************
* Grep an individual file *
*************************************************/
/* This is called from grep_or_recurse() below. It uses a buffer that is three
times the value of MBUFTHIRD. The matching point is never allowed to stray into
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:
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