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

Last change on this file since 5030 was 5030, checked in by cameron, 3 years ago

Restructure regular expression command flags

File size: 8.4 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 <re/re_alt.h>
11#include <re/re_parser.h>
12#include <grep_engine.h>
13#include <fstream>
14#include <string>
15
16#include <boost/uuid/sha1.hpp>
17#include <toolchain.h>
18#include <re/re_toolchain.h>
19#include <mutex>
20
21#include <iostream> // MEEE
22static cl::OptionCategory LegacyGrepOptions("A. Standard Grep Options",
23                                       "These are standard grep options intended for compatibility with typical grep usage.");
24static cl::OptionCategory EnhancedGrepOptions("B. Enhanced Grep Options",
25                                       "These are additional options for icgrep functionality and performance.");
26static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(LegacyGrepOptions));
27static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
28
29static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<regex> <input file ...>"), cl::OneOrMore);
30
31static cl::opt<bool> CaseInsensitive("i", cl::desc("Ignore case distinctions in the pattern and the file."), cl::cat(LegacyGrepOptions));
32
33
34static cl::list<std::string> regexVector("e", cl::desc("Regular expression"), cl::ZeroOrMore, cl::cat(LegacyGrepOptions));
35static 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));
36static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""));
37
38static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(1));
39
40static cl::opt<bool> GrepSupport("gs", cl::desc("Grep support. Pipe the output of icgrep into grep. \
41         Gives you colored output + back-referencing capability."), cl::cat(EnhancedGrepOptions));
42
43
44static std::string allREs;
45static re::ModeFlagSet globalFlags = 0;
46
47re::RE * get_icgrep_RE() {
48 
49    //std::vector<std::string> regexVector;
50    if (RegexFilename != "") {
51        std::ifstream regexFile(RegexFilename.c_str());
52        std::string r;
53        if (regexFile.is_open()) {
54            while (std::getline(regexFile, r)) {
55                regexVector.push_back(r);
56            }
57            regexFile.close();
58        }
59    }
60   
61    // if there are no regexes specified through -e or -f, the first positional argument
62    // must be a regex, not an input file.
63   
64    if (regexVector.size() == 0) {
65        regexVector.push_back(inputFiles[0]);
66        inputFiles.erase(inputFiles.begin());
67    }
68    if (CaseInsensitive) globalFlags |= re::CASE_INSENSITIVE_MODE_FLAG;
69
70 
71    std::vector<re::RE *> REs;
72    re::RE * re_ast = nullptr;
73    for (unsigned i = 0; i < regexVector.size(); i++) {
74        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
75        REs.push_back(re_ast);
76        allREs += regexVector[i] + "\n";
77    }
78    if (REs.size() > 1) {
79        re_ast = re::makeAlt(REs.begin(), REs.end());
80    }
81   
82    return re_ast;
83}
84
85std::string sha1sum(const std::string & str) {
86    char buffer[41];    // 40 hex-digits and the terminating null
87    unsigned int digest[5];     // 160 bits in total
88
89    boost::uuids::detail::sha1 sha1;
90    sha1.process_bytes(str.c_str(), str.size());
91    sha1.get_digest(digest);
92    snprintf(buffer, sizeof(buffer), "%.8x%.8x%.8x%.8x%.8x",
93             digest[0], digest[1], digest[2], digest[3], digest[4]);
94    return std::string(buffer);
95}
96
97std::vector<int> total_CountOnly;
98std::mutex count_mutex;
99size_t fileCount;
100void *DoGrep(void *args)
101{
102    size_t fileIdx;
103    GrepEngine * grepEngine = (GrepEngine *)args;
104
105    count_mutex.lock();
106    fileIdx = fileCount;
107    fileCount++;
108    count_mutex.unlock();
109
110    while (fileIdx < inputFiles.size()){
111        grepEngine->doGrep(inputFiles[fileIdx], fileIdx, CountOnly, total_CountOnly);
112       
113        count_mutex.lock();
114        fileIdx = fileCount;
115        fileCount++;
116        count_mutex.unlock();
117    }
118
119    pthread_exit(NULL);
120}
121
122
123// Returns true if the command line argument shouldn't be passed to icGrep or Grep.
124bool isArgUnwantedForAll(char *argument) {
125
126    bool isUnwated = false;
127    std::vector<std::string> unwantedFlags = {"-gs"};
128
129    for (int i=0; i<unwantedFlags.size(); i++){   
130        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
131            isUnwated = true;
132        }
133    }
134
135    return isUnwated;
136}
137// Filters out the command line strings that shouldn't be passed on to Grep
138bool isArgUnwantedForGrep(char *argument) {
139    bool isUnwated = false;
140    std::vector<std::string> unwantedFlags = {"-n"};
141
142    for (int i = 0; i < unwantedFlags.size(); i++){
143        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
144            isUnwated = true;
145        }
146    }
147
148    for (int i = 0; i < inputFiles.size(); i++){    // filter out input content files.
149        if (strcmp(argument, inputFiles[i].c_str()) == 0) {
150            isUnwated = true;
151        }
152    }
153
154    return isUnwated;
155}
156// Filters out the command line strings that shouldn't be passed on to IcGrep
157bool isArgUnwantedForIcGrep(char *argument) {
158    bool isUnwated = false;
159    std::vector<std::string> unwantedFlags = {"-c"};
160
161    for (int i=0; i<unwantedFlags.size(); i++){
162        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
163            isUnwated = true;
164        }
165    }
166
167    return isUnwated;
168}
169
170/*
171* Constructs a shell command that calls icgrep and then pipes the output to grep.
172* Then executs this shell command using the "system()" function.
173* This allows the output to be colored since all output is piped to grep.
174*/ 
175void pipeIcGrepOutputToGrep(int argc, char *argv[]) {
176    std::string icGrepArguments = "";
177    std::string grepArguments = "";
178
179    // Construct the shell arguments for icgrep and grep
180    // by filtering out the command line arguments passed into this process.
181    for (int i=1; i< argc; i++) {
182        if (!isArgUnwantedForAll(argv[i])) {
183
184            if (!isArgUnwantedForIcGrep(argv[i])) {
185                icGrepArguments.append(argv[i]);
186                icGrepArguments.append(" ");
187            }
188
189            if (!isArgUnwantedForGrep(argv[i])) {
190                grepArguments.append(argv[i]);
191                grepArguments.append(" ");
192            }
193        }
194    }
195
196    std::string systemCall = "./icgrep ";
197    systemCall.append(icGrepArguments);
198    systemCall.append(" ");
199    systemCall.append(" | grep --color=always -P ");
200    systemCall.append(grepArguments);
201    system(systemCall.c_str());
202}
203
204
205int main(int argc, char *argv[]) {
206    cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *>{&LegacyGrepOptions, &EnhancedGrepOptions, re::re_toolchain_flags()});
207    cl::ParseCommandLineOptions(argc, argv);
208   
209    re::RE * re_ast = get_icgrep_RE();
210    std::string module_name = "grepcode:" + sha1sum(allREs) + ":" + std::to_string(globalFlags);
211
212    if (GrepSupport) {  // Calls icgrep again on command line and passes output to grep.
213        pipeIcGrepOutputToGrep(argc, argv);
214        return 0;   // icgrep is called again, so we need to end this process.
215    }
216   
217    GrepEngine grepEngine;
218    grepEngine.grepCodeGen(module_name, re_ast, CountOnly);
219   
220    initResult(inputFiles);
221    for (int i=0; i<inputFiles.size(); i++){
222        total_CountOnly.push_back(0);
223    }
224
225    if (Threads <= 1) {
226        for (unsigned i = 0; i != inputFiles.size(); ++i) {
227            grepEngine.doGrep(inputFiles[i], i, CountOnly, total_CountOnly);
228        }       
229    } else if (Threads > 1) {
230        const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
231        pthread_t threads[numOfThreads];
232
233        for(unsigned long i = 0; i < numOfThreads; ++i){
234            const int rc = pthread_create(&threads[i], NULL, DoGrep, (void *)&grepEngine);
235            if (rc) {
236                throw std::runtime_error("Failed to create thread: code " + std::to_string(rc));
237            }
238        }
239
240        for(unsigned i = 0; i < numOfThreads; ++i) {
241            void * status = nullptr;
242            const int rc = pthread_join(threads[i], &status);
243            if (rc) {
244                throw std::runtime_error("Failed to join thread: code " + std::to_string(rc));
245            }
246        }
247    }
248    PrintResult(CountOnly, total_CountOnly);
249   
250    return 0;
251}
Note: See TracBrowser for help on using the repository browser.