-
Notifications
You must be signed in to change notification settings - Fork 101
/
ugrep.cpp
11105 lines (9432 loc) · 358 KB
/
ugrep.cpp
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
/******************************************************************************\
* Copyright (c) 2019, Robert van Engelen, Genivia Inc. All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* (1) Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* (2) 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. *
* *
* (3) The name of the author may not be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. *
\******************************************************************************/
/**
@file ugrep.cpp
@brief a pattern search utility written in C++11
@author Robert van Engelen - engelen@genivia.com
@copyright (c) 2019-2021, Robert van Engelen, Genivia Inc. All rights reserved.
@copyright (c) BSD-3 License - see LICENSE.txt
For download and installation instructions:
https://github.com/Genivia/ugrep
This program uses RE/flex:
https://github.com/Genivia/RE-flex
Optional libraries to support options -P and -z:
-P: PCRE2 or Boost.Regex
-z: zlib (.gz)
-z: libbz2 (.bz, bz2, .bzip2)
-z: liblzma (.lzma, .xz)
-z: liblz4 (.lz4)
-z: libzstd (.zst, .zstd)
Build ugrep as follows:
$ ./configure --enable-colors
$ make -j
Git does not preserve time stamps so ./configure may fail, in that case do:
$ autoreconf -fi
$ ./configure --enable-colors
$ make -j
After this, you may want to test ugrep and install it (optional):
$ make test
$ sudo make install
*/
#include "ugrep.hpp"
#include "glob.hpp"
#include "mmap.hpp"
#include "output.hpp"
#include "query.hpp"
#include "stats.hpp"
#include <reflex/matcher.h>
#include <reflex/fuzzymatcher.h>
#include <iomanip>
#include <cctype>
#include <limits>
#include <functional>
#include <list>
#include <deque>
#include <thread>
#include <memory>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <sstream>
#ifdef OS_WIN
// compiling for a windows OS, except Cygwin and MinGW
// optionally enable --color=auto by default
// #define WITH_COLOR
// optionally enable PCRE2 for -P
// #define HAVE_PCRE2
// optionally enable Boost.Regex for -P
// #define HAVE_BOOST_REGEX
// optionally enable zlib for -z
// #define HAVE_LIBZ
// optionally enable libbz2 for -z
// #define HAVE_LIBBZ2
// optionally enable liblzma for -z
// #define HAVE_LIBLZMA
// optionally enable liblz4 for -z
// #define HAVE_LIBLZ4
// optionally enable libzstd for -z
// #define HAVE_LIBZSTD
#include <stringapiset.h>
#include <direct.h>
#else
// not compiling for a windows OS
#include <signal.h>
#include <dirent.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
// use PCRE2 for option -P
#ifdef HAVE_PCRE2
# include <reflex/pcre2matcher.h>
#else
// use Boost.Regex for option -P
# ifdef HAVE_BOOST_REGEX
# include <reflex/boostmatcher.h>
# endif
#endif
// optional: specify an optimal decompression block size, default is 65536, must be larger than 1024 for tar extraction
// #define Z_BUF_LEN 16384
// #define Z_BUF_LEN 32768
// use zlib, libbz2, liblzma for option -z
#ifdef HAVE_LIBZ
# include "zstream.hpp"
#endif
// ugrep exit codes
#define EXIT_OK 0 // One or more lines were selected
#define EXIT_FAIL 1 // No lines were selected
#define EXIT_ERROR 2 // An error occurred
// limit the total number of threads spawn (i.e. limit spawn overhead), because grepping is practically IO bound
#ifndef MAX_JOBS
# define MAX_JOBS 16U
#endif
// limit the job queue size to wait to give the worker threads some slack
#ifndef MAX_JOB_QUEUE_SIZE
# define MAX_JOB_QUEUE_SIZE 65536
#endif
// a hard limit on the recursive search depth
#ifndef MAX_DEPTH
# define MAX_DEPTH 100
#endif
// --min-steal default, the minimum co-worker's queue size of pending jobs to steal a job from, smaller values result in higher job stealing rates, should not be less than 3
#ifndef MIN_STEAL
# define MIN_STEAL 3U
#endif
// use dirent d_type when available to improve performance
#ifdef HAVE_STRUCT_DIRENT_D_TYPE
# define DIRENT_TYPE_UNKNOWN DT_UNKNOWN
# define DIRENT_TYPE_LNK DT_LNK
# define DIRENT_TYPE_DIR DT_DIR
# define DIRENT_TYPE_REG DT_REG
#else
# define DIRENT_TYPE_UNKNOWN 0
# define DIRENT_TYPE_LNK 1
# define DIRENT_TYPE_DIR 1
# define DIRENT_TYPE_REG 1
#endif
// the -M MAGIC pattern DFA constructed before threads start, read-only afterwards
reflex::Pattern magic_pattern; // concurrent access is thread safe
reflex::Matcher magic_matcher; // concurrent access is not thread safe
// the --filter-magic-label pattern DFA
reflex::Pattern filter_magic_pattern; // concurrent access is thread safe
// TTY detected
bool tty_term = false;
// color term detected
bool color_term = false;
#ifdef OS_WIN
// CTRL-C handler
BOOL WINAPI sigint(DWORD signal)
{
if (signal == CTRL_C_EVENT || signal == CTRL_BREAK_EVENT)
{
// be nice, reset colors on interrupt when sending output to a color TTY
if (color_term)
color_term = write(1, "\033[m", 3) > 0; // appease -Wunused-result
}
// return FALSE to invoke the next handler (when applicable) or just exit
return FALSE;
}
#else
// SIGINT and SIGTERM handler
static void sigint(int sig)
{
// reset to the default handler
signal(sig, SIG_DFL);
// be nice, reset colors on interrupt when sending output to a color TTY
if (color_term)
color_term = write(1, "\033[m", 3) > 0; // appease -Wunused-result
// signal again
kill(getpid(), sig);
}
#endif
// full home directory path
const char *home_dir = NULL;
// ANSI SGR substrings extracted from GREP_COLORS
char color_sl[COLORLEN]; // selected line
char color_cx[COLORLEN]; // context line
char color_mt[COLORLEN]; // matched text in any matched line
char color_ms[COLORLEN]; // matched text in a selected line
char color_mc[COLORLEN]; // matched text in a context line
char color_fn[COLORLEN]; // file name
char color_ln[COLORLEN]; // line number
char color_cn[COLORLEN]; // column number
char color_bn[COLORLEN]; // byte offset
char color_se[COLORLEN]; // separator
char match_ms[COLORLEN]; // --match or --tag: matched text in a selected line
char match_mc[COLORLEN]; // --match or --tag: matched text in a context line
char match_off[COLORLEN]; // --match or --tag: off
std::string color_wd; // hyperlink working directory path
const char *color_hl = NULL; // hyperlink
const char *color_st = NULL; // ST
const char *color_del = ""; // erase line after the cursor
const char *color_off = ""; // disable colors
const char *color_high = ""; // stderr highlighted text
const char *color_error = ""; // stderr error text
const char *color_warning = ""; // stderr warning text
const char *color_message = ""; // stderr error or warning message text
// number of concurrent threads for workers
size_t threads;
// number of warnings given
std::atomic_size_t warnings;
// redirectable source is standard input by default or a pipe
FILE *source = stdin;
// redirectable output destination is standard output by default or a pipe
FILE *output = stdout;
// Grep object handle, to cancel the search with cancel_ugrep()
struct Grep *grep_handle = NULL;
std::mutex grep_handle_mutex;
// set/clear the handle to be able to use cancel_ugrep()
void set_grep_handle(struct Grep*);
void clear_grep_handle();
#ifndef OS_WIN
// output file stat is available when stat() result is true
bool output_stat_result = false;
bool output_stat_regular = false;
struct stat output_stat;
// container of inodes to detect directory cycles when symlinks are traversed with --dereference
std::set<ino_t> visited;
#ifdef HAVE_STATVFS
// containers of file system ids to exclude from recursive searches or include in recursive searches
std::set<uint64_t> exclude_fs_ids, include_fs_ids;
#endif
#endif
// ugrep command-line options
bool flag_all_threads = false;
bool flag_any_line = false;
bool flag_basic_regexp = false;
bool flag_bool = false;
bool flag_confirm = DEFAULT_CONFIRM;
bool flag_count = false;
bool flag_cpp = false;
bool flag_csv = false;
bool flag_decompress = false;
bool flag_dereference = false;
bool flag_files_with_matches = false;
bool flag_files_without_match = false;
bool flag_fixed_strings = false;
bool flag_hex_ast = false;
bool flag_hex_cbr = true;
bool flag_hex_chr = true;
bool flag_hex_hbr = true;
bool flag_hidden = DEFAULT_HIDDEN;
bool flag_invert_match = false;
bool flag_json = false;
bool flag_line_buffered = false;
bool flag_line_regexp = false;
bool flag_match = false;
bool flag_no_dereference = false;
bool flag_no_header = false;
bool flag_no_messages = false;
bool flag_not = false;
bool flag_null = false;
bool flag_only_line_number = false;
bool flag_only_matching = false;
bool flag_perl_regexp = false;
bool flag_pretty = DEFAULT_PRETTY;
bool flag_quiet = false;
bool flag_sort_rev = false;
bool flag_stdin = false;
bool flag_usage_warnings = false;
bool flag_word_regexp = false;
bool flag_xml = false;
bool flag_hex = false;
bool flag_with_hex = false;
bool flag_no_filename = false;
bool flag_with_filename = false;
Flag flag_binary;
Flag flag_binary_without_match;
Flag flag_break;
Flag flag_byte_offset;
Flag flag_column_number;
Flag flag_empty;
Flag flag_dotall;
Flag flag_free_space;
Flag flag_heading;
Flag flag_ignore_case;
Flag flag_initial_tab;
Flag flag_line_number;
Flag flag_smart_case;
Flag flag_text;
Flag flag_ungroup;
Sort flag_sort_key = Sort::NA;
Action flag_devices_action = Action::SKIP;
Action flag_directories_action = Action::SKIP;
size_t flag_after_context = 0;
size_t flag_before_context = 0;
size_t flag_fuzzy = 0;
size_t flag_hex_columns = 16;
size_t flag_jobs = 0;
size_t flag_max_count = 0;
size_t flag_max_depth = 0;
size_t flag_max_files = 0;
size_t flag_max_line = 0;
size_t flag_max_mmap = DEFAULT_MAX_MMAP_SIZE;
size_t flag_min_depth = 0;
size_t flag_min_line = 0;
size_t flag_min_magic = 1;
size_t flag_min_steal = MIN_STEAL;
size_t flag_not_magic = 0;
size_t flag_query = 0;
size_t flag_tabs = DEFAULT_TABS;
const char *flag_apply_color = NULL;
const char *flag_binary_files = "binary";
const char *flag_color = DEFAULT_COLOR;
const char *flag_colors = NULL;
const char *flag_config = NULL;
const char *flag_devices = "skip";
const char *flag_directories = "skip";
const char *flag_encoding = NULL;
const char *flag_filter = NULL;
const char *flag_format = NULL;
const char *flag_format_begin = NULL;
const char *flag_format_close = NULL;
const char *flag_format_end = NULL;
const char *flag_format_open = NULL;
const char *flag_group_separator = "--";
const char *flag_hexdump = NULL;
const char *flag_label = "(standard input)";
const char *flag_pager = DEFAULT_PAGER;
const char *flag_view = "";
const char *flag_save_config = NULL;
const char *flag_separator = ":";
const char *flag_sort = NULL;
const char *flag_stats = NULL;
const char *flag_tag = NULL;
std::string flag_config_file;
std::set<std::string> flag_config_options;
std::vector<std::string> flag_regexp;
std::vector<std::string> flag_file;
std::vector<std::string> flag_file_type;
std::vector<std::string> flag_file_extension;
std::vector<std::string> flag_file_magic;
std::vector<std::string> flag_filter_magic_label;
std::vector<std::string> flag_glob;
std::vector<std::string> flag_ignore_files;
std::vector<std::string> flag_include;
std::vector<std::string> flag_include_dir;
std::vector<std::string> flag_include_from;
std::vector<std::string> flag_include_fs;
std::vector<std::string> flag_exclude;
std::vector<std::string> flag_exclude_dir;
std::vector<std::string> flag_exclude_from;
std::vector<std::string> flag_exclude_fs;
std::vector<std::string> flag_all_include;
std::vector<std::string> flag_all_include_dir;
std::vector<std::string> flag_all_exclude;
std::vector<std::string> flag_all_exclude_dir;
reflex::Input::file_encoding_type flag_encoding_type = reflex::Input::file_encoding::plain;
// the CNF of Boolean search queries and patterns
CNF bcnf;
// ugrep command-line arguments pointing to argv[]
const char *arg_pattern = NULL;
std::vector<const char*> arg_files;
// function protos
void options(std::list<std::pair<CNF::PATTERN,const char*>>& pattern_args, int argc, const char **argv);
void option_regexp(std::list<std::pair<CNF::PATTERN,const char*>>& pattern_args, const char *arg, bool is_neg = false);
void option_and(std::list<std::pair<CNF::PATTERN,const char*>>& pattern_args, int& i, int argc, const char **argv);
void option_and(std::list<std::pair<CNF::PATTERN,const char*>>& pattern_args, const char *arg);
void option_andnot(std::list<std::pair<CNF::PATTERN,const char*>>& pattern_args, int& i, int argc, const char **argv);
void option_andnot(std::list<std::pair<CNF::PATTERN,const char*>>& pattern_args, const char *arg);
void option_not(std::list<std::pair<CNF::PATTERN,const char*>>& pattern_args, int& i, int argc, const char **argv);
void option_not(std::list<std::pair<CNF::PATTERN,const char*>>& pattern_args, const char *arg);
void init(int argc, const char **argv);
void set_color(const char *colors, const char *parameter, char color[COLORLEN]);
void trim(std::string& line);
void trim_pathname_arg(const char *arg);
bool is_output(ino_t inode);
size_t strtonum(const char *string, const char *message);
size_t strtopos(const char *string, const char *message);
void strtopos2(const char *string, size_t& pos1, size_t& pos2, const char *message, bool optional_first = false);
size_t strtofuzzy(const char *string, const char *message);
void split_globs(FILE *file, std::vector<std::string>& files, std::vector<std::string>& dirs);
void format(const char *format, size_t matches);
void usage(const char *message, const char *arg = NULL, const char *valid = NULL);
void help(std::ostream& out);
void help(const char *what = NULL);
void version();
void is_directory(const char *pathname);
void cannot_decompress(const char *pathname, const char *message);
// open a file where - means stdin/stdout and an initial ~ expands to home directory
int fopen_smart(FILE **file, const char *filename, const char *mode)
{
if (filename == NULL || *filename == '\0')
return errno = ENOENT;
if (strcmp(filename, "-") == 0)
{
*file = strchr(mode, 'w') == NULL ? stdin : stdout;
return 0;
}
if (*filename == '~')
return fopenw_s(file, std::string(home_dir).append(filename + 1).c_str(), mode);
return fopenw_s(file, filename, mode);
}
// read a line from buffered input, returns true when eof
inline bool getline(reflex::BufferedInput& input, std::string& line)
{
int ch;
line.erase();
while ((ch = input.get()) != EOF)
{
if (ch == '\n')
break;
line.push_back(ch);
}
if (!line.empty() && line.back() == '\r')
line.pop_back();
return ch == EOF && line.empty();
}
// read a line from mmap memory, returns true when eof
inline bool getline(const char*& here, size_t& left)
{
// read line from mmap memory
if (left == 0)
return true;
const char *s = static_cast<const char*>(memchr(here, '\n', left));
if (s == NULL)
s = here + left;
else
++s;
left -= s - here;
here = s;
return false;
}
// read a line from mmap memory or from buffered input or from unbuffered input, returns true when eof
inline bool getline(const char*& here, size_t& left, reflex::BufferedInput& buffered_input, reflex::Input& input, std::string& line)
{
if (here != NULL)
{
// read line from mmap memory
if (left == 0)
return true;
const char *s = static_cast<const char*>(memchr(here, '\n', left));
if (s == NULL)
s = here + left;
else
++s;
line.assign(here, s - here);
left -= s - here;
here = s;
return false;
}
int ch;
line.erase();
if (buffered_input.assigned())
{
// read line from buffered input
while ((ch = buffered_input.get()) != EOF)
{
line.push_back(ch);
if (ch == '\n')
break;
}
return ch == EOF && line.empty();
}
// read line from unbuffered input
while ((ch = input.get()) != EOF)
{
line.push_back(ch);
if (ch == '\n')
break;
}
return ch == EOF && line.empty();
}
// return true if s[0..n-1] contains a NUL or is non-displayable invalid UTF-8
inline bool is_binary(const char *s, size_t n)
{
if (memchr(s, '\0', n) != NULL)
return true;
const char *e = s + n;
while (s < e)
{
do
{
if ((*s & 0xc0) == 0x80)
return true;
} while ((*s & 0xc0) != 0xc0 && ++s < e);
if (s >= e)
return false;
if (++s >= e || (*s & 0xc0) != 0x80)
return true;
if (++s < e && (*s & 0xc0) == 0x80)
if (++s < e && (*s & 0xc0) == 0x80)
if (++s < e && (*s & 0xc0) == 0x80)
++s;
}
return false;
}
// check if a file's inode is the current output file
inline bool is_output(ino_t inode)
{
#ifdef OS_WIN
return false; // TODO check that two FILE* on Windows are the same, is this possible?
#else
return output_stat_regular && inode == output_stat.st_ino;
#endif
}
// specify a line of input for the matcher to read, matcher must not use text() or rest() to keep the line contents unmodified
inline void read_line(reflex::AbstractMatcher *matcher, const char *line, size_t size)
{
// safe cast: buffer() is read-only if no matcher.text() and matcher.rest() are used, size + 1 to include final \0
matcher->buffer(const_cast<char*>(line), size + 1);
}
// specify a line of input for the matcher to read, matcher must not use text() or rest() to keep the line contents unmodified
inline void read_line(reflex::AbstractMatcher *matcher, const std::string& line)
{
// safe cast: buffer() is read-only if no matcher.text() and matcher.rest() are used, size + 1 to include final \0
matcher->buffer(const_cast<char*>(line.c_str()), line.size() + 1);
}
// copy color buffers
inline void copy_color(char to[COLORLEN], const char from[COLORLEN])
{
size_t len = std::min(strlen(from), static_cast<size_t>(COLORLEN - 1));
memcpy(to, from, len);
to[len] = '\0';
char *comma = strchr(to, ',');
if (comma != NULL)
*comma = '\0';
}
// grep manages output, matcher, input, and decompression
struct Grep {
// CNF of AND/OR/NOT matchers
typedef std::list<std::list<std::unique_ptr<reflex::AbstractMatcher>>> Matchers;
// entry type
enum class Type { SKIP, DIRECTORY, OTHER };
// entry data extracted from directory contents
struct Entry {
Entry(std::string& pathname, ino_t inode, uint64_t info)
:
pathname(std::move(pathname)),
inode(inode),
info(info),
cost(0)
{ }
std::string pathname;
ino_t inode;
uint64_t info;
uint16_t cost;
#ifndef OS_WIN
// get sortable info from stat buf
static uint64_t sort_info(const struct stat& buf)
{
#if defined(HAVE_STAT_ST_ATIM) && defined(HAVE_STAT_ST_MTIM) && defined(HAVE_STAT_ST_CTIM)
// tv_sec may be 64 bit, but value is small enough to multiply by 1000000 to fit in 64 bits
return static_cast<uint64_t>(flag_sort_key == Sort::SIZE ? buf.st_size : flag_sort_key == Sort::USED ? static_cast<uint64_t>(buf.st_atim.tv_sec) * 1000000 + buf.st_atim.tv_nsec / 1000 : flag_sort_key == Sort::CHANGED ? static_cast<uint64_t>(buf.st_mtim.tv_sec) * 1000000 + buf.st_mtim.tv_nsec / 1000 : flag_sort_key == Sort::CREATED ? static_cast<uint64_t>(buf.st_ctim.tv_sec) * 1000000 + buf.st_ctim.tv_nsec / 1000 : 0);
#elif defined(HAVE_STAT_ST_ATIMESPEC) && defined(HAVE_STAT_ST_MTIMESPEC) && defined(HAVE_STAT_ST_CTIMESPEC)
// tv_sec may be 64 bit, but value is small enough to multiply by 1000000 to fit in 64 bits
return static_cast<uint64_t>(flag_sort_key == Sort::SIZE ? buf.st_size : flag_sort_key == Sort::USED ? static_cast<uint64_t>(buf.st_atimespec.tv_sec) * 1000000 + buf.st_atimespec.tv_nsec / 1000 : flag_sort_key == Sort::CHANGED ? static_cast<uint64_t>(buf.st_mtimespec.tv_sec) * 1000000 + buf.st_mtimespec.tv_nsec / 1000 : flag_sort_key == Sort::CREATED ? static_cast<uint64_t>(buf.st_ctimespec.tv_sec) * 1000000 + buf.st_ctimespec.tv_nsec / 1000 : 0);
#else
return static_cast<uint64_t>(flag_sort_key == Sort::SIZE ? buf.st_size : flag_sort_key == Sort::USED ? buf.st_atime : flag_sort_key == Sort::CHANGED ? buf.st_mtime : flag_sort_key == Sort::CREATED ? buf.st_ctime : 0);
#endif
}
#endif
// compare two entries by pathname
static bool comp_by_path(const Entry& a, const Entry& b)
{
return a.pathname < b.pathname;
}
// compare two entries by size or time (atime, mtime, or ctime), if equal compare by pathname
static bool comp_by_info(const Entry& a, const Entry& b)
{
return a.info < b.info || (a.info == b.info && a.pathname < b.pathname);
}
// compare two entries by edit distance cost
static bool comp_by_best(const Entry& a, const Entry& b)
{
return a.cost < b.cost || (a.cost == b.cost && a.pathname < b.pathname);
}
// reverse compare two entries by pathname
static bool rev_comp_by_path(const Entry& a, const Entry& b)
{
return a.pathname > b.pathname;
}
// reverse compare two entries by size or time (atime, mtime, or ctime), if equal reverse compare by pathname
static bool rev_comp_by_info(const Entry& a, const Entry& b)
{
return a.info > b.info || (a.info == b.info && a.pathname > b.pathname);
}
// reverse compare two entries by edit distance cost
static bool rev_comp_by_best(const Entry& a, const Entry& b)
{
return a.cost > b.cost || (a.cost == b.cost && a.pathname > b.pathname);
}
};
#ifndef OS_WIN
// extend the reflex::Input::Handler to handle stdin from a TTY or a slow pipe
struct StdInHandler : public reflex::Input::Handler {
StdInHandler(Grep *grep)
:
grep(grep)
{ }
Grep *grep;
int operator()()
{
grep->out.flush();
while (true)
{
struct timeval tv;
fd_set rfds, efds;
FD_ZERO(&rfds);
FD_ZERO(&efds);
FD_SET(0, &rfds);
FD_SET(0, &efds);
tv.tv_sec = 1;
tv.tv_usec = 0;
int r = ::select(1, &rfds, NULL, &efds, &tv);
if (r < 0 && errno != EINTR)
return 0;
if (r > 0 && FD_ISSET(0, &efds))
return 0;
if (r > 0)
return 1;
}
}
};
#endif
// extend the reflex::AbstractMatcher::Handler with a grep object reference and references to some of the grep::search locals
struct GrepHandler : public reflex::AbstractMatcher::Handler {
GrepHandler(Grep& grep, const char*& pathname, size_t& lineno, bool& binfile, bool& hex, bool& binary, size_t& matches, bool& stop)
:
grep(grep),
pathname(pathname),
lineno(lineno),
binfile(binfile),
hex(hex),
binary(binary),
matches(matches),
stop(stop)
{ }
Grep& grep; // grep object
const char*& pathname; // grep::search argument pathname
size_t& lineno; // grep::search lineno local variable
bool& binfile; // grep::search binfile local variable
bool& hex; // grep::search hex local variable
bool& binary; // grep::search binary local variable
size_t& matches; // grep::search matches local variable
bool& stop; // grep::search stop local variable
// get the start of the before context, if present
void begin_before(reflex::AbstractMatcher& matcher, const char *buf, size_t len, size_t num, const char*& ptr, size_t& size, size_t& offset)
{
ptr = NULL;
size = 0;
offset = 0;
if (len == 0)
return;
size_t current = matcher.lineno();
size_t between = current - lineno;
if (between > 1)
{
const char *s = buf + len;
const char *e = s;
if (buf[len - 1] != '\n')
--between;
while (--s >= buf)
{
if (*s == '\n')
{
if (--between == 0)
break;;
e = s + 1;
}
}
ptr = ++s;
size = e - s;
offset = s - buf + num;
++lineno;
}
}
// advance to the next before context, if present
void next_before(const char *buf, size_t len, size_t num, const char*& ptr, size_t& size, size_t& offset)
{
if (ptr == NULL)
return;
const char *s = ptr + size;
const char *e = buf + len;
if (s >= e)
{
ptr = NULL;
}
else
{
e = static_cast<const char*>(memchr(s, '\n', e - s));
if (e == NULL)
e = buf + len;
else
++e;
ptr = s;
size = e - s;
offset = s - buf + num;
++lineno;
}
}
};
// extend event GrepHandler to output invert match lines for -v
struct InvertMatchGrepHandler : public GrepHandler {
InvertMatchGrepHandler(Grep& grep, const char*& pathname, size_t& lineno, bool& binfile, bool& hex, bool& binary, size_t& matches, bool& stop)
:
GrepHandler(grep, pathname, lineno, binfile, hex, binary, matches, stop)
{ }
// functor invoked by the reflex::AbstractMatcher when the buffer contents are shifted out, also called explicitly in grep::search
virtual void operator()(reflex::AbstractMatcher& matcher, const char *buf, size_t len, size_t num) override
{
const char *ptr;
size_t size;
size_t offset;
begin_before(matcher, buf, len, num, ptr, size, offset);
while (ptr != NULL)
{
// --range: max line exceeded?
if (flag_max_line > 0 && lineno > flag_max_line)
break;
// --max-files: max reached?
if (matches == 0 && !Stats::found_part())
{
stop = true;
break;
}
// -m: max number of matches reached?
if (flag_max_count > 0 && matches >= flag_max_count)
break;
// output blocked?
if (grep.out.eof)
break;
++matches;
if (flag_with_hex)
binary = false;
binary = binary || flag_hex || (!flag_text && is_binary(ptr, size));
if (binfile || (binary && !flag_hex && !flag_with_hex))
break;
if (hex && !binary)
grep.out.dump.done();
if (!flag_no_header)
grep.out.header(pathname, grep.partname, lineno, NULL, offset, flag_separator, binary);
hex = binary;
if (binary)
{
grep.out.dump.hex(Output::Dump::HEX_LINE, offset, ptr, size);
}
else
{
if (size > 0)
{
size_t sizen = size - (ptr[size - 1] == '\n');
if (sizen > 0)
{
grep.out.str(color_sl);
grep.out.str(ptr, sizen);
grep.out.str(color_off);
}
}
grep.out.nl();
}
next_before(buf, len, num, ptr, size, offset);
}
}
};
// extend event GrepHandler to output formatted invert match lines for --format -v
struct FormatInvertMatchGrepHandler : public GrepHandler {
FormatInvertMatchGrepHandler(Grep& grep, const char*& pathname, size_t& lineno, bool& binfile, bool& hex, bool& binary, size_t& matches, bool& stop)
:
GrepHandler(grep, pathname, lineno, binfile, hex, binary, matches, stop)
{ }
// functor invoked by the reflex::AbstractMatcher when the buffer contents are shifted out, also called explicitly in grep::search
virtual void operator()(reflex::AbstractMatcher& matcher, const char *buf, size_t len, size_t num) override
{
const char *ptr;
size_t size;
size_t offset;
begin_before(matcher, buf, len, num, ptr, size, offset);
while (ptr != NULL)
{
// --range: max line exceeded?
if (flag_max_line > 0 && lineno > flag_max_line)
break;
// output --format-open
if (matches == 0)
{
// --format-open or --format-close: we must acquire lock early before Stats::found_part()
if (flag_format_open != NULL || flag_format_close != NULL)
grep.out.acquire();
// --max-files: max reached?
if (!Stats::found_part())
{
stop = true;
break;
}
if (flag_format_open != NULL)
grep.out.format(flag_format_open, pathname, grep.partname, Stats::found_parts(), &matcher, false, Stats::found_parts() > 1);
}
// -m: max number of matches reached?
if (flag_max_count > 0 && matches >= flag_max_count)
break;
// output blocked?
if (grep.out.eof)
break;
++matches;
// output --format
grep.out.format_invert(flag_format, pathname, grep.partname, matches, lineno, offset, ptr, size - (size > 0 && ptr[size - 1] == '\n'), matches > 1);
next_before(buf, len, num, ptr, size, offset);
}
}
};
// extend event GrepHandler to output any context lines for -y
struct AnyLineGrepHandler : public GrepHandler {
AnyLineGrepHandler(Grep& grep, const char*& pathname, size_t& lineno, bool& binfile, bool& hex, bool& binary, size_t& matches, bool& stop, const char*& rest_line_data, size_t& rest_line_size, size_t& rest_line_last)
:
GrepHandler(grep, pathname, lineno, binfile, hex, binary, matches, stop),
rest_line_data(rest_line_data),
rest_line_size(rest_line_size),
rest_line_last(rest_line_last)
{ }
// functor invoked by the reflex::AbstractMatcher when the buffer contents are shifted out, also called explicitly in grep::search
virtual void operator()(reflex::AbstractMatcher& matcher, const char *buf, size_t len, size_t num) override
{
const char *ptr;
size_t size;