source: icGREP/icgrep-devel/icgrep/icgrep.cpp @ 5218

Last change on this file since 5218 was 5218, checked in by xuedongx, 3 years ago

Add parser for PROSITE protein patterns

File size: 16.7 KB
Line 
1/*
2 *  Copyright (c) 2016 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7#include <cstdio>
8#include <vector>
9#include <llvm/Support/CommandLine.h>
10#include <llvm/Support/ErrorHandling.h>
11#include <llvm/Support/Signals.h>
12#include <re/re_alt.h>
13#include <re/re_seq.h>
14#include <re/re_start.h>
15#include <re/re_end.h>
16#include <re/re_parser.h>
17#include <re/re_utility.h>
18#include <grep_engine.h>
19#include <fstream>
20#include <string>
21
22#include <boost/uuid/sha1.hpp>
23#include <toolchain.h>
24#include <re/re_toolchain.h>
25#include <pablo/pablo_toolchain.h>
26#include <mutex>
27#include <boost/filesystem.hpp>
28
29#include <iostream> // MEEE
30
31#ifdef PRINT_TIMING_INFORMATION
32#include <hrtime.h>
33#include <util/papi_helper.hpp>
34#endif
35
36static cl::OptionCategory LegacyGrepOptions("A. Standard Grep Options",
37                                       "These are standard grep options intended for compatibility with typical grep usage.");
38
39#ifdef FUTURE
40static cl::OptionCategory RegexpOptions("Regular Expression Interpretation", "These options control regular expression interpretation");
41static cl::opt<re::RE_Syntax> RegexpSyntax(cl::desc("Regular expression syntax:"),
42    cl::values(
43        clEnumValN(re::RE_Syntax::FixedStrings, "F", "Fixed strings, separated by newlines"),
44        clEnumValN(re::RE_Syntax::BRE, "G", "Posix basic regular expression (BRE) syntax"),
45        clEnumValN(re::RE_Syntax::ERE, "E", "Posix extended regular expression (ERE) syntax"),
46        clEnumValN(re::RE_Syntax::PROSITE, "PRO", "PROSITE protein patterns syntax"),
47        clEnumValN(re::RE_Syntax::PCRE, "P", "Perl-compatible regular expression (PCRE) syntax - default"),
48               clEnumValEnd), cl::cat(LegacyGrepOptions), cl::Grouping, cl::init(re::RE_Syntax::PCRE));
49#endif
50
51static cl::opt<bool> EntireLineMatching("x", cl::desc("Require that entire lines be matched."), cl::cat(LegacyGrepOptions), cl::Grouping);
52static cl::alias  EntireLineMatchingAlias("line-regexp", cl::desc("Alias for -x"), cl::aliasopt(EntireLineMatching));
53
54static cl::opt<bool> WholeWordMatching("w", cl::desc("Require that whole words be matched."), cl::cat(LegacyGrepOptions), cl::Grouping);
55static cl::alias WholeWordMatchingAlias("word-regexp", cl::desc("Alias for -w"), cl::aliasopt(WholeWordMatching));
56
57static cl::opt<bool> UTF_16("UTF-16", cl::desc("Regular expressions over the UTF-16 representation of Unicode."), cl::cat(LegacyGrepOptions));
58static cl::OptionCategory EnhancedGrepOptions("B. Enhanced Grep Options",
59                                       "These are additional options for icgrep functionality and performance.");
60
61static cl::opt<bool> FileNamesOnly("l", cl::desc("Display only the names of matching files."), cl::cat(LegacyGrepOptions), cl::Grouping);
62static cl::alias FileNamesAlias("files-with-matches", cl::desc("Alias for -l"), cl::aliasopt(FileNamesOnly));
63
64static cl::opt<bool> NonMatchingFileNamesOnly("L", cl::desc("Display only the names of matching files."), cl::cat(LegacyGrepOptions), cl::Grouping);
65static cl::alias NonMatchingFileNamesAlias("files-without-match", cl::desc("Alias for -L"), cl::aliasopt(NonMatchingFileNamesOnly));
66
67
68static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(LegacyGrepOptions), cl::Grouping);
69static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
70
71
72static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<regex> <input file ...>"), cl::OneOrMore);
73
74static cl::opt<bool> EnterDirectoriesRecursively("r", cl::desc("Recursively process files within directories, (but follow only top-level symlinks unless -R)."), cl::cat(LegacyGrepOptions), cl::Grouping);
75static cl::opt<bool> FollowSubdirectorySymlinks("R", cl::desc("Recursively process files within directories, following symlinks at all levels."), cl::cat(LegacyGrepOptions), cl::Grouping);
76static cl::opt<bool> CaseInsensitive("i", cl::desc("Ignore case distinctions in the pattern and the file."), cl::cat(LegacyGrepOptions), cl::Grouping);
77static cl::alias CaseInsensitiveAlisas("ignore-case", cl::desc("Ignore case distinctions in the pattern and the file."), cl::aliasopt(CaseInsensitive));
78
79static cl::list<std::string> regexVector("e", cl::desc("Regular expression"), cl::ZeroOrMore, cl::cat(LegacyGrepOptions));
80static cl::opt<std::string> RegexFilename("f", cl::desc("Take regular expressions (one per line) from a file"), cl::value_desc("regex file"), cl::init(""), cl::cat(LegacyGrepOptions));
81static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""));
82
83static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(1));
84
85static cl::opt<bool> GrepSupport("gs", cl::desc("Grep support. Pipe the output of icgrep into grep. \
86         Gives you colored output + back-referencing capability."), cl::cat(EnhancedGrepOptions));
87
88
89static std::vector<std::string> allFiles;
90//
91// Handler for errors reported through llvm::report_fatal_error.  Report
92// and signal error code 2 (grep convention).
93//
94static void icgrep_error_handler(void *UserData, const std::string &Message,
95                             bool GenCrashDiag) {
96
97    // Modified from LLVM's internal report_fatal_error logic.
98    SmallVector<char, 64> Buffer;
99    raw_svector_ostream OS(Buffer);
100    OS << "icgrep ERROR: " << Message << "\n";
101    StringRef MessageStr = OS.str();
102    ssize_t written = ::write(2, MessageStr.data(), MessageStr.size());
103    (void)written; // If something went wrong, we deliberately just give up.
104
105    // Run the interrupt handlers to make sure any special cleanups get done, in
106    // particular that we remove files registered with RemoveFileOnSignal.
107    llvm::sys::RunInterruptHandlers();
108    exit(2);
109}
110
111static std::string allREs;
112static re::ModeFlagSet globalFlags = 0;
113
114re::RE * get_icgrep_RE() {
115 
116    //std::vector<std::string> regexVector;
117    if (RegexFilename != "") {
118        std::ifstream regexFile(RegexFilename.c_str());
119        std::string r;
120        if (regexFile.is_open()) {
121            while (std::getline(regexFile, r)) {
122                regexVector.push_back(r);
123            }
124            regexFile.close();
125        }
126    }
127   
128    // if there are no regexes specified through -e or -f, the first positional argument
129    // must be a regex, not an input file.
130   
131    if (regexVector.size() == 0) {
132        regexVector.push_back(inputFiles[0]);
133        inputFiles.erase(inputFiles.begin());
134    }
135    if (CaseInsensitive) globalFlags |= re::CASE_INSENSITIVE_MODE_FLAG;
136
137 
138    std::vector<re::RE *> REs;
139    re::RE * re_ast = nullptr;
140    for (unsigned i = 0; i < regexVector.size(); i++) {
141#ifdef FUTURE
142        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags, RegexpSyntax);
143#else
144        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
145#endif
146        REs.push_back(re_ast);
147        allREs += regexVector[i] + "\n";
148    }
149    if (REs.size() > 1) {
150        re_ast = re::makeAlt(REs.begin(), REs.end());
151    }
152    if (WholeWordMatching) {
153        re_ast = re::makeSeq({re::makeWordBoundary(), re_ast, re::makeWordBoundary()});
154    }
155    if (EntireLineMatching) {
156        re_ast = re::makeSeq({re::makeStart(), re_ast, re::makeEnd()});
157    }   
158    return re_ast;
159}
160
161std::string sha1sum(const std::string & str) {
162    char buffer[41];    // 40 hex-digits and the terminating null
163    unsigned int digest[5];     // 160 bits in total
164
165    boost::uuids::detail::sha1 sha1;
166    sha1.process_bytes(str.c_str(), str.size());
167    sha1.get_digest(digest);
168    snprintf(buffer, sizeof(buffer), "%.8x%.8x%.8x%.8x%.8x",
169             digest[0], digest[1], digest[2], digest[3], digest[4]);
170    return std::string(buffer);
171}
172
173std::vector<size_t> total_CountOnly;
174std::mutex count_mutex;
175size_t fileCount;
176void *DoGrep(void *args)
177{
178    size_t fileIdx;
179    GrepEngine * grepEngine = (GrepEngine *)args;
180
181    count_mutex.lock();
182    fileIdx = fileCount;
183    fileCount++;
184    count_mutex.unlock();
185
186    while (fileIdx < allFiles.size()){
187        grepEngine->doGrep(allFiles[fileIdx], fileIdx, CountOnly, total_CountOnly, UTF_16);
188       
189        count_mutex.lock();
190        fileIdx = fileCount;
191        fileCount++;
192        count_mutex.unlock();
193    }
194
195    pthread_exit(NULL);
196}
197
198
199// Returns true if the command line argument shouldn't be passed to icGrep or Grep.
200bool isArgUnwantedForAll(char *argument) {
201    std::vector<std::string> unwantedFlags = {"-gs"};
202    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
203        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
204            return true;
205        }
206    }
207    return false;
208}
209// Filters out the command line strings that shouldn't be passed on to Grep
210bool isArgUnwantedForGrep(char *argument) {
211#ifdef FUTURE
212    std::vector<std::string> unwantedFlags = {"-n", "-P", "-G", "-E", "-PRO"};
213#else
214    std::vector<std::string> unwantedFlags = {"-n"};
215#endif
216
217    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
218        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
219            return true;
220        }
221    }
222
223    for (unsigned i = 0; i < inputFiles.size(); ++i){    // filter out input content files.
224        if (strcmp(argument, inputFiles[i].c_str()) == 0) {
225            return true;
226        }
227    }
228
229    return false;
230}
231// Filters out the command line strings that shouldn't be passed on to IcGrep
232bool isArgUnwantedForIcGrep(char *argument) {
233    bool isUnwanted = false;
234    std::vector<std::string> unwantedFlags = {"-c"};
235
236    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
237        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
238            isUnwanted = true;
239        }
240    }
241
242    return isUnwanted;
243}
244
245/*
246* Constructs a shell command that calls icgrep and then pipes the output to grep.
247* Then executs this shell command using the "system()" function.
248* This allows the output to be colored since all output is piped to grep.
249*/ 
250void pipeIcGrepOutputToGrep(int argc, char *argv[]) {
251    std::string icGrepArguments = "";
252    std::string grepArguments = "";
253
254    // Construct the shell arguments for icgrep and grep
255    // by filtering out the command line arguments passed into this process.
256    for (int i = 1; i < argc; i++) {
257        if (!isArgUnwantedForAll(argv[i])) {
258
259            if (!isArgUnwantedForIcGrep(argv[i])) {
260                // Wrap everything in quotes since the arguments passed into this program had them stripped by bash.
261                icGrepArguments.append("\"");       
262                icGrepArguments.append(argv[i]);
263                icGrepArguments.append("\" ");
264            }
265
266            if (!isArgUnwantedForGrep(argv[i])) {
267                grepArguments.append("\"");
268                grepArguments.append(argv[i]);
269                grepArguments.append("\" ");
270            }
271        }
272    }
273
274#ifdef FUTURE
275    switch (RegexpSyntax) {
276        case re::RE_Syntax::BRE:
277            grepArguments.append("\"-G\" ");
278            break;
279        case re::RE_Syntax::ERE:
280            grepArguments.append("\"-E\" ");
281            break;
282        case re::RE_Syntax::PROSITE:
283            grepArguments.append("\"-PRO\" ");
284            break;
285        case re::RE_Syntax::PCRE:
286            grepArguments.append("\"-P\" ");
287            break;
288        default:
289            //TODO: handle fix string
290            break;
291    }
292#endif
293
294    std::string systemCall = argv[0];
295    systemCall.append(" ");
296    systemCall.append(icGrepArguments);
297    systemCall.append(" ");
298#ifdef FUTURE
299    systemCall.append(" | grep --color=always ");
300#else
301    systemCall.append(" | grep --color=always -P ");
302#endif
303    systemCall.append(grepArguments);
304
305    system(systemCall.c_str());
306}
307
308
309// This is a stub, to be expanded later.
310bool excludeDirectory(boost::filesystem::path dirpath) { return dirpath.filename() == ".svn";}
311
312std::vector<std::string> getFullFileList(cl::list<std::string> & inputFiles) {
313    using namespace boost::filesystem;
314    symlink_option follow_symlink = FollowSubdirectorySymlinks ? symlink_option::recurse : symlink_option::none;
315    std::vector<std::string> expanded_paths;
316    boost::system::error_code errc;
317    if (FollowSubdirectorySymlinks) {
318        EnterDirectoriesRecursively = true;
319    }
320    for (auto & f : inputFiles) {
321        path p(f);
322        if (EnterDirectoriesRecursively && is_directory(p)) {
323            if (!excludeDirectory(p)) {
324                recursive_directory_iterator di(p, follow_symlink, errc), end;
325                if (errc) {
326                    // If we cannot enter the directory, keep it in the list of files.
327                    expanded_paths.push_back(f); 
328                    continue;
329                }
330                while (di != end) {
331                    auto & e = di->path();
332                    if (is_directory(e)) {
333                        if (excludeDirectory(e)) di.no_push();
334                    }
335                    else expanded_paths.push_back(e.string());
336                    di.increment(errc);
337                    if (errc) {
338                        expanded_paths.push_back(e.string()); 
339                    }
340                }
341            }
342        }
343        else expanded_paths.push_back(p.string());
344    }
345    return expanded_paths;
346}
347
348
349int main(int argc, char *argv[]) {
350    llvm::install_fatal_error_handler(&icgrep_error_handler);
351#ifndef USE_LLVM_3_6
352    cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *>{&LegacyGrepOptions, &EnhancedGrepOptions, re::re_toolchain_flags(), pablo::pablo_toolchain_flags(), codegen::codegen_flags()});
353#endif
354    cl::ParseCommandLineOptions(argc, argv);
355#ifdef FUTURE
356    if (RegexpSyntax == re::RE_Syntax::FixedStrings) {
357        llvm::report_fatal_error("Sorry, FixedStrings syntax is not fully supported\n.");
358    }
359#endif
360    re::RE * re_ast = get_icgrep_RE();
361    std::string module_name = "grepcode:" + sha1sum(allREs) + ":" + std::to_string(globalFlags);
362   
363    if (GrepSupport) {  // Calls icgrep again on command line and passes output to grep.
364        pipeIcGrepOutputToGrep(argc, argv);
365        return 0;   // icgrep is called again, so we need to end this process.
366    }
367   
368    GrepEngine grepEngine;
369    grepEngine.grepCodeGen(module_name, re_ast, CountOnly, UTF_16);
370
371    releaseSlabAllocatorMemory();
372   
373    allFiles = getFullFileList(inputFiles);
374   
375    if (FileNamesOnly && NonMatchingFileNamesOnly) {
376        // Strange request: print names of all matching files and all non-matching files: i.e., all of them.
377        // (Although GNU grep prints nothing.)
378        for (auto & f : allFiles) {
379            if (boost::filesystem::exists(f)) {
380                std::cout << f << "\n";
381            } else {
382                std::cerr << "Error: cannot open " << f << " for processing. Skipped.\n";
383            }
384        }
385        exit(0);
386    }
387    if (FileNamesOnly) {
388        llvm::report_fatal_error("Sorry, -l/-files-with-matches not yet supported\n.");
389    }
390    if (NonMatchingFileNamesOnly) {
391        llvm::report_fatal_error("Sorry, -L/-files-without-match not yet supported\n.");
392    }
393   
394    initResult(allFiles);
395    for (unsigned i=0; i < allFiles.size(); ++i){
396        total_CountOnly.push_back(0);
397    }
398
399    if (Threads <= 1) {
400
401        #ifdef PRINT_TIMING_INFORMATION
402        // PAPI_RES_STL, PAPI_STL_CCY, PAPI_FUL_CCY, PAPI_MEM_WCY
403        // PAPI_RES_STL, PAPI_BR_MSP, PAPI_LST_INS, PAPI_L1_TCM
404        papi::PapiCounter<4> papiCounters({PAPI_RES_STL, PAPI_STL_CCY, PAPI_FUL_CCY, PAPI_MEM_WCY});
405        #endif
406        for (unsigned i = 0; i != allFiles.size(); ++i) {
407            #ifdef PRINT_TIMING_INFORMATION
408            papiCounters.start();
409            const timestamp_t execution_start = read_cycle_counter();
410            #endif
411            grepEngine.doGrep(allFiles[i], i, CountOnly, total_CountOnly, UTF_16);
412            #ifdef PRINT_TIMING_INFORMATION
413            const timestamp_t execution_end = read_cycle_counter();
414            papiCounters.stop();
415            std::cerr << "EXECUTION TIME: " << allFiles[i] << ":" << "CYCLES|" << (execution_end - execution_start) << papiCounters << std::endl;
416            #endif
417        }       
418    } else if (Threads > 1) {
419        const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
420        pthread_t threads[numOfThreads];
421
422        for(unsigned long i = 0; i < numOfThreads; ++i){
423            const int rc = pthread_create(&threads[i], NULL, DoGrep, (void *)&grepEngine);
424            if (rc) {
425                llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
426            }
427        }
428
429        for(unsigned i = 0; i < numOfThreads; ++i) {
430            void * status = nullptr;
431            const int rc = pthread_join(threads[i], &status);
432            if (rc) {
433                llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
434            }
435        }
436    }
437   
438    PrintResult(CountOnly, total_CountOnly);
439   
440    return 0;
441}
Note: See TracBrowser for help on using the repository browser.